blob: b21dd2beba74fc766846b1c8e66d165e71bf9b22 [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
Jesse Hall399184a2014-03-03 15:42:54 -0800273void Layer::onSidebandStreamChanged() {
274 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
275 // mSidebandStreamChanged was false
276 mFlinger->signalLayerUpdate();
277 }
278}
279
Mathias Agopian67106042013-03-14 19:18:13 -0700280// called with SurfaceFlinger::mStateLock from the drawing thread after
281// the layer has been remove from the current state list (and just before
282// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800283void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800284 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700285 for (const auto& child : mCurrentChildren) {
286 child->onRemoved();
287 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700288}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700289
Mathias Agopian13127d82013-03-05 17:47:11 -0800290// ---------------------------------------------------------------------------
291// set-up
292// ---------------------------------------------------------------------------
293
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700294const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800295 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800296}
297
Mathias Agopianf9d93272009-06-19 17:00:27 -0700298status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800299 PixelFormat format, uint32_t flags)
300{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700301 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700302 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700303
304 // never allow a surface larger than what our underlying GL implementation
305 // can handle.
306 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800307 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700308 return BAD_VALUE;
309 }
310
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700311 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700312
Riley Andrews03414a12014-07-01 14:22:59 -0700313 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700314 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700315 mCurrentOpacity = getOpacityForFormat(format);
316
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800317 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
318 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
319 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700320
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321 return NO_ERROR;
322}
323
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700324sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800325 Mutex::Autolock _l(mLock);
326
327 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700328 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800329
330 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700331
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700332 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800333}
334
Dan Stozab9b08832014-03-13 11:55:57 -0700335sp<IGraphicBufferProducer> Layer::getProducer() const {
336 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700337}
338
Mathias Agopian13127d82013-03-05 17:47:11 -0800339// ---------------------------------------------------------------------------
340// h/w composer set-up
341// ---------------------------------------------------------------------------
342
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800343Rect Layer::getContentCrop() const {
344 // this is the crop rectangle that applies to the buffer
345 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700346 Rect crop;
347 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800348 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700349 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800350 } else if (mActiveBuffer != NULL) {
351 // otherwise we use the whole buffer
352 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700353 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800354 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700355 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700356 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700357 return crop;
358}
359
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700360static Rect reduce(const Rect& win, const Region& exclude) {
361 if (CC_LIKELY(exclude.isEmpty())) {
362 return win;
363 }
364 if (exclude.isRect()) {
365 return win.reduce(exclude.getBounds());
366 }
367 return Region(win).subtract(exclude).getBounds();
368}
369
Robert Carr1f0a16a2016-10-24 16:27:39 -0700370Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
371 const Layer::State& s(getDrawingState());
372 Rect win(s.active.w, s.active.h);
373
374 if (!s.crop.isEmpty()) {
375 win.intersect(s.crop, &win);
376 }
377
378 Transform t = getTransform();
379 win = t.transform(win);
380
381 const sp<Layer>& p = getParent();
382 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
383 // When calculating the parent bounds for purposes of clipping,
384 // we don't need to constrain the parent to its transparent region.
385 // The transparent region is an optimization based on the
386 // buffer contents of the layer, but does not affect the space allocated to
387 // it by policy, and thus children should be allowed to extend into the
388 // parent's transparent region. In fact one of the main uses, is to reduce
389 // buffer allocation size in cases where a child window sits behind a main window
390 // (by marking the hole in the parent window as a transparent region)
391 if (p != nullptr) {
392 Rect bounds = p->computeScreenBounds(false);
393 bounds.intersect(win, &win);
394 }
395
396 if (reduceTransparentRegion) {
397 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
398 win = reduce(win, screenTransparentRegion);
399 }
400
401 return win;
402}
403
Mathias Agopian13127d82013-03-05 17:47:11 -0800404Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700405 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700406 return computeBounds(s.activeTransparentRegion);
407}
408
409Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
410 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800411 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700412
413 if (!s.crop.isEmpty()) {
414 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800415 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700416
417 Rect bounds = win;
418 const auto& p = getParent();
419 if (p != nullptr) {
Robert Carrde9ec442017-02-08 17:43:36 -0800420 // Look in computeScreenBounds recursive call for explanation of
421 // why we pass false here.
422 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700423 }
424
425 Transform t = getTransform();
426 if (p != nullptr) {
427 win = t.transform(win);
428 win.intersect(bounds, &win);
429 win = t.inverse().transform(win);
430 }
431
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700432 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700433 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800434}
435
Robert Carr1f0a16a2016-10-24 16:27:39 -0700436Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700437 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800438 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700439 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800440
441 // apply the projection's clipping to the window crop in
442 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700443 // if there are no window scaling involved, this operation will map to full
444 // pixels in the buffer.
445 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
446 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700447
448 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700449 if (!s.crop.isEmpty()) {
450 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700451 }
452
Robert Carr1f0a16a2016-10-24 16:27:39 -0700453 Transform t = getTransform();
454 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000455 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
456 activeCrop.clear();
457 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700458 if (!s.finalCrop.isEmpty()) {
459 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000460 activeCrop.clear();
461 }
462 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700463 return activeCrop;
464}
465
466gfx::FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
467 // the content crop is the area of the content that gets scaled to the
468 // layer's size. This is in buffer space.
469 gfx::FloatRect crop = getContentCrop().toFloatRect();
470
471 // In addition there is a WM-specified crop we pull from our drawing state.
472 const State& s(getDrawingState());
473
474 // Screen space to make reduction to parent crop clearer.
475 Rect activeCrop = computeInitialCrop(hw);
476 const auto& p = getParent();
477 if (p != nullptr) {
478 auto parentCrop = p->computeInitialCrop(hw);
479 activeCrop.intersect(parentCrop, &activeCrop);
480 }
481 Transform t = getTransform();
482 // Back to layer space to work with the content crop.
483 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800484
Michael Lentine28ea2172014-11-19 18:32:37 -0800485 // This needs to be here as transform.transform(Rect) computes the
486 // transformed rect and then takes the bounding box of the result before
487 // returning. This means
488 // transform.inverse().transform(transform.transform(Rect)) != Rect
489 // in which case we need to make sure the final rect is clipped to the
490 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000491 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
492 activeCrop.clear();
493 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800494
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700495 // subtract the transparent region and snap to the bounds
496 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
497
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000498 // Transform the window crop to match the buffer coordinate system,
499 // which means using the inverse of the current transform set on the
500 // SurfaceFlingerConsumer.
501 uint32_t invTransform = mCurrentTransform;
502 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
503 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700504 * the code below applies the primary display's inverse transform to the
505 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000506 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700507 uint32_t invTransformOrient =
508 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000509 // calculate the inverse transform
510 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
511 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
512 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800513 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000514 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700515 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
516 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800517 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000518
519 int winWidth = s.active.w;
520 int winHeight = s.active.h;
521 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
522 // If the activeCrop has been rotate the ends are rotated but not
523 // the space itself so when transforming ends back we can't rely on
524 // a modification of the axes of rotation. To account for this we
525 // need to reorient the inverse rotation in terms of the current
526 // axes of rotation.
527 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
528 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
529 if (is_h_flipped == is_v_flipped) {
530 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
531 NATIVE_WINDOW_TRANSFORM_FLIP_H;
532 }
533 winWidth = s.active.h;
534 winHeight = s.active.w;
535 }
536 const Rect winCrop = activeCrop.transform(
537 invTransform, s.active.w, s.active.h);
538
539 // below, crop is intersected with winCrop expressed in crop's coordinate space
540 float xScale = crop.getWidth() / float(winWidth);
541 float yScale = crop.getHeight() / float(winHeight);
542
543 float insetL = winCrop.left * xScale;
544 float insetT = winCrop.top * yScale;
545 float insetR = (winWidth - winCrop.right ) * xScale;
546 float insetB = (winHeight - winCrop.bottom) * yScale;
547
548 crop.left += insetL;
549 crop.top += insetT;
550 crop.right -= insetR;
551 crop.bottom -= insetB;
552
Mathias Agopian13127d82013-03-05 17:47:11 -0800553 return crop;
554}
555
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000556#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800557void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000558#else
559void Layer::setGeometry(
560 const sp<const DisplayDevice>& hw,
561 HWComposer::HWCLayerInterface& layer)
562#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700563{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000564#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 const auto hwcId = displayDevice->getHwcDisplayId();
566 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000567#else
568 layer.setDefaultState();
569#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700570
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700571 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 hwcInfo.forceClientComposition = false;
574
575 if (isSecure() && !displayDevice->isSecure()) {
576 hwcInfo.forceClientComposition = true;
577 }
578
579 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000580#else
581 layer.setSkip(false);
582
583 if (isSecure() && !hw->isSecure()) {
584 layer.setSkip(true);
585 }
586#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700587
Mathias Agopian13127d82013-03-05 17:47:11 -0800588 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700589 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000590#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800591 if (!isOpaque(s) || s.alpha != 1.0f) {
592 auto blendMode = mPremultipliedAlpha ?
593 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
594 auto error = hwcLayer->setBlendMode(blendMode);
595 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
596 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
597 to_string(error).c_str(), static_cast<int32_t>(error));
598 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000599#else
600 if (!isOpaque(s) || s.alpha != 0xFF) {
601 layer.setBlending(mPremultipliedAlpha ?
602 HWC_BLENDING_PREMULT :
603 HWC_BLENDING_COVERAGE);
604 }
605#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800606
607 // apply the layer's transform, followed by the display's global transform
608 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700609 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700610 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700611 if (!s.crop.isEmpty()) {
612 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700613 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000614#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000615 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000616#else
617 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
618#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000619 activeCrop.clear();
620 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700621 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800622 // This needs to be here as transform.transform(Rect) computes the
623 // transformed rect and then takes the bounding box of the result before
624 // returning. This means
625 // transform.inverse().transform(transform.transform(Rect)) != Rect
626 // in which case we need to make sure the final rect is clipped to the
627 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000628 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
629 activeCrop.clear();
630 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700631 // mark regions outside the crop as transparent
632 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
633 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
634 s.active.w, s.active.h));
635 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
636 activeCrop.left, activeCrop.bottom));
637 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
638 s.active.w, activeCrop.bottom));
639 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700640
641 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700642 if (!s.finalCrop.isEmpty()) {
643 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000644 frame.clear();
645 }
646 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000647#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000648 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
649 frame.clear();
650 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800651 const Transform& tr(displayDevice->getTransform());
652 Rect transformedFrame = tr.transform(frame);
653 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700654 if (error != HWC2::Error::None) {
655 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
656 mName.string(), transformedFrame.left, transformedFrame.top,
657 transformedFrame.right, transformedFrame.bottom,
658 to_string(error).c_str(), static_cast<int32_t>(error));
659 } else {
660 hwcInfo.displayFrame = transformedFrame;
661 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800662
Dan Stoza71bded52016-10-19 11:10:33 -0700663 gfx::FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800664 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700665 if (error != HWC2::Error::None) {
666 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
667 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
668 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
669 static_cast<int32_t>(error));
670 } else {
671 hwcInfo.sourceCrop = sourceCrop;
672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673
674 error = hwcLayer->setPlaneAlpha(s.alpha);
675 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
676 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
677 static_cast<int32_t>(error));
678
Robert Carrae060832016-11-28 10:51:00 -0800679 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800681 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800682 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500683
684 error = hwcLayer->setInfo(s.type, s.appId);
685 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
686 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000687#else
688 if (!frame.intersect(hw->getViewport(), &frame)) {
689 frame.clear();
690 }
691 const Transform& tr(hw->getTransform());
692 layer.setFrame(tr.transform(frame));
693 layer.setCrop(computeCrop(hw));
694 layer.setPlaneAlpha(s.alpha);
695#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800696
Mathias Agopian29a367b2011-07-12 14:51:45 -0700697 /*
698 * Transformations are applied in this order:
699 * 1) buffer orientation/flip/mirror
700 * 2) state transformation (window manager)
701 * 3) layer orientation (screen orientation)
702 * (NOTE: the matrices are multiplied in reverse order)
703 */
704
705 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700706 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700707
708 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
709 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700710 * the code below applies the primary display's inverse transform to the
711 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700712 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700713 uint32_t invTransform =
714 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700715 // calculate the inverse transform
716 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
717 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
718 NATIVE_WINDOW_TRANSFORM_FLIP_H;
719 }
720 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700721 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700722 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700723
724 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800725 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000726#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 if (orientation & Transform::ROT_INVALID) {
728 // we can only handle simple transformation
729 hwcInfo.forceClientComposition = true;
730 } else {
731 auto transform = static_cast<HWC2::Transform>(orientation);
732 auto error = hwcLayer->setTransform(transform);
733 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
734 "%s (%d)", mName.string(), to_string(transform).c_str(),
735 to_string(error).c_str(), static_cast<int32_t>(error));
736 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000737#else
738 if (orientation & Transform::ROT_INVALID) {
739 // we can only handle simple transformation
740 layer.setSkip(true);
741 } else {
742 layer.setTransform(orientation);
743 }
744#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700745}
746
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000747#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800748void Layer::forceClientComposition(int32_t hwcId) {
749 if (mHwcLayers.count(hwcId) == 0) {
750 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
751 return;
752 }
753
754 mHwcLayers[hwcId].forceClientComposition = true;
755}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000756#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800757
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000758#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
760 // Apply this display's projection's viewport to the visible region
761 // before giving it to the HWC HAL.
762 const Transform& tr = displayDevice->getTransform();
763 const auto& viewport = displayDevice->getViewport();
764 Region visible = tr.transform(visibleRegion.intersect(viewport));
765 auto hwcId = displayDevice->getHwcDisplayId();
766 auto& hwcLayer = mHwcLayers[hwcId].layer;
767 auto error = hwcLayer->setVisibleRegion(visible);
768 if (error != HWC2::Error::None) {
769 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
770 to_string(error).c_str(), static_cast<int32_t>(error));
771 visible.dump(LOG_TAG);
772 }
773
774 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
775 if (error != HWC2::Error::None) {
776 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
777 to_string(error).c_str(), static_cast<int32_t>(error));
778 surfaceDamageRegion.dump(LOG_TAG);
779 }
780
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700781 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700783 setCompositionType(hwcId, HWC2::Composition::Sideband);
784 ALOGV("[%s] Requesting Sideband composition", mName.string());
785 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800786 if (error != HWC2::Error::None) {
787 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
788 mName.string(), mSidebandStream->handle(),
789 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700791 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792 }
793
Dan Stoza0a21df72016-07-20 12:52:38 -0700794 // Client layers
795 if (mHwcLayers[hwcId].forceClientComposition ||
796 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700797 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700799 return;
800 }
801
Dan Stoza0a21df72016-07-20 12:52:38 -0700802 // SolidColor layers
803 if (mActiveBuffer == nullptr) {
804 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700805
806 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700807 error = hwcLayer->setColor({0, 0, 0, 255});
808 if (error != HWC2::Error::None) {
809 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
810 to_string(error).c_str(), static_cast<int32_t>(error));
811 }
Dan Stozac6c89542016-07-27 10:16:52 -0700812
813 // Clear out the transform, because it doesn't make sense absent a
814 // source buffer
815 error = hwcLayer->setTransform(HWC2::Transform::None);
816 if (error != HWC2::Error::None) {
817 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
818 to_string(error).c_str(), static_cast<int32_t>(error));
819 }
820
Dan Stoza0a21df72016-07-20 12:52:38 -0700821 return;
822 }
823
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700824 // Device or Cursor layers
825 if (mPotentialCursor) {
826 ALOGV("[%s] Requesting Cursor composition", mName.string());
827 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828 } else {
829 ALOGV("[%s] Requesting Device composition", mName.string());
830 setCompositionType(hwcId, HWC2::Composition::Device);
831 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700832
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700833 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
834 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
835 if (error != HWC2::Error::None) {
836 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
837 mCurrentState.dataSpace, to_string(error).c_str(),
838 static_cast<int32_t>(error));
839 }
840
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700841 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
842 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
843 if (error != HWC2::Error::None) {
844 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
845 mActiveBuffer->handle, to_string(error).c_str(),
846 static_cast<int32_t>(error));
847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000849#else
850void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
851 HWComposer::HWCLayerInterface& layer) {
852 // we have to set the visible region on every frame because
853 // we currently free it during onLayerDisplayed(), which is called
854 // after HWComposer::commit() -- every frame.
855 // Apply this display's projection's viewport to the visible region
856 // before giving it to the HWC HAL.
857 const Transform& tr = hw->getTransform();
858 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
859 layer.setVisibleRegionScreen(visible);
860 layer.setSurfaceDamage(surfaceDamageRegion);
861 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700862
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000863 if (mSidebandStream.get()) {
864 layer.setSidebandStream(mSidebandStream);
865 } else {
866 // NOTE: buffer can be NULL if the client never drew into this
867 // layer yet, or if we ran out of memory
868 layer.setBuffer(mActiveBuffer);
869 }
870}
871#endif
872
873#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
875 auto hwcId = displayDevice->getHwcDisplayId();
876 if (mHwcLayers.count(hwcId) == 0 ||
877 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
878 return;
879 }
880
881 // This gives us only the "orientation" component of the transform
882 const State& s(getCurrentState());
883
884 // Apply the layer's transform, followed by the display's global transform
885 // Here we're guaranteed that the layer's transform preserves rects
886 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700887 if (!s.crop.isEmpty()) {
888 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800889 }
890 // Subtract the transparent region and snap to the bounds
891 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700892 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700894 if (!s.finalCrop.isEmpty()) {
895 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000896 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897 auto& displayTransform(displayDevice->getTransform());
898 auto position = displayTransform.transform(frame);
899
900 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
901 position.top);
902 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
903 "to (%d, %d): %s (%d)", mName.string(), position.left,
904 position.top, to_string(error).c_str(),
905 static_cast<int32_t>(error));
906}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000907#else
908void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
909 HWComposer::HWCLayerInterface& layer) {
910 int fenceFd = -1;
911
912 // TODO: there is a possible optimization here: we only need to set the
913 // acquire fence the first time a new buffer is acquired on EACH display.
914
915 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
916 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
917 if (fence->isValid()) {
918 fenceFd = fence->dup();
919 if (fenceFd == -1) {
920 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
921 }
922 }
923 }
924 layer.setAcquireFenceFd(fenceFd);
925}
926
927Rect Layer::getPosition(
928 const sp<const DisplayDevice>& hw)
929{
930 // this gives us only the "orientation" component of the transform
931 const State& s(getCurrentState());
932
933 // apply the layer's transform, followed by the display's global transform
934 // here we're guaranteed that the layer's transform preserves rects
935 Rect win(s.active.w, s.active.h);
936 if (!s.crop.isEmpty()) {
937 win.intersect(s.crop, &win);
938 }
939 // subtract the transparent region and snap to the bounds
940 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700941 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000942 frame.intersect(hw->getViewport(), &frame);
943 if (!s.finalCrop.isEmpty()) {
944 frame.intersect(s.finalCrop, &frame);
945 }
946 const Transform& tr(hw->getTransform());
947 return Rect(tr.transform(frame));
948}
949#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700950
Mathias Agopian13127d82013-03-05 17:47:11 -0800951// ---------------------------------------------------------------------------
952// drawing...
953// ---------------------------------------------------------------------------
954
955void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800956 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800957}
958
Dan Stozac7014012014-02-14 15:03:43 -0800959void Layer::draw(const sp<const DisplayDevice>& hw,
960 bool useIdentityTransform) const {
961 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800962}
963
Dan Stozac7014012014-02-14 15:03:43 -0800964void Layer::draw(const sp<const DisplayDevice>& hw) const {
965 onDraw(hw, Region(hw->bounds()), false);
966}
967
968void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
969 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800970{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800971 ATRACE_CALL();
972
Mathias Agopiana67932f2011-04-20 14:20:59 -0700973 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800974 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -0700975 // in fact never been drawn into. This happens frequently with
976 // SurfaceView because the WindowManager can't know when the client
977 // has drawn the first time.
978
979 // If there is nothing under us, we paint the screen in black, otherwise
980 // we just skip this update.
981
982 // figure out if there is something below us
983 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -0700984 bool finished = false;
985 mFlinger->mDrawingState.layersSortedByZ.traverseInZOrder([&](Layer* layer) {
986 if (finished || layer == static_cast<Layer const*>(this)) {
987 finished = true;
988 return;
989 }
Mathias Agopian42977342012-08-05 00:40:46 -0700990 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -0700991 });
Mathias Agopian179169e2010-05-06 20:21:45 -0700992 // if not everything below us is covered, we plug the holes!
993 Region holes(clip.subtract(under));
994 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -0800995 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -0700996 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800997 return;
998 }
Mathias Agopiana67932f2011-04-20 14:20:59 -0700999
Andy McFadden97eba892012-12-11 15:21:45 -08001000 // Bind the current buffer to the GL texture, and wait for it to be
1001 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001002 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1003 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001004 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001005 // Go ahead and draw the buffer anyway; no matter what we do the screen
1006 // is probably going to have something visibly wrong.
1007 }
1008
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001009 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1010
Mathias Agopian875d8e12013-06-07 15:35:48 -07001011 RenderEngine& engine(mFlinger->getRenderEngine());
1012
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001013 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001014 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001015 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001016
1017 // Query the texture matrix given our current filtering mode.
1018 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001019 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1020 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001021
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001022 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1023
1024 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001025 * the code below applies the primary display's inverse transform to
1026 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001027 */
1028
1029 // create a 4x4 transform matrix from the display transform flags
1030 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1031 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1032 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1033
1034 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -07001035 uint32_t transform =
1036 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001037 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
1038 tr = tr * rot90;
1039 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
1040 tr = tr * flipH;
1041 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
1042 tr = tr * flipV;
1043
1044 // calculate the inverse
1045 tr = inverse(tr);
1046
1047 // and finally apply it to the original texture matrix
1048 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1049 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1050 }
1051
Jamie Genniscbb1a952012-05-08 17:05:52 -07001052 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001053 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1054 mTexture.setFiltering(useFiltering);
1055 mTexture.setMatrix(textureMatrix);
1056
1057 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001058 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001059 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001060 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001061 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001062 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001063}
1064
Mathias Agopian13127d82013-03-05 17:47:11 -08001065
Dan Stozac7014012014-02-14 15:03:43 -08001066void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001067 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001068 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001069{
Mathias Agopian19733a32013-08-28 18:13:56 -07001070 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001071 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001072 engine.setupFillWithColor(red, green, blue, alpha);
1073 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001074}
1075
1076void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001077 const sp<const DisplayDevice>& hw) const {
1078 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001079}
1080
Dan Stozac7014012014-02-14 15:03:43 -08001081void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001082 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001083 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001084
Dan Stozac7014012014-02-14 15:03:43 -08001085 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001086
Mathias Agopian13127d82013-03-05 17:47:11 -08001087 /*
1088 * NOTE: the way we compute the texture coordinates here produces
1089 * different results than when we take the HWC path -- in the later case
1090 * the "source crop" is rounded to texel boundaries.
1091 * This can produce significantly different results when the texture
1092 * is scaled by a large amount.
1093 *
1094 * The GL code below is more logical (imho), and the difference with
1095 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001096 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001097 * GL composition when a buffer scaling is applied (maybe with some
1098 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1099 * like more of a hack.
1100 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001101 Rect win(computeBounds());
1102
Robert Carr1f0a16a2016-10-24 16:27:39 -07001103 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001104 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001105 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001106 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001107 win.clear();
1108 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001109 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001110 if (!win.intersect(computeBounds(), &win)) {
1111 win.clear();
1112 }
1113 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001114
Mathias Agopian3f844832013-08-07 21:24:32 -07001115 float left = float(win.left) / float(s.active.w);
1116 float top = float(win.top) / float(s.active.h);
1117 float right = float(win.right) / float(s.active.w);
1118 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001119
Mathias Agopian875d8e12013-06-07 15:35:48 -07001120 // TODO: we probably want to generate the texture coords with the mesh
1121 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001122 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1123 texCoords[0] = vec2(left, 1.0f - top);
1124 texCoords[1] = vec2(left, 1.0f - bottom);
1125 texCoords[2] = vec2(right, 1.0f - bottom);
1126 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001127
Mathias Agopian875d8e12013-06-07 15:35:48 -07001128 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001129 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001130 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001131 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001132}
1133
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001134#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001135void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1136 bool callIntoHwc) {
1137 if (mHwcLayers.count(hwcId) == 0) {
1138 ALOGE("setCompositionType called without a valid HWC layer");
1139 return;
1140 }
1141 auto& hwcInfo = mHwcLayers[hwcId];
1142 auto& hwcLayer = hwcInfo.layer;
1143 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1144 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1145 if (hwcInfo.compositionType != type) {
1146 ALOGV(" actually setting");
1147 hwcInfo.compositionType = type;
1148 if (callIntoHwc) {
1149 auto error = hwcLayer->setCompositionType(type);
1150 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1151 "composition type %s: %s (%d)", mName.string(),
1152 to_string(type).c_str(), to_string(error).c_str(),
1153 static_cast<int32_t>(error));
1154 }
1155 }
1156}
1157
1158HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001159 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1160 // If we're querying the composition type for a display that does not
1161 // have a HWC counterpart, then it will always be Client
1162 return HWC2::Composition::Client;
1163 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001164 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001165 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001166 return HWC2::Composition::Invalid;
1167 }
1168 return mHwcLayers.at(hwcId).compositionType;
1169}
1170
1171void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1172 if (mHwcLayers.count(hwcId) == 0) {
1173 ALOGE("setClearClientTarget called without a valid HWC layer");
1174 return;
1175 }
1176 mHwcLayers[hwcId].clearClientTarget = clear;
1177}
1178
1179bool Layer::getClearClientTarget(int32_t hwcId) const {
1180 if (mHwcLayers.count(hwcId) == 0) {
1181 ALOGE("getClearClientTarget called without a valid HWC layer");
1182 return false;
1183 }
1184 return mHwcLayers.at(hwcId).clearClientTarget;
1185}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001186#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001187
Ruben Brunk1681d952014-06-27 15:51:55 -07001188uint32_t Layer::getProducerStickyTransform() const {
1189 int producerStickyTransform = 0;
1190 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1191 if (ret != OK) {
1192 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1193 strerror(-ret), ret);
1194 return 0;
1195 }
1196 return static_cast<uint32_t>(producerStickyTransform);
1197}
1198
Dan Stozac5da2712016-07-20 15:38:12 -07001199bool Layer::latchUnsignaledBuffers() {
1200 static bool propertyLoaded = false;
1201 static bool latch = false;
1202 static std::mutex mutex;
1203 std::lock_guard<std::mutex> lock(mutex);
1204 if (!propertyLoaded) {
1205 char value[PROPERTY_VALUE_MAX] = {};
1206 property_get("debug.sf.latch_unsignaled", value, "0");
1207 latch = atoi(value);
1208 propertyLoaded = true;
1209 }
1210 return latch;
1211}
1212
Dan Stozacac35382016-01-27 12:21:06 -08001213uint64_t Layer::getHeadFrameNumber() const {
1214 Mutex::Autolock lock(mQueueItemLock);
1215 if (!mQueueItems.empty()) {
1216 return mQueueItems[0].mFrameNumber;
1217 } else {
1218 return mCurrentFrameNumber;
1219 }
1220}
1221
Dan Stoza1ce65812016-06-15 16:26:27 -07001222bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001223#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001224 if (latchUnsignaledBuffers()) {
1225 return true;
1226 }
1227
Dan Stoza1ce65812016-06-15 16:26:27 -07001228 Mutex::Autolock lock(mQueueItemLock);
1229 if (mQueueItems.empty()) {
1230 return true;
1231 }
1232 if (mQueueItems[0].mIsDroppable) {
1233 // Even though this buffer's fence may not have signaled yet, it could
1234 // be replaced by another buffer before it has a chance to, which means
1235 // that it's possible to get into a situation where a buffer is never
1236 // able to be latched. To avoid this, grab this buffer anyway.
1237 return true;
1238 }
1239 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001240#else
1241 return true;
1242#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001243}
1244
Dan Stozacac35382016-01-27 12:21:06 -08001245bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1246 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1247 // Don't bother with a SyncPoint, since we've already latched the
1248 // relevant frame
1249 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001250 }
1251
Dan Stozacac35382016-01-27 12:21:06 -08001252 Mutex::Autolock lock(mLocalSyncPointMutex);
1253 mLocalSyncPoints.push_back(point);
1254 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001255}
1256
Mathias Agopian13127d82013-03-05 17:47:11 -08001257void Layer::setFiltering(bool filtering) {
1258 mFiltering = filtering;
1259}
1260
1261bool Layer::getFiltering() const {
1262 return mFiltering;
1263}
1264
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001265// As documented in libhardware header, formats in the range
1266// 0x100 - 0x1FF are specific to the HAL implementation, and
1267// are known to have no alpha channel
1268// TODO: move definition for device-specific range into
1269// hardware.h, instead of using hard-coded values here.
1270#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1271
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001272bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001273 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1274 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001275 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001276 switch (format) {
1277 case HAL_PIXEL_FORMAT_RGBA_8888:
1278 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001279 case HAL_PIXEL_FORMAT_RGBA_FP16:
Mathias Agopiandd533712013-07-26 15:31:39 -07001280 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001281 }
1282 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001283 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001284}
1285
Mathias Agopian13127d82013-03-05 17:47:11 -08001286// ----------------------------------------------------------------------------
1287// local state
1288// ----------------------------------------------------------------------------
1289
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001290static void boundPoint(vec2* point, const Rect& crop) {
1291 if (point->x < crop.left) {
1292 point->x = crop.left;
1293 }
1294 if (point->x > crop.right) {
1295 point->x = crop.right;
1296 }
1297 if (point->y < crop.top) {
1298 point->y = crop.top;
1299 }
1300 if (point->y > crop.bottom) {
1301 point->y = crop.bottom;
1302 }
1303}
1304
Dan Stozac7014012014-02-14 15:03:43 -08001305void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1306 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001307{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001308 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001309 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001310 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001311 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001312
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001313 vec2 lt = vec2(win.left, win.top);
1314 vec2 lb = vec2(win.left, win.bottom);
1315 vec2 rb = vec2(win.right, win.bottom);
1316 vec2 rt = vec2(win.right, win.top);
1317
Robert Carr1f0a16a2016-10-24 16:27:39 -07001318 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001319 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001320 lt = layerTransform.transform(lt);
1321 lb = layerTransform.transform(lb);
1322 rb = layerTransform.transform(rb);
1323 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001324 }
1325
Robert Carrb5d3d262016-03-25 15:08:13 -07001326 if (!s.finalCrop.isEmpty()) {
1327 boundPoint(&lt, s.finalCrop);
1328 boundPoint(&lb, s.finalCrop);
1329 boundPoint(&rb, s.finalCrop);
1330 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001331 }
1332
Mathias Agopianff2ed702013-09-01 21:36:12 -07001333 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001334 position[0] = hwTransform.transform(lt);
1335 position[1] = hwTransform.transform(lb);
1336 position[2] = hwTransform.transform(rb);
1337 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001338 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001339 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001340 }
1341}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001342
Andy McFadden4125a4f2014-01-29 17:17:11 -08001343bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001344{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001345 // if we don't have a buffer yet, we're translucent regardless of the
1346 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001347 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001348 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001349 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001350
1351 // if the layer has the opaque flag, then we're always opaque,
1352 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001353 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001354}
1355
Dan Stoza23116082015-06-18 14:58:39 -07001356bool Layer::isSecure() const
1357{
1358 const Layer::State& s(mDrawingState);
1359 return (s.flags & layer_state_t::eLayerSecure);
1360}
1361
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001362bool Layer::isProtected() const
1363{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001364 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001365 return (activeBuffer != 0) &&
1366 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1367}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001368
Mathias Agopian13127d82013-03-05 17:47:11 -08001369bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001370 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001371}
1372
1373bool Layer::isCropped() const {
1374 return !mCurrentCrop.isEmpty();
1375}
1376
1377bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1378 return mNeedsFiltering || hw->needsFiltering();
1379}
1380
1381void Layer::setVisibleRegion(const Region& visibleRegion) {
1382 // always called from main thread
1383 this->visibleRegion = visibleRegion;
1384}
1385
1386void Layer::setCoveredRegion(const Region& coveredRegion) {
1387 // always called from main thread
1388 this->coveredRegion = coveredRegion;
1389}
1390
1391void Layer::setVisibleNonTransparentRegion(const Region&
1392 setVisibleNonTransparentRegion) {
1393 // always called from main thread
1394 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1395}
1396
1397// ----------------------------------------------------------------------------
1398// transaction
1399// ----------------------------------------------------------------------------
1400
Dan Stoza7dde5992015-05-22 09:51:44 -07001401void Layer::pushPendingState() {
1402 if (!mCurrentState.modified) {
1403 return;
1404 }
1405
Dan Stoza7dde5992015-05-22 09:51:44 -07001406 // If this transaction is waiting on the receipt of a frame, generate a sync
1407 // point and send it to the remote layer.
1408 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001409 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1410 sp<Handle> handle = nullptr;
1411 sp<Layer> handleLayer = nullptr;
1412 if (strongBinder != nullptr) {
1413 handle = static_cast<Handle*>(strongBinder.get());
1414 handleLayer = handle->owner.promote();
1415 }
1416 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001417 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1418 // If we can't promote the layer we are intended to wait on,
1419 // then it is expired or otherwise invalid. Allow this transaction
1420 // to be applied as per normal (no synchronization).
1421 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001422 } else {
1423 auto syncPoint = std::make_shared<SyncPoint>(
1424 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001425 if (handleLayer->addSyncPoint(syncPoint)) {
1426 mRemoteSyncPoints.push_back(std::move(syncPoint));
1427 } else {
1428 // We already missed the frame we're supposed to synchronize
1429 // on, so go ahead and apply the state update
1430 mCurrentState.handle = nullptr;
1431 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001432 }
1433
Dan Stoza7dde5992015-05-22 09:51:44 -07001434 // Wake us up to check if the frame has been received
1435 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001436 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001437 }
1438 mPendingStates.push_back(mCurrentState);
1439}
1440
Pablo Ceballos05289c22016-04-14 15:49:55 -07001441void Layer::popPendingState(State* stateToCommit) {
1442 auto oldFlags = stateToCommit->flags;
1443 *stateToCommit = mPendingStates[0];
1444 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1445 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001446
1447 mPendingStates.removeAt(0);
1448}
1449
Pablo Ceballos05289c22016-04-14 15:49:55 -07001450bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001451 bool stateUpdateAvailable = false;
1452 while (!mPendingStates.empty()) {
1453 if (mPendingStates[0].handle != nullptr) {
1454 if (mRemoteSyncPoints.empty()) {
1455 // If we don't have a sync point for this, apply it anyway. It
1456 // will be visually wrong, but it should keep us from getting
1457 // into too much trouble.
1458 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001459 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001460 stateUpdateAvailable = true;
1461 continue;
1462 }
1463
Dan Stozacac35382016-01-27 12:21:06 -08001464 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1465 mPendingStates[0].frameNumber) {
1466 ALOGE("[%s] Unexpected sync point frame number found",
1467 mName.string());
1468
1469 // Signal our end of the sync point and then dispose of it
1470 mRemoteSyncPoints.front()->setTransactionApplied();
1471 mRemoteSyncPoints.pop_front();
1472 continue;
1473 }
1474
Dan Stoza7dde5992015-05-22 09:51:44 -07001475 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1476 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001477 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001478 stateUpdateAvailable = true;
1479
1480 // Signal our end of the sync point and then dispose of it
1481 mRemoteSyncPoints.front()->setTransactionApplied();
1482 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001483 } else {
1484 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001485 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001486 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001487 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001488 stateUpdateAvailable = true;
1489 }
1490 }
1491
1492 // If we still have pending updates, wake SurfaceFlinger back up and point
1493 // it at this layer so we can process them
1494 if (!mPendingStates.empty()) {
1495 setTransactionFlags(eTransactionNeeded);
1496 mFlinger->setTransactionFlags(eTraversalNeeded);
1497 }
1498
1499 mCurrentState.modified = false;
1500 return stateUpdateAvailable;
1501}
1502
1503void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001504 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001505 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001506 Mutex::Autolock lock(mLocalSyncPointMutex);
1507 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001508 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001509 point->setFrameAvailable();
1510 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001511 }
1512}
1513
Mathias Agopian13127d82013-03-05 17:47:11 -08001514uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001515 ATRACE_CALL();
1516
Dan Stoza7dde5992015-05-22 09:51:44 -07001517 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001518 Layer::State c = getCurrentState();
1519 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001520 return 0;
1521 }
1522
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001523 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001524
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001525 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1526 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001527
1528 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001529 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001530 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001531 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001532 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001533 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001534 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001535 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001536 this, getName().string(), mCurrentTransform,
1537 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001538 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001539 c.crop.left,
1540 c.crop.top,
1541 c.crop.right,
1542 c.crop.bottom,
1543 c.crop.getWidth(),
1544 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001545 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001546 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001547 s.crop.left,
1548 s.crop.top,
1549 s.crop.right,
1550 s.crop.bottom,
1551 s.crop.getWidth(),
1552 s.crop.getHeight(),
1553 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001554
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001555 // record the new size, form this point on, when the client request
1556 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001557 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001558 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001559 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001560
Robert Carr82364e32016-05-15 11:27:47 -07001561 const bool resizePending = (c.requested.w != c.active.w) ||
1562 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001563 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001564 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001565 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001566 // if we have a pending resize, unless we are in fixed-size mode.
1567 // the drawing state will be updated only once we receive a buffer
1568 // with the correct size.
1569 //
1570 // in particular, we want to make sure the clip (which is part
1571 // of the geometry state) is latched together with the size but is
1572 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001573 //
1574 // If a sideband stream is attached, however, we want to skip this
1575 // optimization so that transactions aren't missed when a buffer
1576 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001577
1578 flags |= eDontUpdateGeometryState;
1579 }
1580 }
1581
Mathias Agopian13127d82013-03-05 17:47:11 -08001582 // always set active to requested, unless we're asked not to
1583 // this is used by Layer, which special cases resizes.
1584 if (flags & eDontUpdateGeometryState) {
1585 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001586 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001587 if (mFreezePositionUpdates) {
1588 float tx = c.active.transform.tx();
1589 float ty = c.active.transform.ty();
1590 c.active = c.requested;
1591 c.active.transform.set(tx, ty);
1592 editCurrentState.active = c.active;
1593 } else {
1594 editCurrentState.active = editCurrentState.requested;
1595 c.active = c.requested;
1596 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001597 }
1598
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001599 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001600 // invalidate and recompute the visible regions if needed
1601 flags |= Layer::eVisibleRegion;
1602 }
1603
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001604 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001605 // invalidate and recompute the visible regions if needed
1606 flags |= eVisibleRegion;
1607 this->contentDirty = true;
1608
1609 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001610 const uint8_t type = c.active.transform.getType();
1611 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001612 (type >= Transform::SCALE));
1613 }
1614
Dan Stozac8145172016-04-28 16:29:06 -07001615 // If the layer is hidden, signal and clear out all local sync points so
1616 // that transactions for layers depending on this layer's frames becoming
1617 // visible are not blocked
1618 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001619 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001620 }
1621
Mathias Agopian13127d82013-03-05 17:47:11 -08001622 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001623 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001624 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001625}
1626
Pablo Ceballos05289c22016-04-14 15:49:55 -07001627void Layer::commitTransaction(const State& stateToCommit) {
1628 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001629}
1630
Mathias Agopian13127d82013-03-05 17:47:11 -08001631uint32_t Layer::getTransactionFlags(uint32_t flags) {
1632 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1633}
1634
1635uint32_t Layer::setTransactionFlags(uint32_t flags) {
1636 return android_atomic_or(flags, &mTransactionFlags);
1637}
1638
Robert Carr82364e32016-05-15 11:27:47 -07001639bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001640 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001641 return false;
1642 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001643
1644 // We update the requested and active position simultaneously because
1645 // we want to apply the position portion of the transform matrix immediately,
1646 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001647 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001648 if (immediate && !mFreezePositionUpdates) {
1649 mCurrentState.active.transform.set(x, y);
1650 }
1651 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001652
Dan Stoza7dde5992015-05-22 09:51:44 -07001653 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001654 setTransactionFlags(eTransactionNeeded);
1655 return true;
1656}
Robert Carr82364e32016-05-15 11:27:47 -07001657
Robert Carr1f0a16a2016-10-24 16:27:39 -07001658bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1659 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1660 if (idx < 0) {
1661 return false;
1662 }
1663 if (childLayer->setLayer(z)) {
1664 mCurrentChildren.removeAt(idx);
1665 mCurrentChildren.add(childLayer);
1666 }
1667 return true;
1668}
1669
Robert Carrae060832016-11-28 10:51:00 -08001670bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001671 if (mCurrentState.z == z)
1672 return false;
1673 mCurrentState.sequence++;
1674 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001675 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001676 setTransactionFlags(eTransactionNeeded);
1677 return true;
1678}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001679
Mathias Agopian13127d82013-03-05 17:47:11 -08001680bool Layer::setSize(uint32_t w, uint32_t h) {
1681 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1682 return false;
1683 mCurrentState.requested.w = w;
1684 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001685 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001686 setTransactionFlags(eTransactionNeeded);
1687 return true;
1688}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001689#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001691#else
1692bool Layer::setAlpha(uint8_t alpha) {
1693#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001694 if (mCurrentState.alpha == alpha)
1695 return false;
1696 mCurrentState.sequence++;
1697 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001698 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001699 setTransactionFlags(eTransactionNeeded);
1700 return true;
1701}
1702bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1703 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001704 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001705 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001706 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001707 setTransactionFlags(eTransactionNeeded);
1708 return true;
1709}
1710bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001711 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001712 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001713 setTransactionFlags(eTransactionNeeded);
1714 return true;
1715}
1716bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1717 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1718 if (mCurrentState.flags == newFlags)
1719 return false;
1720 mCurrentState.sequence++;
1721 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001722 mCurrentState.mask = mask;
1723 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001724 setTransactionFlags(eTransactionNeeded);
1725 return true;
1726}
Robert Carr99e27f02016-06-16 15:18:02 -07001727
1728bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001729 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001730 return false;
1731 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001732 mCurrentState.requestedCrop = crop;
1733 if (immediate) {
1734 mCurrentState.crop = crop;
1735 }
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}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001740bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001741 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001742 return false;
1743 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001744 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001745 mCurrentState.modified = true;
1746 setTransactionFlags(eTransactionNeeded);
1747 return true;
1748}
Mathias Agopian13127d82013-03-05 17:47:11 -08001749
Robert Carrc3574f72016-03-24 12:19:32 -07001750bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1751 if (scalingMode == mOverrideScalingMode)
1752 return false;
1753 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001754 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001755 return true;
1756}
1757
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001758void Layer::setInfo(uint32_t type, uint32_t appId) {
1759 mCurrentState.appId = appId;
1760 mCurrentState.type = type;
1761 mCurrentState.modified = true;
1762 setTransactionFlags(eTransactionNeeded);
1763}
1764
Robert Carrc3574f72016-03-24 12:19:32 -07001765uint32_t Layer::getEffectiveScalingMode() const {
1766 if (mOverrideScalingMode >= 0) {
1767 return mOverrideScalingMode;
1768 }
1769 return mCurrentScalingMode;
1770}
1771
Mathias Agopian13127d82013-03-05 17:47:11 -08001772bool Layer::setLayerStack(uint32_t layerStack) {
1773 if (mCurrentState.layerStack == layerStack)
1774 return false;
1775 mCurrentState.sequence++;
1776 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001777 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001778 setTransactionFlags(eTransactionNeeded);
1779 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001780}
1781
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001782bool Layer::setDataSpace(android_dataspace dataSpace) {
1783 if (mCurrentState.dataSpace == dataSpace)
1784 return false;
1785 mCurrentState.sequence++;
1786 mCurrentState.dataSpace = dataSpace;
1787 mCurrentState.modified = true;
1788 setTransactionFlags(eTransactionNeeded);
1789 return true;
1790}
1791
Robert Carr1f0a16a2016-10-24 16:27:39 -07001792uint32_t Layer::getLayerStack() const {
1793 auto p = getParent();
1794 if (p == nullptr) {
1795 return getDrawingState().layerStack;
1796 }
1797 return p->getLayerStack();
1798}
1799
Dan Stoza7dde5992015-05-22 09:51:44 -07001800void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1801 uint64_t frameNumber) {
1802 mCurrentState.handle = handle;
1803 mCurrentState.frameNumber = frameNumber;
1804 // We don't set eTransactionNeeded, because just receiving a deferral
1805 // request without any other state updates shouldn't actually induce a delay
1806 mCurrentState.modified = true;
1807 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001808 mCurrentState.handle = nullptr;
1809 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001810 mCurrentState.modified = false;
1811}
1812
Dan Stozaee44edd2015-03-23 15:50:23 -07001813void Layer::useSurfaceDamage() {
1814 if (mFlinger->mForceFullDamage) {
1815 surfaceDamageRegion = Region::INVALID_REGION;
1816 } else {
1817 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1818 }
1819}
1820
1821void Layer::useEmptyDamage() {
1822 surfaceDamageRegion.clear();
1823}
1824
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001825// ----------------------------------------------------------------------------
1826// pageflip handling...
1827// ----------------------------------------------------------------------------
1828
Dan Stoza6b9454d2014-11-07 16:00:59 -08001829bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001830 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001831 return true;
1832 }
1833
Dan Stoza6b9454d2014-11-07 16:00:59 -08001834 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001835 if (mQueueItems.empty()) {
1836 return false;
1837 }
1838 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001839 nsecs_t expectedPresent =
1840 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001841
1842 // Ignore timestamps more than a second in the future
1843 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1844 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1845 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1846 expectedPresent);
1847
1848 bool isDue = timestamp < expectedPresent;
1849 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001850}
1851
Brian Andersond6927fb2016-07-23 23:37:30 -07001852bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1853 if (mBufferLatched) {
1854 Mutex::Autolock lock(mFrameEventHistoryMutex);
1855 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1856 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001857 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001858 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001859}
1860
Brian Anderson3d4039d2016-09-23 16:31:30 -07001861bool Layer::onPostComposition(
1862 const std::shared_ptr<FenceTime>& glDoneFence,
1863 const std::shared_ptr<FenceTime>& presentFence,
1864 const std::shared_ptr<FenceTime>& retireFence) {
1865 mAcquireTimeline.updateSignalTimes();
1866 mReleaseTimeline.updateSignalTimes();
1867
Brian Andersond6927fb2016-07-23 23:37:30 -07001868 // mFrameLatencyNeeded is true when a new frame was latched for the
1869 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001870 if (!mFrameLatencyNeeded)
1871 return false;
1872
Fabien Sanglard28e98082016-12-05 10:19:46 -08001873 // Update mFrameEventHistory.
1874 {
1875 Mutex::Autolock lock(mFrameEventHistoryMutex);
1876 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001877 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001878 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1879 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001880 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001881
1882 // Update mFrameTracker.
1883 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1884 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1885
Brian Anderson3d4039d2016-09-23 16:31:30 -07001886 std::shared_ptr<FenceTime> frameReadyFence =
1887 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001888 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001889 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001890 } else {
1891 // There was no fence for this frame, so assume that it was ready
1892 // to be presented at the desired present time.
1893 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1894 }
1895
Brian Anderson3d4039d2016-09-23 16:31:30 -07001896 if (presentFence->isValid()) {
1897 mFrameTracker.setActualPresentFence(
1898 std::shared_ptr<FenceTime>(presentFence));
1899 } else if (retireFence->isValid()) {
1900 mFrameTracker.setActualPresentFence(
1901 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001902 } else {
1903 // The HWC doesn't support present fences, so use the refresh
1904 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001905 mFrameTracker.setActualPresentTime(
1906 mFlinger->getHwComposer().getRefreshTimestamp(
1907 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001908 }
1909
1910 mFrameTracker.advanceFrame();
1911 mFrameLatencyNeeded = false;
1912 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001913}
1914
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001915#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07001916void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001918 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001919 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001920 mReleaseTimeline.push(releaseFenceTime);
1921
1922 Mutex::Autolock lock(mFrameEventHistoryMutex);
1923 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07001924 mPreviousFrameNumber, dequeueReadyTime, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001926#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927
Robert Carr1f0a16a2016-10-24 16:27:39 -07001928bool Layer::isHiddenByPolicy() const {
1929 const Layer::State& s(mDrawingState);
1930 const auto& parent = getParent();
1931 if (parent != nullptr && parent->isHiddenByPolicy()) {
1932 return true;
1933 }
1934 return s.flags & layer_state_t::eLayerHidden;
1935}
1936
Mathias Agopianda27af92012-09-13 18:17:13 -07001937bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001938 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001939#ifdef USE_HWC2
Robert Carr1f0a16a2016-10-24 16:27:39 -07001940 return !(isHiddenByPolicy()) && s.alpha > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001942#else
Robert Carr1f0a16a2016-10-24 16:27:39 -07001943 return !(isHiddenByPolicy()) && s.alpha
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001944 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1945#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001946}
1947
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001948bool Layer::allTransactionsSignaled() {
1949 auto headFrameNumber = getHeadFrameNumber();
1950 bool matchingFramesFound = false;
1951 bool allTransactionsApplied = true;
1952 Mutex::Autolock lock(mLocalSyncPointMutex);
1953
1954 for (auto& point : mLocalSyncPoints) {
1955 if (point->getFrameNumber() > headFrameNumber) {
1956 break;
1957 }
1958 matchingFramesFound = true;
1959
1960 if (!point->frameIsAvailable()) {
1961 // We haven't notified the remote layer that the frame for
1962 // this point is available yet. Notify it now, and then
1963 // abort this attempt to latch.
1964 point->setFrameAvailable();
1965 allTransactionsApplied = false;
1966 break;
1967 }
1968
1969 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1970 }
1971 return !matchingFramesFound || allTransactionsApplied;
1972}
1973
Brian Andersond6927fb2016-07-23 23:37:30 -07001974Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001976 ATRACE_CALL();
1977
Jesse Hall399184a2014-03-03 15:42:54 -08001978 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1979 // mSidebandStreamChanged was true
1980 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07001981 if (mSidebandStream != NULL) {
1982 setTransactionFlags(eTransactionNeeded);
1983 mFlinger->setTransactionFlags(eTraversalNeeded);
1984 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07001985 recomputeVisibleRegions = true;
1986
1987 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001988 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08001989 }
1990
Mathias Agopian4fec8732012-06-29 14:12:52 -07001991 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07001992 if (mQueuedFrames <= 0 && !mAutoRefresh) {
1993 return outDirtyRegion;
1994 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001995
Fabien Sanglard223eb912016-10-13 10:15:06 -07001996 // if we've already called updateTexImage() without going through
1997 // a composition step, we have to skip this layer at this point
1998 // because we cannot call updateTeximage() without a corresponding
1999 // compositionComplete() call.
2000 // we'll trigger an update in onPreComposition().
2001 if (mRefreshPending) {
2002 return outDirtyRegion;
2003 }
2004
2005 // If the head buffer's acquire fence hasn't signaled yet, return and
2006 // try again later
2007 if (!headFenceHasSignaled()) {
2008 mFlinger->signalLayerUpdate();
2009 return outDirtyRegion;
2010 }
2011
2012 // Capture the old state of the layer for comparisons later
2013 const State& s(getDrawingState());
2014 const bool oldOpacity = isOpaque(s);
2015 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2016
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002017 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002018 mFlinger->signalLayerUpdate();
2019 return outDirtyRegion;
2020 }
2021
2022 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2023 // of the buffer queue isn't modified when the buffer queue is returning
2024 // BufferItem's that weren't actually queued. This can happen in shared
2025 // buffer mode.
2026 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002027 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2028 getProducerStickyTransform() != 0, mName.string(),
2029 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002030 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2031 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2032 mLastFrameNumberReceived);
2033 if (updateResult == BufferQueue::PRESENT_LATER) {
2034 // Producer doesn't want buffer to be displayed yet. Signal a
2035 // layer update so we check again at the next opportunity.
2036 mFlinger->signalLayerUpdate();
2037 return outDirtyRegion;
2038 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2039 // If the buffer has been rejected, remove it from the shadow queue
2040 // and return early
2041 if (queuedBuffer) {
2042 Mutex::Autolock lock(mQueueItemLock);
2043 mQueueItems.removeAt(0);
2044 android_atomic_dec(&mQueuedFrames);
2045 }
2046 return outDirtyRegion;
2047 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2048 // This can occur if something goes wrong when trying to create the
2049 // EGLImage for this buffer. If this happens, the buffer has already
2050 // been released, so we need to clean up the queue and bug out
2051 // early.
2052 if (queuedBuffer) {
2053 Mutex::Autolock lock(mQueueItemLock);
2054 mQueueItems.clear();
2055 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002056 }
2057
Fabien Sanglard223eb912016-10-13 10:15:06 -07002058 // Once we have hit this state, the shadow queue may no longer
2059 // correctly reflect the incoming BufferQueue's contents, so even if
2060 // updateTexImage starts working, the only safe course of action is
2061 // to continue to ignore updates.
2062 mUpdateTexImageFailed = true;
2063
2064 return outDirtyRegion;
2065 }
2066
2067 if (queuedBuffer) {
2068 // Autolock scope
2069 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2070
2071 Mutex::Autolock lock(mQueueItemLock);
2072
2073 // Remove any stale buffers that have been dropped during
2074 // updateTexImage
2075 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2076 mQueueItems.removeAt(0);
2077 android_atomic_dec(&mQueuedFrames);
2078 }
2079
2080 mQueueItems.removeAt(0);
2081 }
2082
2083
2084 // Decrement the queued-frames count. Signal another event if we
2085 // have more frames pending.
2086 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2087 || mAutoRefresh) {
2088 mFlinger->signalLayerUpdate();
2089 }
2090
Fabien Sanglard223eb912016-10-13 10:15:06 -07002091 // update the active buffer
2092 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
2093 if (mActiveBuffer == NULL) {
2094 // this can only happen if the very first buffer was rejected.
2095 return outDirtyRegion;
2096 }
2097
Brian Andersond6927fb2016-07-23 23:37:30 -07002098 mBufferLatched = true;
2099 mPreviousFrameNumber = mCurrentFrameNumber;
2100 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2101
2102 {
2103 Mutex::Autolock lock(mFrameEventHistoryMutex);
2104 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2105#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002106 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002107 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002108 mReleaseTimeline.push(releaseFenceTime);
2109 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07002110 mPreviousFrameNumber, latchTime, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07002111#endif
2112 }
2113
Fabien Sanglard223eb912016-10-13 10:15:06 -07002114 mRefreshPending = true;
2115 mFrameLatencyNeeded = true;
2116 if (oldActiveBuffer == NULL) {
2117 // the first time we receive a buffer, we need to trigger a
2118 // geometry invalidation.
2119 recomputeVisibleRegions = true;
2120 }
2121
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002122 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2123
Fabien Sanglard223eb912016-10-13 10:15:06 -07002124 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2125 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2126 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2127 if ((crop != mCurrentCrop) ||
2128 (transform != mCurrentTransform) ||
2129 (scalingMode != mCurrentScalingMode))
2130 {
2131 mCurrentCrop = crop;
2132 mCurrentTransform = transform;
2133 mCurrentScalingMode = scalingMode;
2134 recomputeVisibleRegions = true;
2135 }
2136
2137 if (oldActiveBuffer != NULL) {
2138 uint32_t bufWidth = mActiveBuffer->getWidth();
2139 uint32_t bufHeight = mActiveBuffer->getHeight();
2140 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2141 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002142 recomputeVisibleRegions = true;
2143 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002144 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002145
Fabien Sanglard223eb912016-10-13 10:15:06 -07002146 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2147 if (oldOpacity != isOpaque(s)) {
2148 recomputeVisibleRegions = true;
2149 }
Dan Stozacac35382016-01-27 12:21:06 -08002150
Fabien Sanglard223eb912016-10-13 10:15:06 -07002151 // Remove any sync points corresponding to the buffer which was just
2152 // latched
2153 {
2154 Mutex::Autolock lock(mLocalSyncPointMutex);
2155 auto point = mLocalSyncPoints.begin();
2156 while (point != mLocalSyncPoints.end()) {
2157 if (!(*point)->frameIsAvailable() ||
2158 !(*point)->transactionIsApplied()) {
2159 // This sync point must have been added since we started
2160 // latching. Don't drop it yet.
2161 ++point;
2162 continue;
2163 }
2164
2165 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2166 point = mLocalSyncPoints.erase(point);
2167 } else {
2168 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002169 }
2170 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002171 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002172
2173 // FIXME: postedRegion should be dirty & bounds
2174 Region dirtyRegion(Rect(s.active.w, s.active.h));
2175
2176 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002178
Mathias Agopian4fec8732012-06-29 14:12:52 -07002179 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180}
2181
Mathias Agopiana67932f2011-04-20 14:20:59 -07002182uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002183{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002184 // TODO: should we do something special if mSecure is set?
2185 if (mProtectedByApp) {
2186 // need a hardware-protected path to external video sink
2187 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002188 }
Riley Andrews03414a12014-07-01 14:22:59 -07002189 if (mPotentialCursor) {
2190 usage |= GraphicBuffer::USAGE_CURSOR;
2191 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002192 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002193 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002194}
2195
Mathias Agopian84300952012-11-21 16:02:13 -08002196void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002197 uint32_t orientation = 0;
2198 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002199 // The transform hint is used to improve performance, but we can
2200 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002201 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002202 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002203 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002204 if (orientation & Transform::ROT_INVALID) {
2205 orientation = 0;
2206 }
2207 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002208 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002209}
2210
Mathias Agopian13127d82013-03-05 17:47:11 -08002211// ----------------------------------------------------------------------------
2212// debugging
2213// ----------------------------------------------------------------------------
2214
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002215void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002216{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002217 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002218
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002219 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002220 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002221 "+ %s %p (%s)\n",
2222 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002223 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002224
Mathias Agopian2ca79392013-04-02 18:30:32 -07002225 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002226 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002227 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002228 sp<Client> client(mClientRef.promote());
2229
Mathias Agopian74d211a2013-04-22 16:55:35 +02002230 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002231 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2232 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002233 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002234#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002236#else
2237 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2238#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002239 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002240 getLayerStack(), s.z,
2241 s.active.transform.tx(), s.active.transform.ty(),
2242 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002243 s.crop.left, s.crop.top,
2244 s.crop.right, s.crop.bottom,
2245 s.finalCrop.left, s.finalCrop.top,
2246 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002247 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002248 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002249 s.active.transform[0][0], s.active.transform[0][1],
2250 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002251 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002252
2253 sp<const GraphicBuffer> buf0(mActiveBuffer);
2254 uint32_t w0=0, h0=0, s0=0, f0=0;
2255 if (buf0 != 0) {
2256 w0 = buf0->getWidth();
2257 h0 = buf0->getHeight();
2258 s0 = buf0->getStride();
2259 f0 = buf0->format;
2260 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002261 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002262 " "
2263 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2264 " queued-frames=%d, mRefreshPending=%d\n",
2265 mFormat, w0, h0, s0,f0,
2266 mQueuedFrames, mRefreshPending);
2267
Mathias Agopian13127d82013-03-05 17:47:11 -08002268 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002269 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002270 }
2271}
2272
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002273#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002274void Layer::miniDumpHeader(String8& result) {
2275 result.append("----------------------------------------");
2276 result.append("---------------------------------------\n");
2277 result.append(" Layer name\n");
2278 result.append(" Z | ");
2279 result.append(" Comp Type | ");
2280 result.append(" Disp Frame (LTRB) | ");
2281 result.append(" Source Crop (LTRB)\n");
2282 result.append("----------------------------------------");
2283 result.append("---------------------------------------\n");
2284}
2285
2286void Layer::miniDump(String8& result, int32_t hwcId) const {
2287 if (mHwcLayers.count(hwcId) == 0) {
2288 return;
2289 }
2290
2291 String8 name;
2292 if (mName.length() > 77) {
2293 std::string shortened;
2294 shortened.append(mName.string(), 36);
2295 shortened.append("[...]");
2296 shortened.append(mName.string() + (mName.length() - 36), 36);
2297 name = shortened.c_str();
2298 } else {
2299 name = mName;
2300 }
2301
2302 result.appendFormat(" %s\n", name.string());
2303
2304 const Layer::State& layerState(getDrawingState());
2305 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2306 result.appendFormat(" %10u | ", layerState.z);
2307 result.appendFormat("%10s | ",
2308 to_string(getCompositionType(hwcId)).c_str());
2309 const Rect& frame = hwcInfo.displayFrame;
2310 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2311 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002312 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002313 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2314 crop.right, crop.bottom);
2315
2316 result.append("- - - - - - - - - - - - - - - - - - - - ");
2317 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2318}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002319#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002320
Svetoslavd85084b2014-03-20 10:28:31 -07002321void Layer::dumpFrameStats(String8& result) const {
2322 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002323}
2324
Svetoslavd85084b2014-03-20 10:28:31 -07002325void Layer::clearFrameStats() {
2326 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002327}
2328
Jamie Gennis6547ff42013-07-16 20:12:42 -07002329void Layer::logFrameStats() {
2330 mFrameTracker.logAndResetStats(mName);
2331}
2332
Svetoslavd85084b2014-03-20 10:28:31 -07002333void Layer::getFrameStats(FrameStats* outStats) const {
2334 mFrameTracker.getStats(outStats);
2335}
2336
Brian Andersond6927fb2016-07-23 23:37:30 -07002337void Layer::dumpFrameEvents(String8& result) {
2338 result.appendFormat("- Layer %s (%s, %p)\n",
2339 getName().string(), getTypeId(), this);
2340 Mutex::Autolock lock(mFrameEventHistoryMutex);
2341 mFrameEventHistory.checkFencesForCompletion();
2342 mFrameEventHistory.dump(result);
2343}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002344
Brian Anderson3890c392016-07-25 12:48:08 -07002345void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2346 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002347 Mutex::Autolock lock(mFrameEventHistoryMutex);
2348 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002349 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002350 mFrameEventHistory.addQueue(*newTimestamps);
2351 }
2352
Brian Anderson3890c392016-07-25 12:48:08 -07002353 if (outDelta) {
2354 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002355 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002356}
Dan Stozae77c7662016-05-13 11:37:28 -07002357
2358std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2359 bool forceFlush) {
2360 std::vector<OccupancyTracker::Segment> history;
2361 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2362 &history);
2363 if (result != NO_ERROR) {
2364 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2365 result);
2366 return {};
2367 }
2368 return history;
2369}
2370
Robert Carr367c5682016-06-20 11:55:28 -07002371bool Layer::getTransformToDisplayInverse() const {
2372 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2373}
2374
Robert Carr1f0a16a2016-10-24 16:27:39 -07002375void Layer::addChild(const sp<Layer>& layer) {
2376 mCurrentChildren.add(layer);
2377 layer->setParent(this);
2378}
2379
2380ssize_t Layer::removeChild(const sp<Layer>& layer) {
2381 layer->setParent(nullptr);
2382 return mCurrentChildren.remove(layer);
2383}
2384
Robert Carr1db73f62016-12-21 12:58:51 -08002385bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2386 sp<Handle> handle = nullptr;
2387 sp<Layer> newParent = nullptr;
2388 if (newParentHandle == nullptr) {
2389 return false;
2390 }
2391 handle = static_cast<Handle*>(newParentHandle.get());
2392 newParent = handle->owner.promote();
2393 if (newParent == nullptr) {
2394 ALOGE("Unable to promote Layer handle");
2395 return false;
2396 }
2397
2398 for (const sp<Layer>& child : mCurrentChildren) {
2399 newParent->addChild(child);
2400
2401 sp<Client> client(child->mClientRef.promote());
2402 if (client != nullptr) {
2403 client->setParentLayer(newParent);
2404 }
2405 }
2406 mCurrentChildren.clear();
2407
2408 return true;
2409}
2410
Robert Carr1f0a16a2016-10-24 16:27:39 -07002411void Layer::setParent(const sp<Layer>& layer) {
2412 mParent = layer;
2413}
2414
2415void Layer::clearSyncPoints() {
2416 for (const auto& child : mCurrentChildren) {
2417 child->clearSyncPoints();
2418 }
2419
2420 Mutex::Autolock lock(mLocalSyncPointMutex);
2421 for (auto& point : mLocalSyncPoints) {
2422 point->setFrameAvailable();
2423 }
2424 mLocalSyncPoints.clear();
2425}
2426
2427int32_t Layer::getZ() const {
2428 return mDrawingState.z;
2429}
2430
2431/**
2432 * Negatively signed children are before 'this' in Z-order.
2433 */
2434void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) {
2435 size_t i = 0;
2436 for (; i < mDrawingChildren.size(); i++) {
2437 const auto& child = mDrawingChildren[i];
2438 if (child->getZ() >= 0)
2439 break;
2440 child->traverseInZOrder(exec);
2441 }
2442 exec(this);
2443 for (; i < mDrawingChildren.size(); i++) {
2444 const auto& child = mDrawingChildren[i];
2445 child->traverseInZOrder(exec);
2446 }
2447}
2448
2449/**
2450 * Positively signed children are before 'this' in reverse Z-order.
2451 */
2452void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) {
2453 int32_t i = 0;
2454 for (i = mDrawingChildren.size()-1; i>=0; i--) {
2455 const auto& child = mDrawingChildren[i];
2456 if (child->getZ() < 0) {
2457 break;
2458 }
2459 child->traverseInReverseZOrder(exec);
2460 }
2461 exec(this);
2462 for (; i>=0; i--) {
2463 const auto& child = mDrawingChildren[i];
2464 child->traverseInReverseZOrder(exec);
2465 }
2466}
2467
2468Transform Layer::getTransform() const {
2469 Transform t;
2470 const auto& p = getParent();
2471 if (p != nullptr) {
2472 t = p->getTransform();
2473 }
2474 return t * getDrawingState().active.transform;
2475}
2476
2477void Layer::commitChildList() {
2478 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2479 const auto& child = mCurrentChildren[i];
2480 child->commitChildList();
2481 }
2482 mDrawingChildren = mCurrentChildren;
2483}
2484
Mathias Agopian13127d82013-03-05 17:47:11 -08002485// ---------------------------------------------------------------------------
2486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002487}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002488
2489#if defined(__gl_h_)
2490#error "don't include gl/gl.h in this file"
2491#endif
2492
2493#if defined(__gl2_h_)
2494#error "don't include gl2/gl2.h in this file"
2495#endif