blob: 3a9bca6bb042199463928f2614502cad980e0fcd [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080041#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
43#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020044#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070045#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070047#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070048#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Mathias Agopian1b031492012-06-20 17:51:20 -070051#include "DisplayHardware/HWComposer.h"
52
Mathias Agopian875d8e12013-06-07 15:35:48 -070053#include "RenderEngine/RenderEngine.h"
54
Dan Stozac5da2712016-07-20 15:38:12 -070055#include <mutex>
56
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#define DEBUG_RESIZE 0
58
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059namespace android {
60
61// ---------------------------------------------------------------------------
62
Mathias Agopian13127d82013-03-05 17:47:11 -080063int32_t Layer::sSequence = 1;
64
Mathias Agopian4d9b8222013-03-12 17:11:48 -070065Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
66 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080067 : contentDirty(false),
68 sequence(uint32_t(android_atomic_inc(&sSequence))),
69 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070070 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080071 mPremultipliedAlpha(true),
72 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080073 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070075 mPendingStateMutex(),
76 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070077 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080078 mSidebandStreamChanged(false),
Mathias Agopiana67932f2011-04-20 14:20:59 -070079 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070080 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070081 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070082 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070083 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080084 mCurrentFrameNumber(0),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mPreviousFrameNumber(-1U),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080086 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080087 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080088 mFiltering(false),
89 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070090 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000091#ifndef USE_HWC2
92 mIsGlesComposition(false),
93#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080094 mProtectedByApp(false),
95 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070096 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070097 mPotentialCursor(false),
98 mQueueItemLock(),
99 mQueueItemCondition(),
100 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700101 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800102 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700103 mAutoRefresh(false),
104 mFreezePositionUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000106#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800107 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000108#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800109
Mathias Agopiana67932f2011-04-20 14:20:59 -0700110 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700111 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700112 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700113
114 uint32_t layerFlags = 0;
115 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800116 layerFlags |= layer_state_t::eLayerHidden;
117 if (flags & ISurfaceComposerClient::eOpaque)
118 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700119 if (flags & ISurfaceComposerClient::eSecure)
120 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700121
122 if (flags & ISurfaceComposerClient::eNonPremultiplied)
123 mPremultipliedAlpha = false;
124
125 mName = name;
126
127 mCurrentState.active.w = w;
128 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800129 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700130 mCurrentState.crop.makeInvalid();
131 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700132 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000133#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800134 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000135#else
136 mCurrentState.alpha = 0xFF;
137#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700138 mCurrentState.layerStack = 0;
139 mCurrentState.flags = layerFlags;
140 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700141 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700142 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500143 mCurrentState.appId = 0;
144 mCurrentState.type = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700145
146 // drawing state & current state are identical
147 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700148
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000149#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800150 const auto& hwc = flinger->getHwComposer();
151 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
152 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000153#else
154 nsecs_t displayPeriod =
155 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
156#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700157 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Jamie Gennise8696a42012-01-15 18:54:57 -0800158}
159
Mathias Agopian3f844832013-08-07 21:24:32 -0700160void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800161 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700162 sp<IGraphicBufferProducer> producer;
163 sp<IGraphicBufferConsumer> consumer;
Irvel468051e2016-06-13 16:44:44 -0700164 BufferQueue::createBufferQueue(&producer, &consumer, nullptr, true);
Robert Carr1db73f62016-12-21 12:58:51 -0800165 mProducer = new MonitoredProducer(producer, mFlinger, this);
Irvel468051e2016-06-13 16:44:44 -0700166 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800167 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800168 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700169 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800170
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800171 if (mFlinger->isLayerTripleBufferingDisabled()) {
172 mProducer->setMaxDequeuedBufferCount(2);
173 }
Andy McFadden69052052012-09-14 16:10:11 -0700174
Mathias Agopian84300952012-11-21 16:02:13 -0800175 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
176 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700177}
178
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700179Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800180 sp<Client> c(mClientRef.promote());
181 if (c != 0) {
182 c->detachLayer(this);
183 }
184
Dan Stozacac35382016-01-27 12:21:06 -0800185 for (auto& point : mRemoteSyncPoints) {
186 point->setTransactionApplied();
187 }
Dan Stozac8145172016-04-28 16:29:06 -0700188 for (auto& point : mLocalSyncPoints) {
189 point->setFrameAvailable();
190 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700191 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700192 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700193}
194
Mathias Agopian13127d82013-03-05 17:47:11 -0800195// ---------------------------------------------------------------------------
196// callbacks
197// ---------------------------------------------------------------------------
198
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000199#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800200void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
201 if (mHwcLayers.empty()) {
202 return;
203 }
204 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
205}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000206#else
207void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
208 HWComposer::HWCLayerInterface* layer) {
209 if (layer) {
210 layer->onDisplayed();
211 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
212 }
213}
214#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800215
Dan Stoza6b9454d2014-11-07 16:00:59 -0800216void Layer::onFrameAvailable(const BufferItem& item) {
217 // Add this buffer from our internal queue tracker
218 { // Autolock scope
219 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700220 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
221 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700222 // Reset the frame number tracker when we receive the first buffer after
223 // a frame number reset
224 if (item.mFrameNumber == 1) {
225 mLastFrameNumberReceived = 0;
226 }
227
228 // Ensure that callbacks are handled in order
229 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
230 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
231 ms2ns(500));
232 if (result != NO_ERROR) {
233 ALOGE("[%s] Timed out waiting on callback", mName.string());
234 }
235 }
236
Dan Stoza6b9454d2014-11-07 16:00:59 -0800237 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700238 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700239
240 // Wake up any pending callbacks
241 mLastFrameNumberReceived = item.mFrameNumber;
242 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800243 }
244
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800245 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700246}
247
Dan Stoza6b9454d2014-11-07 16:00:59 -0800248void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700249 { // Autolock scope
250 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700251
Dan Stoza7dde5992015-05-22 09:51:44 -0700252 // Ensure that callbacks are handled in order
253 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
254 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
255 ms2ns(500));
256 if (result != NO_ERROR) {
257 ALOGE("[%s] Timed out waiting on callback", mName.string());
258 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700259 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700260
261 if (mQueueItems.empty()) {
262 ALOGE("Can't replace a frame on an empty queue");
263 return;
264 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700265 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700266
267 // Wake up any pending callbacks
268 mLastFrameNumberReceived = item.mFrameNumber;
269 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700270 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800271}
272
Chia-I Wu06d63de2017-01-04 14:58:51 +0800273void Layer::onBuffersReleased() {
274#ifdef USE_HWC2
275 Mutex::Autolock lock(mHwcBufferCacheMutex);
276
277 for (auto info : mHwcBufferCaches) {
278 info.second.clear();
279 }
280#endif
281}
282
Jesse Hall399184a2014-03-03 15:42:54 -0800283void Layer::onSidebandStreamChanged() {
284 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
285 // mSidebandStreamChanged was false
286 mFlinger->signalLayerUpdate();
287 }
288}
289
Mathias Agopian67106042013-03-14 19:18:13 -0700290// called with SurfaceFlinger::mStateLock from the drawing thread after
291// the layer has been remove from the current state list (and just before
292// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800293void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800294 mSurfaceFlingerConsumer->abandon();
Robert Carr1f0a16a2016-10-24 16:27:39 -0700295 for (const auto& child : mCurrentChildren) {
296 child->onRemoved();
297 }
Mathias Agopian48d819a2009-09-10 19:41:18 -0700298}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700299
Mathias Agopian13127d82013-03-05 17:47:11 -0800300// ---------------------------------------------------------------------------
301// set-up
302// ---------------------------------------------------------------------------
303
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700304const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800305 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306}
307
Mathias Agopianf9d93272009-06-19 17:00:27 -0700308status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309 PixelFormat format, uint32_t flags)
310{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700311 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700312 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700313
314 // never allow a surface larger than what our underlying GL implementation
315 // can handle.
316 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800317 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700318 return BAD_VALUE;
319 }
320
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700321 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700322
Riley Andrews03414a12014-07-01 14:22:59 -0700323 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700324 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700325 mCurrentOpacity = getOpacityForFormat(format);
326
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800327 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
328 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
329 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 return NO_ERROR;
332}
333
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700334sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800335 Mutex::Autolock _l(mLock);
336
337 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700338 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800339
340 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700341
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700342 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800343}
344
Dan Stozab9b08832014-03-13 11:55:57 -0700345sp<IGraphicBufferProducer> Layer::getProducer() const {
346 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700347}
348
Mathias Agopian13127d82013-03-05 17:47:11 -0800349// ---------------------------------------------------------------------------
350// h/w composer set-up
351// ---------------------------------------------------------------------------
352
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800353Rect Layer::getContentCrop() const {
354 // this is the crop rectangle that applies to the buffer
355 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700356 Rect crop;
357 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800358 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700359 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800360 } else if (mActiveBuffer != NULL) {
361 // otherwise we use the whole buffer
362 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700363 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800364 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700365 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700366 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700367 return crop;
368}
369
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700370static Rect reduce(const Rect& win, const Region& exclude) {
371 if (CC_LIKELY(exclude.isEmpty())) {
372 return win;
373 }
374 if (exclude.isRect()) {
375 return win.reduce(exclude.getBounds());
376 }
377 return Region(win).subtract(exclude).getBounds();
378}
379
Robert Carr1f0a16a2016-10-24 16:27:39 -0700380Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
381 const Layer::State& s(getDrawingState());
382 Rect win(s.active.w, s.active.h);
383
384 if (!s.crop.isEmpty()) {
385 win.intersect(s.crop, &win);
386 }
387
388 Transform t = getTransform();
389 win = t.transform(win);
390
391 const sp<Layer>& p = getParent();
392 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
393 // When calculating the parent bounds for purposes of clipping,
394 // we don't need to constrain the parent to its transparent region.
395 // The transparent region is an optimization based on the
396 // buffer contents of the layer, but does not affect the space allocated to
397 // it by policy, and thus children should be allowed to extend into the
398 // parent's transparent region. In fact one of the main uses, is to reduce
399 // buffer allocation size in cases where a child window sits behind a main window
400 // (by marking the hole in the parent window as a transparent region)
401 if (p != nullptr) {
402 Rect bounds = p->computeScreenBounds(false);
403 bounds.intersect(win, &win);
404 }
405
406 if (reduceTransparentRegion) {
407 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
408 win = reduce(win, screenTransparentRegion);
409 }
410
411 return win;
412}
413
Mathias Agopian13127d82013-03-05 17:47:11 -0800414Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700415 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700416 return computeBounds(s.activeTransparentRegion);
417}
418
419Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
420 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800421 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700422
423 if (!s.crop.isEmpty()) {
424 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800425 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700426
427 Rect bounds = win;
428 const auto& p = getParent();
429 if (p != nullptr) {
430 bounds = p->computeScreenBounds();
431 }
432
433 Transform t = getTransform();
434 if (p != nullptr) {
435 win = t.transform(win);
436 win.intersect(bounds, &win);
437 win = t.inverse().transform(win);
438 }
439
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700440 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700441 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800442}
443
Robert Carr1f0a16a2016-10-24 16:27:39 -0700444Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
Robert Carrb5d3d262016-03-25 15:08:13 -0700445 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800446 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700447 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800448
449 // apply the projection's clipping to the window crop in
450 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700451 // if there are no window scaling involved, this operation will map to full
452 // pixels in the buffer.
453 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
454 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700455
456 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700457 if (!s.crop.isEmpty()) {
458 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700459 }
460
Robert Carr1f0a16a2016-10-24 16:27:39 -0700461 Transform t = getTransform();
462 activeCrop = t.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000463 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
464 activeCrop.clear();
465 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700466 if (!s.finalCrop.isEmpty()) {
467 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000468 activeCrop.clear();
469 }
470 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700471 return activeCrop;
472}
473
474gfx::FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
475 // the content crop is the area of the content that gets scaled to the
476 // layer's size. This is in buffer space.
477 gfx::FloatRect crop = getContentCrop().toFloatRect();
478
479 // In addition there is a WM-specified crop we pull from our drawing state.
480 const State& s(getDrawingState());
481
482 // Screen space to make reduction to parent crop clearer.
483 Rect activeCrop = computeInitialCrop(hw);
484 const auto& p = getParent();
485 if (p != nullptr) {
486 auto parentCrop = p->computeInitialCrop(hw);
487 activeCrop.intersect(parentCrop, &activeCrop);
488 }
489 Transform t = getTransform();
490 // Back to layer space to work with the content crop.
491 activeCrop = t.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800492
Michael Lentine28ea2172014-11-19 18:32:37 -0800493 // This needs to be here as transform.transform(Rect) computes the
494 // transformed rect and then takes the bounding box of the result before
495 // returning. This means
496 // transform.inverse().transform(transform.transform(Rect)) != Rect
497 // in which case we need to make sure the final rect is clipped to the
498 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000499 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
500 activeCrop.clear();
501 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800502
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700503 // subtract the transparent region and snap to the bounds
504 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
505
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000506 // Transform the window crop to match the buffer coordinate system,
507 // which means using the inverse of the current transform set on the
508 // SurfaceFlingerConsumer.
509 uint32_t invTransform = mCurrentTransform;
510 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
511 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700512 * the code below applies the primary display's inverse transform to the
513 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000514 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700515 uint32_t invTransformOrient =
516 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000517 // calculate the inverse transform
518 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
519 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
520 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800521 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000522 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700523 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
524 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800525 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000526
527 int winWidth = s.active.w;
528 int winHeight = s.active.h;
529 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
530 // If the activeCrop has been rotate the ends are rotated but not
531 // the space itself so when transforming ends back we can't rely on
532 // a modification of the axes of rotation. To account for this we
533 // need to reorient the inverse rotation in terms of the current
534 // axes of rotation.
535 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
536 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
537 if (is_h_flipped == is_v_flipped) {
538 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
539 NATIVE_WINDOW_TRANSFORM_FLIP_H;
540 }
541 winWidth = s.active.h;
542 winHeight = s.active.w;
543 }
544 const Rect winCrop = activeCrop.transform(
545 invTransform, s.active.w, s.active.h);
546
547 // below, crop is intersected with winCrop expressed in crop's coordinate space
548 float xScale = crop.getWidth() / float(winWidth);
549 float yScale = crop.getHeight() / float(winHeight);
550
551 float insetL = winCrop.left * xScale;
552 float insetT = winCrop.top * yScale;
553 float insetR = (winWidth - winCrop.right ) * xScale;
554 float insetB = (winHeight - winCrop.bottom) * yScale;
555
556 crop.left += insetL;
557 crop.top += insetT;
558 crop.right -= insetR;
559 crop.bottom -= insetB;
560
Mathias Agopian13127d82013-03-05 17:47:11 -0800561 return crop;
562}
563
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000564#ifdef USE_HWC2
Robert Carrae060832016-11-28 10:51:00 -0800565void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000566#else
567void Layer::setGeometry(
568 const sp<const DisplayDevice>& hw,
569 HWComposer::HWCLayerInterface& layer)
570#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700571{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800573 const auto hwcId = displayDevice->getHwcDisplayId();
574 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000575#else
576 layer.setDefaultState();
577#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700578
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700579 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000580#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800581 hwcInfo.forceClientComposition = false;
582
583 if (isSecure() && !displayDevice->isSecure()) {
584 hwcInfo.forceClientComposition = true;
585 }
586
587 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000588#else
589 layer.setSkip(false);
590
591 if (isSecure() && !hw->isSecure()) {
592 layer.setSkip(true);
593 }
594#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700595
Mathias Agopian13127d82013-03-05 17:47:11 -0800596 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700597 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000598#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599 if (!isOpaque(s) || s.alpha != 1.0f) {
600 auto blendMode = mPremultipliedAlpha ?
601 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
602 auto error = hwcLayer->setBlendMode(blendMode);
603 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
604 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
605 to_string(error).c_str(), static_cast<int32_t>(error));
606 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000607#else
608 if (!isOpaque(s) || s.alpha != 0xFF) {
609 layer.setBlending(mPremultipliedAlpha ?
610 HWC_BLENDING_PREMULT :
611 HWC_BLENDING_COVERAGE);
612 }
613#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800614
615 // apply the layer's transform, followed by the display's global transform
616 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700617 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700618 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -0700619 if (!s.crop.isEmpty()) {
620 Rect activeCrop(s.crop);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700621 activeCrop = t.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000622#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000623 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000624#else
625 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
626#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000627 activeCrop.clear();
628 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700629 activeCrop = t.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800630 // This needs to be here as transform.transform(Rect) computes the
631 // transformed rect and then takes the bounding box of the result before
632 // returning. This means
633 // transform.inverse().transform(transform.transform(Rect)) != Rect
634 // in which case we need to make sure the final rect is clipped to the
635 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000636 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
637 activeCrop.clear();
638 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700639 // mark regions outside the crop as transparent
640 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
641 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
642 s.active.w, s.active.h));
643 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
644 activeCrop.left, activeCrop.bottom));
645 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
646 s.active.w, activeCrop.bottom));
647 }
Robert Carr1f0a16a2016-10-24 16:27:39 -0700648
649 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700650 if (!s.finalCrop.isEmpty()) {
651 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000652 frame.clear();
653 }
654 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000655#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000656 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
657 frame.clear();
658 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 const Transform& tr(displayDevice->getTransform());
660 Rect transformedFrame = tr.transform(frame);
661 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700662 if (error != HWC2::Error::None) {
663 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
664 mName.string(), transformedFrame.left, transformedFrame.top,
665 transformedFrame.right, transformedFrame.bottom,
666 to_string(error).c_str(), static_cast<int32_t>(error));
667 } else {
668 hwcInfo.displayFrame = transformedFrame;
669 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800670
Dan Stoza71bded52016-10-19 11:10:33 -0700671 gfx::FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800672 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700673 if (error != HWC2::Error::None) {
674 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
675 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
676 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
677 static_cast<int32_t>(error));
678 } else {
679 hwcInfo.sourceCrop = sourceCrop;
680 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681
682 error = hwcLayer->setPlaneAlpha(s.alpha);
683 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
684 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
685 static_cast<int32_t>(error));
686
Robert Carrae060832016-11-28 10:51:00 -0800687 error = hwcLayer->setZOrder(z);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800688 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
Robert Carrae060832016-11-28 10:51:00 -0800689 mName.string(), z, to_string(error).c_str(),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 static_cast<int32_t>(error));
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -0500691
692 error = hwcLayer->setInfo(s.type, s.appId);
693 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
694 mName.string(), static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000695#else
696 if (!frame.intersect(hw->getViewport(), &frame)) {
697 frame.clear();
698 }
699 const Transform& tr(hw->getTransform());
700 layer.setFrame(tr.transform(frame));
701 layer.setCrop(computeCrop(hw));
702 layer.setPlaneAlpha(s.alpha);
703#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800704
Mathias Agopian29a367b2011-07-12 14:51:45 -0700705 /*
706 * Transformations are applied in this order:
707 * 1) buffer orientation/flip/mirror
708 * 2) state transformation (window manager)
709 * 3) layer orientation (screen orientation)
710 * (NOTE: the matrices are multiplied in reverse order)
711 */
712
713 const Transform bufferOrientation(mCurrentTransform);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700714 Transform transform(tr * t * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700715
716 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
717 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700718 * the code below applies the primary display's inverse transform to the
719 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700720 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700721 uint32_t invTransform =
722 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700723 // calculate the inverse transform
724 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
725 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
726 NATIVE_WINDOW_TRANSFORM_FLIP_H;
727 }
728 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700729 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700730 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700731
732 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800733 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000734#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800735 if (orientation & Transform::ROT_INVALID) {
736 // we can only handle simple transformation
737 hwcInfo.forceClientComposition = true;
738 } else {
739 auto transform = static_cast<HWC2::Transform>(orientation);
740 auto error = hwcLayer->setTransform(transform);
741 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
742 "%s (%d)", mName.string(), to_string(transform).c_str(),
743 to_string(error).c_str(), static_cast<int32_t>(error));
744 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000745#else
746 if (orientation & Transform::ROT_INVALID) {
747 // we can only handle simple transformation
748 layer.setSkip(true);
749 } else {
750 layer.setTransform(orientation);
751 }
752#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700753}
754
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000755#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756void Layer::forceClientComposition(int32_t hwcId) {
757 if (mHwcLayers.count(hwcId) == 0) {
758 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
759 return;
760 }
761
762 mHwcLayers[hwcId].forceClientComposition = true;
763}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000764#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000766#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
768 // Apply this display's projection's viewport to the visible region
769 // before giving it to the HWC HAL.
770 const Transform& tr = displayDevice->getTransform();
771 const auto& viewport = displayDevice->getViewport();
772 Region visible = tr.transform(visibleRegion.intersect(viewport));
773 auto hwcId = displayDevice->getHwcDisplayId();
774 auto& hwcLayer = mHwcLayers[hwcId].layer;
775 auto error = hwcLayer->setVisibleRegion(visible);
776 if (error != HWC2::Error::None) {
777 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
778 to_string(error).c_str(), static_cast<int32_t>(error));
779 visible.dump(LOG_TAG);
780 }
781
782 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
783 if (error != HWC2::Error::None) {
784 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
785 to_string(error).c_str(), static_cast<int32_t>(error));
786 surfaceDamageRegion.dump(LOG_TAG);
787 }
788
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700789 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800790 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700791 setCompositionType(hwcId, HWC2::Composition::Sideband);
792 ALOGV("[%s] Requesting Sideband composition", mName.string());
793 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800794 if (error != HWC2::Error::None) {
795 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
796 mName.string(), mSidebandStream->handle(),
797 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700799 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 }
801
Dan Stoza0a21df72016-07-20 12:52:38 -0700802 // Client layers
803 if (mHwcLayers[hwcId].forceClientComposition ||
804 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700805 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700807 return;
808 }
809
Dan Stoza0a21df72016-07-20 12:52:38 -0700810 // SolidColor layers
811 if (mActiveBuffer == nullptr) {
812 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700813
814 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700815 error = hwcLayer->setColor({0, 0, 0, 255});
816 if (error != HWC2::Error::None) {
817 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
818 to_string(error).c_str(), static_cast<int32_t>(error));
819 }
Dan Stozac6c89542016-07-27 10:16:52 -0700820
821 // Clear out the transform, because it doesn't make sense absent a
822 // source buffer
823 error = hwcLayer->setTransform(HWC2::Transform::None);
824 if (error != HWC2::Error::None) {
825 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
826 to_string(error).c_str(), static_cast<int32_t>(error));
827 }
828
Dan Stoza0a21df72016-07-20 12:52:38 -0700829 return;
830 }
831
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700832 // Device or Cursor layers
833 if (mPotentialCursor) {
834 ALOGV("[%s] Requesting Cursor composition", mName.string());
835 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800836 } else {
837 ALOGV("[%s] Requesting Device composition", mName.string());
838 setCompositionType(hwcId, HWC2::Composition::Device);
839 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700840
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700841 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
842 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
843 if (error != HWC2::Error::None) {
844 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
845 mCurrentState.dataSpace, to_string(error).c_str(),
846 static_cast<int32_t>(error));
847 }
848
Chia-I Wu06d63de2017-01-04 14:58:51 +0800849 uint32_t hwcSlot = 0;
850 buffer_handle_t hwcHandle = nullptr;
851 {
852 Mutex::Autolock lock(mHwcBufferCacheMutex);
853
854 auto& hwcBufferCache = mHwcBufferCaches[hwcId];
855 sp<GraphicBuffer> hwcBuffer;
856 hwcBufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
857 &hwcSlot, &hwcBuffer);
858 if (hwcBuffer != nullptr) {
859 hwcHandle = hwcBuffer->handle;
860 }
861 }
862
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700863 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
Chia-I Wu06d63de2017-01-04 14:58:51 +0800864 error = hwcLayer->setBuffer(hwcSlot, hwcHandle, acquireFence);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700865 if (error != HWC2::Error::None) {
866 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
867 mActiveBuffer->handle, to_string(error).c_str(),
868 static_cast<int32_t>(error));
869 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000871#else
872void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
873 HWComposer::HWCLayerInterface& layer) {
874 // we have to set the visible region on every frame because
875 // we currently free it during onLayerDisplayed(), which is called
876 // after HWComposer::commit() -- every frame.
877 // Apply this display's projection's viewport to the visible region
878 // before giving it to the HWC HAL.
879 const Transform& tr = hw->getTransform();
880 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
881 layer.setVisibleRegionScreen(visible);
882 layer.setSurfaceDamage(surfaceDamageRegion);
883 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700884
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000885 if (mSidebandStream.get()) {
886 layer.setSidebandStream(mSidebandStream);
887 } else {
888 // NOTE: buffer can be NULL if the client never drew into this
889 // layer yet, or if we ran out of memory
890 layer.setBuffer(mActiveBuffer);
891 }
892}
893#endif
894
895#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
897 auto hwcId = displayDevice->getHwcDisplayId();
898 if (mHwcLayers.count(hwcId) == 0 ||
899 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
900 return;
901 }
902
903 // This gives us only the "orientation" component of the transform
904 const State& s(getCurrentState());
905
906 // Apply the layer's transform, followed by the display's global transform
907 // Here we're guaranteed that the layer's transform preserves rects
908 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700909 if (!s.crop.isEmpty()) {
910 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800911 }
912 // Subtract the transparent region and snap to the bounds
913 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700914 Rect frame(getTransform().transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800915 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700916 if (!s.finalCrop.isEmpty()) {
917 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000918 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800919 auto& displayTransform(displayDevice->getTransform());
920 auto position = displayTransform.transform(frame);
921
922 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
923 position.top);
924 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
925 "to (%d, %d): %s (%d)", mName.string(), position.left,
926 position.top, to_string(error).c_str(),
927 static_cast<int32_t>(error));
928}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000929#else
930void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
931 HWComposer::HWCLayerInterface& layer) {
932 int fenceFd = -1;
933
934 // TODO: there is a possible optimization here: we only need to set the
935 // acquire fence the first time a new buffer is acquired on EACH display.
936
937 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
938 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
939 if (fence->isValid()) {
940 fenceFd = fence->dup();
941 if (fenceFd == -1) {
942 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
943 }
944 }
945 }
946 layer.setAcquireFenceFd(fenceFd);
947}
948
949Rect Layer::getPosition(
950 const sp<const DisplayDevice>& hw)
951{
952 // this gives us only the "orientation" component of the transform
953 const State& s(getCurrentState());
954
955 // apply the layer's transform, followed by the display's global transform
956 // here we're guaranteed that the layer's transform preserves rects
957 Rect win(s.active.w, s.active.h);
958 if (!s.crop.isEmpty()) {
959 win.intersect(s.crop, &win);
960 }
961 // subtract the transparent region and snap to the bounds
962 Rect bounds = reduce(win, s.activeTransparentRegion);
Robert Carr1f0a16a2016-10-24 16:27:39 -0700963 Rect frame(getTransform().transform(bounds));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000964 frame.intersect(hw->getViewport(), &frame);
965 if (!s.finalCrop.isEmpty()) {
966 frame.intersect(s.finalCrop, &frame);
967 }
968 const Transform& tr(hw->getTransform());
969 return Rect(tr.transform(frame));
970}
971#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700972
Mathias Agopian13127d82013-03-05 17:47:11 -0800973// ---------------------------------------------------------------------------
974// drawing...
975// ---------------------------------------------------------------------------
976
977void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800978 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800979}
980
Dan Stozac7014012014-02-14 15:03:43 -0800981void Layer::draw(const sp<const DisplayDevice>& hw,
982 bool useIdentityTransform) const {
983 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800984}
985
Dan Stozac7014012014-02-14 15:03:43 -0800986void Layer::draw(const sp<const DisplayDevice>& hw) const {
987 onDraw(hw, Region(hw->bounds()), false);
988}
989
990void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
991 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800992{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800993 ATRACE_CALL();
994
Mathias Agopiana67932f2011-04-20 14:20:59 -0700995 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800996 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -0700997 // in fact never been drawn into. This happens frequently with
998 // SurfaceView because the WindowManager can't know when the client
999 // has drawn the first time.
1000
1001 // If there is nothing under us, we paint the screen in black, otherwise
1002 // we just skip this update.
1003
1004 // figure out if there is something below us
1005 Region under;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001006 bool finished = false;
1007 mFlinger->mDrawingState.layersSortedByZ.traverseInZOrder([&](Layer* layer) {
1008 if (finished || layer == static_cast<Layer const*>(this)) {
1009 finished = true;
1010 return;
1011 }
Mathias Agopian42977342012-08-05 00:40:46 -07001012 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Robert Carr1f0a16a2016-10-24 16:27:39 -07001013 });
Mathias Agopian179169e2010-05-06 20:21:45 -07001014 // if not everything below us is covered, we plug the holes!
1015 Region holes(clip.subtract(under));
1016 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -08001017 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -07001018 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001019 return;
1020 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001021
Andy McFadden97eba892012-12-11 15:21:45 -08001022 // Bind the current buffer to the GL texture, and wait for it to be
1023 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001024 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1025 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -08001026 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -07001027 // Go ahead and draw the buffer anyway; no matter what we do the screen
1028 // is probably going to have something visibly wrong.
1029 }
1030
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001031 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1032
Mathias Agopian875d8e12013-06-07 15:35:48 -07001033 RenderEngine& engine(mFlinger->getRenderEngine());
1034
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001035 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -07001036 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -07001037 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -07001038
1039 // Query the texture matrix given our current filtering mode.
1040 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001041 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1042 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -07001043
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001044 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1045
1046 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -07001047 * the code below applies the primary display's inverse transform to
1048 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001049 */
1050
1051 // create a 4x4 transform matrix from the display transform flags
1052 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1053 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1054 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1055
1056 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -07001057 uint32_t transform =
1058 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001059 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
1060 tr = tr * rot90;
1061 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
1062 tr = tr * flipH;
1063 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
1064 tr = tr * flipV;
1065
1066 // calculate the inverse
1067 tr = inverse(tr);
1068
1069 // and finally apply it to the original texture matrix
1070 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1071 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1072 }
1073
Jamie Genniscbb1a952012-05-08 17:05:52 -07001074 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -07001075 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1076 mTexture.setFiltering(useFiltering);
1077 mTexture.setMatrix(textureMatrix);
1078
1079 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -07001080 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -07001081 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -07001082 }
Fabien Sanglard85789802016-12-07 13:08:24 -08001083 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001084 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001085}
1086
Mathias Agopian13127d82013-03-05 17:47:11 -08001087
Dan Stozac7014012014-02-14 15:03:43 -08001088void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -08001089 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -08001090 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001091{
Mathias Agopian19733a32013-08-28 18:13:56 -07001092 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -08001093 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -07001094 engine.setupFillWithColor(red, green, blue, alpha);
1095 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -08001096}
1097
1098void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001099 const sp<const DisplayDevice>& hw) const {
1100 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001101}
1102
Dan Stozac7014012014-02-14 15:03:43 -08001103void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001104 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001105 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001106
Dan Stozac7014012014-02-14 15:03:43 -08001107 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001108
Mathias Agopian13127d82013-03-05 17:47:11 -08001109 /*
1110 * NOTE: the way we compute the texture coordinates here produces
1111 * different results than when we take the HWC path -- in the later case
1112 * the "source crop" is rounded to texel boundaries.
1113 * This can produce significantly different results when the texture
1114 * is scaled by a large amount.
1115 *
1116 * The GL code below is more logical (imho), and the difference with
1117 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001118 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001119 * GL composition when a buffer scaling is applied (maybe with some
1120 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1121 * like more of a hack.
1122 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001123 Rect win(computeBounds());
1124
Robert Carr1f0a16a2016-10-24 16:27:39 -07001125 Transform t = getTransform();
Robert Carrb5d3d262016-03-25 15:08:13 -07001126 if (!s.finalCrop.isEmpty()) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001127 win = t.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001128 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001129 win.clear();
1130 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07001131 win = t.inverse().transform(win);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001132 if (!win.intersect(computeBounds(), &win)) {
1133 win.clear();
1134 }
1135 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001136
Mathias Agopian3f844832013-08-07 21:24:32 -07001137 float left = float(win.left) / float(s.active.w);
1138 float top = float(win.top) / float(s.active.h);
1139 float right = float(win.right) / float(s.active.w);
1140 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001141
Mathias Agopian875d8e12013-06-07 15:35:48 -07001142 // TODO: we probably want to generate the texture coords with the mesh
1143 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001144 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1145 texCoords[0] = vec2(left, 1.0f - top);
1146 texCoords[1] = vec2(left, 1.0f - bottom);
1147 texCoords[2] = vec2(right, 1.0f - bottom);
1148 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001149
Mathias Agopian875d8e12013-06-07 15:35:48 -07001150 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001151 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001152 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001153 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001154}
1155
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001156#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001157void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1158 bool callIntoHwc) {
1159 if (mHwcLayers.count(hwcId) == 0) {
1160 ALOGE("setCompositionType called without a valid HWC layer");
1161 return;
1162 }
1163 auto& hwcInfo = mHwcLayers[hwcId];
1164 auto& hwcLayer = hwcInfo.layer;
1165 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1166 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1167 if (hwcInfo.compositionType != type) {
1168 ALOGV(" actually setting");
1169 hwcInfo.compositionType = type;
1170 if (callIntoHwc) {
1171 auto error = hwcLayer->setCompositionType(type);
1172 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1173 "composition type %s: %s (%d)", mName.string(),
1174 to_string(type).c_str(), to_string(error).c_str(),
1175 static_cast<int32_t>(error));
1176 }
1177 }
1178}
1179
1180HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001181 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1182 // If we're querying the composition type for a display that does not
1183 // have a HWC counterpart, then it will always be Client
1184 return HWC2::Composition::Client;
1185 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001186 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001187 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001188 return HWC2::Composition::Invalid;
1189 }
1190 return mHwcLayers.at(hwcId).compositionType;
1191}
1192
1193void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1194 if (mHwcLayers.count(hwcId) == 0) {
1195 ALOGE("setClearClientTarget called without a valid HWC layer");
1196 return;
1197 }
1198 mHwcLayers[hwcId].clearClientTarget = clear;
1199}
1200
1201bool Layer::getClearClientTarget(int32_t hwcId) const {
1202 if (mHwcLayers.count(hwcId) == 0) {
1203 ALOGE("getClearClientTarget called without a valid HWC layer");
1204 return false;
1205 }
1206 return mHwcLayers.at(hwcId).clearClientTarget;
1207}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001208#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209
Ruben Brunk1681d952014-06-27 15:51:55 -07001210uint32_t Layer::getProducerStickyTransform() const {
1211 int producerStickyTransform = 0;
1212 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1213 if (ret != OK) {
1214 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1215 strerror(-ret), ret);
1216 return 0;
1217 }
1218 return static_cast<uint32_t>(producerStickyTransform);
1219}
1220
Dan Stozac5da2712016-07-20 15:38:12 -07001221bool Layer::latchUnsignaledBuffers() {
1222 static bool propertyLoaded = false;
1223 static bool latch = false;
1224 static std::mutex mutex;
1225 std::lock_guard<std::mutex> lock(mutex);
1226 if (!propertyLoaded) {
1227 char value[PROPERTY_VALUE_MAX] = {};
1228 property_get("debug.sf.latch_unsignaled", value, "0");
1229 latch = atoi(value);
1230 propertyLoaded = true;
1231 }
1232 return latch;
1233}
1234
Dan Stozacac35382016-01-27 12:21:06 -08001235uint64_t Layer::getHeadFrameNumber() const {
1236 Mutex::Autolock lock(mQueueItemLock);
1237 if (!mQueueItems.empty()) {
1238 return mQueueItems[0].mFrameNumber;
1239 } else {
1240 return mCurrentFrameNumber;
1241 }
1242}
1243
Dan Stoza1ce65812016-06-15 16:26:27 -07001244bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001245#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001246 if (latchUnsignaledBuffers()) {
1247 return true;
1248 }
1249
Dan Stoza1ce65812016-06-15 16:26:27 -07001250 Mutex::Autolock lock(mQueueItemLock);
1251 if (mQueueItems.empty()) {
1252 return true;
1253 }
1254 if (mQueueItems[0].mIsDroppable) {
1255 // Even though this buffer's fence may not have signaled yet, it could
1256 // be replaced by another buffer before it has a chance to, which means
1257 // that it's possible to get into a situation where a buffer is never
1258 // able to be latched. To avoid this, grab this buffer anyway.
1259 return true;
1260 }
1261 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001262#else
1263 return true;
1264#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001265}
1266
Dan Stozacac35382016-01-27 12:21:06 -08001267bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1268 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1269 // Don't bother with a SyncPoint, since we've already latched the
1270 // relevant frame
1271 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001272 }
1273
Dan Stozacac35382016-01-27 12:21:06 -08001274 Mutex::Autolock lock(mLocalSyncPointMutex);
1275 mLocalSyncPoints.push_back(point);
1276 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001277}
1278
Mathias Agopian13127d82013-03-05 17:47:11 -08001279void Layer::setFiltering(bool filtering) {
1280 mFiltering = filtering;
1281}
1282
1283bool Layer::getFiltering() const {
1284 return mFiltering;
1285}
1286
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001287// As documented in libhardware header, formats in the range
1288// 0x100 - 0x1FF are specific to the HAL implementation, and
1289// are known to have no alpha channel
1290// TODO: move definition for device-specific range into
1291// hardware.h, instead of using hard-coded values here.
1292#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1293
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001294bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001295 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1296 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001297 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001298 switch (format) {
1299 case HAL_PIXEL_FORMAT_RGBA_8888:
1300 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001301 case HAL_PIXEL_FORMAT_RGBA_FP16:
Mathias Agopiandd533712013-07-26 15:31:39 -07001302 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001303 }
1304 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001305 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001306}
1307
Mathias Agopian13127d82013-03-05 17:47:11 -08001308// ----------------------------------------------------------------------------
1309// local state
1310// ----------------------------------------------------------------------------
1311
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001312static void boundPoint(vec2* point, const Rect& crop) {
1313 if (point->x < crop.left) {
1314 point->x = crop.left;
1315 }
1316 if (point->x > crop.right) {
1317 point->x = crop.right;
1318 }
1319 if (point->y < crop.top) {
1320 point->y = crop.top;
1321 }
1322 if (point->y > crop.bottom) {
1323 point->y = crop.bottom;
1324 }
1325}
1326
Dan Stozac7014012014-02-14 15:03:43 -08001327void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1328 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001329{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001330 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001331 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001332 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001333 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001334
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001335 vec2 lt = vec2(win.left, win.top);
1336 vec2 lb = vec2(win.left, win.bottom);
1337 vec2 rb = vec2(win.right, win.bottom);
1338 vec2 rt = vec2(win.right, win.top);
1339
Robert Carr1f0a16a2016-10-24 16:27:39 -07001340 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001341 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001342 lt = layerTransform.transform(lt);
1343 lb = layerTransform.transform(lb);
1344 rb = layerTransform.transform(rb);
1345 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001346 }
1347
Robert Carrb5d3d262016-03-25 15:08:13 -07001348 if (!s.finalCrop.isEmpty()) {
1349 boundPoint(&lt, s.finalCrop);
1350 boundPoint(&lb, s.finalCrop);
1351 boundPoint(&rb, s.finalCrop);
1352 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001353 }
1354
Mathias Agopianff2ed702013-09-01 21:36:12 -07001355 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001356 position[0] = hwTransform.transform(lt);
1357 position[1] = hwTransform.transform(lb);
1358 position[2] = hwTransform.transform(rb);
1359 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001360 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001361 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001362 }
1363}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001364
Andy McFadden4125a4f2014-01-29 17:17:11 -08001365bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001366{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001367 // if we don't have a buffer yet, we're translucent regardless of the
1368 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001369 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001370 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001371 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001372
1373 // if the layer has the opaque flag, then we're always opaque,
1374 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001375 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001376}
1377
Dan Stoza23116082015-06-18 14:58:39 -07001378bool Layer::isSecure() const
1379{
1380 const Layer::State& s(mDrawingState);
1381 return (s.flags & layer_state_t::eLayerSecure);
1382}
1383
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001384bool Layer::isProtected() const
1385{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001386 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001387 return (activeBuffer != 0) &&
1388 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1389}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001390
Mathias Agopian13127d82013-03-05 17:47:11 -08001391bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001392 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001393}
1394
1395bool Layer::isCropped() const {
1396 return !mCurrentCrop.isEmpty();
1397}
1398
1399bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1400 return mNeedsFiltering || hw->needsFiltering();
1401}
1402
1403void Layer::setVisibleRegion(const Region& visibleRegion) {
1404 // always called from main thread
1405 this->visibleRegion = visibleRegion;
1406}
1407
1408void Layer::setCoveredRegion(const Region& coveredRegion) {
1409 // always called from main thread
1410 this->coveredRegion = coveredRegion;
1411}
1412
1413void Layer::setVisibleNonTransparentRegion(const Region&
1414 setVisibleNonTransparentRegion) {
1415 // always called from main thread
1416 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1417}
1418
1419// ----------------------------------------------------------------------------
1420// transaction
1421// ----------------------------------------------------------------------------
1422
Dan Stoza7dde5992015-05-22 09:51:44 -07001423void Layer::pushPendingState() {
1424 if (!mCurrentState.modified) {
1425 return;
1426 }
1427
Dan Stoza7dde5992015-05-22 09:51:44 -07001428 // If this transaction is waiting on the receipt of a frame, generate a sync
1429 // point and send it to the remote layer.
1430 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001431 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1432 sp<Handle> handle = nullptr;
1433 sp<Layer> handleLayer = nullptr;
1434 if (strongBinder != nullptr) {
1435 handle = static_cast<Handle*>(strongBinder.get());
1436 handleLayer = handle->owner.promote();
1437 }
1438 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001439 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1440 // If we can't promote the layer we are intended to wait on,
1441 // then it is expired or otherwise invalid. Allow this transaction
1442 // to be applied as per normal (no synchronization).
1443 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001444 } else {
1445 auto syncPoint = std::make_shared<SyncPoint>(
1446 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001447 if (handleLayer->addSyncPoint(syncPoint)) {
1448 mRemoteSyncPoints.push_back(std::move(syncPoint));
1449 } else {
1450 // We already missed the frame we're supposed to synchronize
1451 // on, so go ahead and apply the state update
1452 mCurrentState.handle = nullptr;
1453 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001454 }
1455
Dan Stoza7dde5992015-05-22 09:51:44 -07001456 // Wake us up to check if the frame has been received
1457 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001458 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001459 }
1460 mPendingStates.push_back(mCurrentState);
1461}
1462
Pablo Ceballos05289c22016-04-14 15:49:55 -07001463void Layer::popPendingState(State* stateToCommit) {
1464 auto oldFlags = stateToCommit->flags;
1465 *stateToCommit = mPendingStates[0];
1466 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1467 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001468
1469 mPendingStates.removeAt(0);
1470}
1471
Pablo Ceballos05289c22016-04-14 15:49:55 -07001472bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001473 bool stateUpdateAvailable = false;
1474 while (!mPendingStates.empty()) {
1475 if (mPendingStates[0].handle != nullptr) {
1476 if (mRemoteSyncPoints.empty()) {
1477 // If we don't have a sync point for this, apply it anyway. It
1478 // will be visually wrong, but it should keep us from getting
1479 // into too much trouble.
1480 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001481 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001482 stateUpdateAvailable = true;
1483 continue;
1484 }
1485
Dan Stozacac35382016-01-27 12:21:06 -08001486 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1487 mPendingStates[0].frameNumber) {
1488 ALOGE("[%s] Unexpected sync point frame number found",
1489 mName.string());
1490
1491 // Signal our end of the sync point and then dispose of it
1492 mRemoteSyncPoints.front()->setTransactionApplied();
1493 mRemoteSyncPoints.pop_front();
1494 continue;
1495 }
1496
Dan Stoza7dde5992015-05-22 09:51:44 -07001497 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1498 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001499 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001500 stateUpdateAvailable = true;
1501
1502 // Signal our end of the sync point and then dispose of it
1503 mRemoteSyncPoints.front()->setTransactionApplied();
1504 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001505 } else {
1506 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001507 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001508 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001509 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001510 stateUpdateAvailable = true;
1511 }
1512 }
1513
1514 // If we still have pending updates, wake SurfaceFlinger back up and point
1515 // it at this layer so we can process them
1516 if (!mPendingStates.empty()) {
1517 setTransactionFlags(eTransactionNeeded);
1518 mFlinger->setTransactionFlags(eTraversalNeeded);
1519 }
1520
1521 mCurrentState.modified = false;
1522 return stateUpdateAvailable;
1523}
1524
1525void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001526 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001527 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001528 Mutex::Autolock lock(mLocalSyncPointMutex);
1529 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001530 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001531 point->setFrameAvailable();
1532 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001533 }
1534}
1535
Mathias Agopian13127d82013-03-05 17:47:11 -08001536uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001537 ATRACE_CALL();
1538
Dan Stoza7dde5992015-05-22 09:51:44 -07001539 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001540 Layer::State c = getCurrentState();
1541 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001542 return 0;
1543 }
1544
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001545 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001546
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001547 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1548 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001549
1550 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001551 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001552 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001553 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001554 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001555 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001556 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001557 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001558 this, getName().string(), mCurrentTransform,
1559 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001560 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001561 c.crop.left,
1562 c.crop.top,
1563 c.crop.right,
1564 c.crop.bottom,
1565 c.crop.getWidth(),
1566 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001567 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001568 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001569 s.crop.left,
1570 s.crop.top,
1571 s.crop.right,
1572 s.crop.bottom,
1573 s.crop.getWidth(),
1574 s.crop.getHeight(),
1575 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001576
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001577 // record the new size, form this point on, when the client request
1578 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001579 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001580 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001581 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001582
Robert Carr82364e32016-05-15 11:27:47 -07001583 const bool resizePending = (c.requested.w != c.active.w) ||
1584 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001585 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001586 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001587 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001588 // if we have a pending resize, unless we are in fixed-size mode.
1589 // the drawing state will be updated only once we receive a buffer
1590 // with the correct size.
1591 //
1592 // in particular, we want to make sure the clip (which is part
1593 // of the geometry state) is latched together with the size but is
1594 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001595 //
1596 // If a sideband stream is attached, however, we want to skip this
1597 // optimization so that transactions aren't missed when a buffer
1598 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001599
1600 flags |= eDontUpdateGeometryState;
1601 }
1602 }
1603
Mathias Agopian13127d82013-03-05 17:47:11 -08001604 // always set active to requested, unless we're asked not to
1605 // this is used by Layer, which special cases resizes.
1606 if (flags & eDontUpdateGeometryState) {
1607 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001608 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001609 if (mFreezePositionUpdates) {
1610 float tx = c.active.transform.tx();
1611 float ty = c.active.transform.ty();
1612 c.active = c.requested;
1613 c.active.transform.set(tx, ty);
1614 editCurrentState.active = c.active;
1615 } else {
1616 editCurrentState.active = editCurrentState.requested;
1617 c.active = c.requested;
1618 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001619 }
1620
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001621 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001622 // invalidate and recompute the visible regions if needed
1623 flags |= Layer::eVisibleRegion;
1624 }
1625
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001626 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001627 // invalidate and recompute the visible regions if needed
1628 flags |= eVisibleRegion;
1629 this->contentDirty = true;
1630
1631 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001632 const uint8_t type = c.active.transform.getType();
1633 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001634 (type >= Transform::SCALE));
1635 }
1636
Dan Stozac8145172016-04-28 16:29:06 -07001637 // If the layer is hidden, signal and clear out all local sync points so
1638 // that transactions for layers depending on this layer's frames becoming
1639 // visible are not blocked
1640 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001641 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001642 }
1643
Mathias Agopian13127d82013-03-05 17:47:11 -08001644 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001645 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001646 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001647}
1648
Pablo Ceballos05289c22016-04-14 15:49:55 -07001649void Layer::commitTransaction(const State& stateToCommit) {
1650 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001651}
1652
Mathias Agopian13127d82013-03-05 17:47:11 -08001653uint32_t Layer::getTransactionFlags(uint32_t flags) {
1654 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1655}
1656
1657uint32_t Layer::setTransactionFlags(uint32_t flags) {
1658 return android_atomic_or(flags, &mTransactionFlags);
1659}
1660
Robert Carr82364e32016-05-15 11:27:47 -07001661bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001662 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001663 return false;
1664 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001665
1666 // We update the requested and active position simultaneously because
1667 // we want to apply the position portion of the transform matrix immediately,
1668 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001669 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001670 if (immediate && !mFreezePositionUpdates) {
1671 mCurrentState.active.transform.set(x, y);
1672 }
1673 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001674
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 Carr82364e32016-05-15 11:27:47 -07001679
Robert Carr1f0a16a2016-10-24 16:27:39 -07001680bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1681 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1682 if (idx < 0) {
1683 return false;
1684 }
1685 if (childLayer->setLayer(z)) {
1686 mCurrentChildren.removeAt(idx);
1687 mCurrentChildren.add(childLayer);
1688 }
1689 return true;
1690}
1691
Robert Carrae060832016-11-28 10:51:00 -08001692bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001693 if (mCurrentState.z == z)
1694 return false;
1695 mCurrentState.sequence++;
1696 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001697 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001698 setTransactionFlags(eTransactionNeeded);
1699 return true;
1700}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001701
Mathias Agopian13127d82013-03-05 17:47:11 -08001702bool Layer::setSize(uint32_t w, uint32_t h) {
1703 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1704 return false;
1705 mCurrentState.requested.w = w;
1706 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001707 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001708 setTransactionFlags(eTransactionNeeded);
1709 return true;
1710}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001711#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001712bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001713#else
1714bool Layer::setAlpha(uint8_t alpha) {
1715#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001716 if (mCurrentState.alpha == alpha)
1717 return false;
1718 mCurrentState.sequence++;
1719 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001720 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001721 setTransactionFlags(eTransactionNeeded);
1722 return true;
1723}
1724bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1725 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001726 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001727 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001728 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001729 setTransactionFlags(eTransactionNeeded);
1730 return true;
1731}
1732bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001733 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001734 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001735 setTransactionFlags(eTransactionNeeded);
1736 return true;
1737}
1738bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1739 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1740 if (mCurrentState.flags == newFlags)
1741 return false;
1742 mCurrentState.sequence++;
1743 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001744 mCurrentState.mask = mask;
1745 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001746 setTransactionFlags(eTransactionNeeded);
1747 return true;
1748}
Robert Carr99e27f02016-06-16 15:18:02 -07001749
1750bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001751 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001752 return false;
1753 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001754 mCurrentState.requestedCrop = crop;
1755 if (immediate) {
1756 mCurrentState.crop = crop;
1757 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001758 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001759 setTransactionFlags(eTransactionNeeded);
1760 return true;
1761}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001762bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001763 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001764 return false;
1765 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001766 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001767 mCurrentState.modified = true;
1768 setTransactionFlags(eTransactionNeeded);
1769 return true;
1770}
Mathias Agopian13127d82013-03-05 17:47:11 -08001771
Robert Carrc3574f72016-03-24 12:19:32 -07001772bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1773 if (scalingMode == mOverrideScalingMode)
1774 return false;
1775 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001776 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001777 return true;
1778}
1779
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001780void Layer::setInfo(uint32_t type, uint32_t appId) {
1781 mCurrentState.appId = appId;
1782 mCurrentState.type = type;
1783 mCurrentState.modified = true;
1784 setTransactionFlags(eTransactionNeeded);
1785}
1786
Robert Carrc3574f72016-03-24 12:19:32 -07001787uint32_t Layer::getEffectiveScalingMode() const {
1788 if (mOverrideScalingMode >= 0) {
1789 return mOverrideScalingMode;
1790 }
1791 return mCurrentScalingMode;
1792}
1793
Mathias Agopian13127d82013-03-05 17:47:11 -08001794bool Layer::setLayerStack(uint32_t layerStack) {
1795 if (mCurrentState.layerStack == layerStack)
1796 return false;
1797 mCurrentState.sequence++;
1798 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001799 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001800 setTransactionFlags(eTransactionNeeded);
1801 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001802}
1803
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001804bool Layer::setDataSpace(android_dataspace dataSpace) {
1805 if (mCurrentState.dataSpace == dataSpace)
1806 return false;
1807 mCurrentState.sequence++;
1808 mCurrentState.dataSpace = dataSpace;
1809 mCurrentState.modified = true;
1810 setTransactionFlags(eTransactionNeeded);
1811 return true;
1812}
1813
Robert Carr1f0a16a2016-10-24 16:27:39 -07001814uint32_t Layer::getLayerStack() const {
1815 auto p = getParent();
1816 if (p == nullptr) {
1817 return getDrawingState().layerStack;
1818 }
1819 return p->getLayerStack();
1820}
1821
Dan Stoza7dde5992015-05-22 09:51:44 -07001822void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1823 uint64_t frameNumber) {
1824 mCurrentState.handle = handle;
1825 mCurrentState.frameNumber = frameNumber;
1826 // We don't set eTransactionNeeded, because just receiving a deferral
1827 // request without any other state updates shouldn't actually induce a delay
1828 mCurrentState.modified = true;
1829 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001830 mCurrentState.handle = nullptr;
1831 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001832 mCurrentState.modified = false;
1833}
1834
Dan Stozaee44edd2015-03-23 15:50:23 -07001835void Layer::useSurfaceDamage() {
1836 if (mFlinger->mForceFullDamage) {
1837 surfaceDamageRegion = Region::INVALID_REGION;
1838 } else {
1839 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1840 }
1841}
1842
1843void Layer::useEmptyDamage() {
1844 surfaceDamageRegion.clear();
1845}
1846
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001847// ----------------------------------------------------------------------------
1848// pageflip handling...
1849// ----------------------------------------------------------------------------
1850
Dan Stoza6b9454d2014-11-07 16:00:59 -08001851bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001852 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001853 return true;
1854 }
1855
Dan Stoza6b9454d2014-11-07 16:00:59 -08001856 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001857 if (mQueueItems.empty()) {
1858 return false;
1859 }
1860 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001861 nsecs_t expectedPresent =
1862 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001863
1864 // Ignore timestamps more than a second in the future
1865 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1866 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1867 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1868 expectedPresent);
1869
1870 bool isDue = timestamp < expectedPresent;
1871 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001872}
1873
Brian Andersond6927fb2016-07-23 23:37:30 -07001874bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1875 if (mBufferLatched) {
1876 Mutex::Autolock lock(mFrameEventHistoryMutex);
1877 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1878 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001879 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001880 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001881}
1882
Brian Anderson3d4039d2016-09-23 16:31:30 -07001883bool Layer::onPostComposition(
1884 const std::shared_ptr<FenceTime>& glDoneFence,
1885 const std::shared_ptr<FenceTime>& presentFence,
1886 const std::shared_ptr<FenceTime>& retireFence) {
1887 mAcquireTimeline.updateSignalTimes();
1888 mReleaseTimeline.updateSignalTimes();
1889
Brian Andersond6927fb2016-07-23 23:37:30 -07001890 // mFrameLatencyNeeded is true when a new frame was latched for the
1891 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001892 if (!mFrameLatencyNeeded)
1893 return false;
1894
Fabien Sanglard28e98082016-12-05 10:19:46 -08001895 // Update mFrameEventHistory.
1896 {
1897 Mutex::Autolock lock(mFrameEventHistoryMutex);
1898 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001899 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001900 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1901 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001902 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001903
1904 // Update mFrameTracker.
1905 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1906 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1907
Brian Anderson3d4039d2016-09-23 16:31:30 -07001908 std::shared_ptr<FenceTime> frameReadyFence =
1909 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001910 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001911 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001912 } else {
1913 // There was no fence for this frame, so assume that it was ready
1914 // to be presented at the desired present time.
1915 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1916 }
1917
Brian Anderson3d4039d2016-09-23 16:31:30 -07001918 if (presentFence->isValid()) {
1919 mFrameTracker.setActualPresentFence(
1920 std::shared_ptr<FenceTime>(presentFence));
1921 } else if (retireFence->isValid()) {
1922 mFrameTracker.setActualPresentFence(
1923 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001924 } else {
1925 // The HWC doesn't support present fences, so use the refresh
1926 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001927 mFrameTracker.setActualPresentTime(
1928 mFlinger->getHwComposer().getRefreshTimestamp(
1929 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001930 }
1931
1932 mFrameTracker.advanceFrame();
1933 mFrameLatencyNeeded = false;
1934 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001935}
1936
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001937#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07001938void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001939 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001940 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001941 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001942 mReleaseTimeline.push(releaseFenceTime);
1943
1944 Mutex::Autolock lock(mFrameEventHistoryMutex);
1945 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07001946 mPreviousFrameNumber, dequeueReadyTime, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001947}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001948#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949
Robert Carr1f0a16a2016-10-24 16:27:39 -07001950bool Layer::isHiddenByPolicy() const {
1951 const Layer::State& s(mDrawingState);
1952 const auto& parent = getParent();
1953 if (parent != nullptr && parent->isHiddenByPolicy()) {
1954 return true;
1955 }
1956 return s.flags & layer_state_t::eLayerHidden;
1957}
1958
Mathias Agopianda27af92012-09-13 18:17:13 -07001959bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001960 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001961#ifdef USE_HWC2
Robert Carr1f0a16a2016-10-24 16:27:39 -07001962 return !(isHiddenByPolicy()) && s.alpha > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08001963 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001964#else
Robert Carr1f0a16a2016-10-24 16:27:39 -07001965 return !(isHiddenByPolicy()) && s.alpha
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001966 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1967#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001968}
1969
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001970bool Layer::allTransactionsSignaled() {
1971 auto headFrameNumber = getHeadFrameNumber();
1972 bool matchingFramesFound = false;
1973 bool allTransactionsApplied = true;
1974 Mutex::Autolock lock(mLocalSyncPointMutex);
1975
1976 for (auto& point : mLocalSyncPoints) {
1977 if (point->getFrameNumber() > headFrameNumber) {
1978 break;
1979 }
1980 matchingFramesFound = true;
1981
1982 if (!point->frameIsAvailable()) {
1983 // We haven't notified the remote layer that the frame for
1984 // this point is available yet. Notify it now, and then
1985 // abort this attempt to latch.
1986 point->setFrameAvailable();
1987 allTransactionsApplied = false;
1988 break;
1989 }
1990
1991 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1992 }
1993 return !matchingFramesFound || allTransactionsApplied;
1994}
1995
Brian Andersond6927fb2016-07-23 23:37:30 -07001996Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001998 ATRACE_CALL();
1999
Jesse Hall399184a2014-03-03 15:42:54 -08002000 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2001 // mSidebandStreamChanged was true
2002 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002003 if (mSidebandStream != NULL) {
2004 setTransactionFlags(eTransactionNeeded);
2005 mFlinger->setTransactionFlags(eTraversalNeeded);
2006 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002007 recomputeVisibleRegions = true;
2008
2009 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002010 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002011 }
2012
Mathias Agopian4fec8732012-06-29 14:12:52 -07002013 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002014 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2015 return outDirtyRegion;
2016 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002017
Fabien Sanglard223eb912016-10-13 10:15:06 -07002018 // if we've already called updateTexImage() without going through
2019 // a composition step, we have to skip this layer at this point
2020 // because we cannot call updateTeximage() without a corresponding
2021 // compositionComplete() call.
2022 // we'll trigger an update in onPreComposition().
2023 if (mRefreshPending) {
2024 return outDirtyRegion;
2025 }
2026
2027 // If the head buffer's acquire fence hasn't signaled yet, return and
2028 // try again later
2029 if (!headFenceHasSignaled()) {
2030 mFlinger->signalLayerUpdate();
2031 return outDirtyRegion;
2032 }
2033
2034 // Capture the old state of the layer for comparisons later
2035 const State& s(getDrawingState());
2036 const bool oldOpacity = isOpaque(s);
2037 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2038
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002039 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002040 mFlinger->signalLayerUpdate();
2041 return outDirtyRegion;
2042 }
2043
2044 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2045 // of the buffer queue isn't modified when the buffer queue is returning
2046 // BufferItem's that weren't actually queued. This can happen in shared
2047 // buffer mode.
2048 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002049 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2050 getProducerStickyTransform() != 0, mName.string(),
2051 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002052 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2053 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2054 mLastFrameNumberReceived);
2055 if (updateResult == BufferQueue::PRESENT_LATER) {
2056 // Producer doesn't want buffer to be displayed yet. Signal a
2057 // layer update so we check again at the next opportunity.
2058 mFlinger->signalLayerUpdate();
2059 return outDirtyRegion;
2060 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2061 // If the buffer has been rejected, remove it from the shadow queue
2062 // and return early
2063 if (queuedBuffer) {
2064 Mutex::Autolock lock(mQueueItemLock);
2065 mQueueItems.removeAt(0);
2066 android_atomic_dec(&mQueuedFrames);
2067 }
2068 return outDirtyRegion;
2069 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2070 // This can occur if something goes wrong when trying to create the
2071 // EGLImage for this buffer. If this happens, the buffer has already
2072 // been released, so we need to clean up the queue and bug out
2073 // early.
2074 if (queuedBuffer) {
2075 Mutex::Autolock lock(mQueueItemLock);
2076 mQueueItems.clear();
2077 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002078 }
2079
Fabien Sanglard223eb912016-10-13 10:15:06 -07002080 // Once we have hit this state, the shadow queue may no longer
2081 // correctly reflect the incoming BufferQueue's contents, so even if
2082 // updateTexImage starts working, the only safe course of action is
2083 // to continue to ignore updates.
2084 mUpdateTexImageFailed = true;
2085
2086 return outDirtyRegion;
2087 }
2088
2089 if (queuedBuffer) {
2090 // Autolock scope
2091 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2092
2093 Mutex::Autolock lock(mQueueItemLock);
2094
2095 // Remove any stale buffers that have been dropped during
2096 // updateTexImage
2097 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2098 mQueueItems.removeAt(0);
2099 android_atomic_dec(&mQueuedFrames);
2100 }
2101
2102 mQueueItems.removeAt(0);
2103 }
2104
2105
2106 // Decrement the queued-frames count. Signal another event if we
2107 // have more frames pending.
2108 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2109 || mAutoRefresh) {
2110 mFlinger->signalLayerUpdate();
2111 }
2112
Fabien Sanglard223eb912016-10-13 10:15:06 -07002113 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002114 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2115 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002116 if (mActiveBuffer == NULL) {
2117 // this can only happen if the very first buffer was rejected.
2118 return outDirtyRegion;
2119 }
2120
Brian Andersond6927fb2016-07-23 23:37:30 -07002121 mBufferLatched = true;
2122 mPreviousFrameNumber = mCurrentFrameNumber;
2123 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2124
2125 {
2126 Mutex::Autolock lock(mFrameEventHistoryMutex);
2127 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2128#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002129 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002130 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002131 mReleaseTimeline.push(releaseFenceTime);
2132 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07002133 mPreviousFrameNumber, latchTime, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07002134#endif
2135 }
2136
Fabien Sanglard223eb912016-10-13 10:15:06 -07002137 mRefreshPending = true;
2138 mFrameLatencyNeeded = true;
2139 if (oldActiveBuffer == NULL) {
2140 // the first time we receive a buffer, we need to trigger a
2141 // geometry invalidation.
2142 recomputeVisibleRegions = true;
2143 }
2144
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002145 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2146
Fabien Sanglard223eb912016-10-13 10:15:06 -07002147 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2148 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2149 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2150 if ((crop != mCurrentCrop) ||
2151 (transform != mCurrentTransform) ||
2152 (scalingMode != mCurrentScalingMode))
2153 {
2154 mCurrentCrop = crop;
2155 mCurrentTransform = transform;
2156 mCurrentScalingMode = scalingMode;
2157 recomputeVisibleRegions = true;
2158 }
2159
2160 if (oldActiveBuffer != NULL) {
2161 uint32_t bufWidth = mActiveBuffer->getWidth();
2162 uint32_t bufHeight = mActiveBuffer->getHeight();
2163 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2164 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002165 recomputeVisibleRegions = true;
2166 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002167 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002168
Fabien Sanglard223eb912016-10-13 10:15:06 -07002169 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2170 if (oldOpacity != isOpaque(s)) {
2171 recomputeVisibleRegions = true;
2172 }
Dan Stozacac35382016-01-27 12:21:06 -08002173
Fabien Sanglard223eb912016-10-13 10:15:06 -07002174 // Remove any sync points corresponding to the buffer which was just
2175 // latched
2176 {
2177 Mutex::Autolock lock(mLocalSyncPointMutex);
2178 auto point = mLocalSyncPoints.begin();
2179 while (point != mLocalSyncPoints.end()) {
2180 if (!(*point)->frameIsAvailable() ||
2181 !(*point)->transactionIsApplied()) {
2182 // This sync point must have been added since we started
2183 // latching. Don't drop it yet.
2184 ++point;
2185 continue;
2186 }
2187
2188 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2189 point = mLocalSyncPoints.erase(point);
2190 } else {
2191 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002192 }
2193 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002194 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002195
2196 // FIXME: postedRegion should be dirty & bounds
2197 Region dirtyRegion(Rect(s.active.w, s.active.h));
2198
2199 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002200 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002201
Mathias Agopian4fec8732012-06-29 14:12:52 -07002202 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203}
2204
Mathias Agopiana67932f2011-04-20 14:20:59 -07002205uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002206{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002207 // TODO: should we do something special if mSecure is set?
2208 if (mProtectedByApp) {
2209 // need a hardware-protected path to external video sink
2210 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002211 }
Riley Andrews03414a12014-07-01 14:22:59 -07002212 if (mPotentialCursor) {
2213 usage |= GraphicBuffer::USAGE_CURSOR;
2214 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002215 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002216 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002217}
2218
Mathias Agopian84300952012-11-21 16:02:13 -08002219void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002220 uint32_t orientation = 0;
2221 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002222 // The transform hint is used to improve performance, but we can
2223 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002224 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002225 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002226 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002227 if (orientation & Transform::ROT_INVALID) {
2228 orientation = 0;
2229 }
2230 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002231 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002232}
2233
Mathias Agopian13127d82013-03-05 17:47:11 -08002234// ----------------------------------------------------------------------------
2235// debugging
2236// ----------------------------------------------------------------------------
2237
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002238void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002239{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002240 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002241
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002242 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002243 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002244 "+ %s %p (%s)\n",
2245 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002246 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002247
Mathias Agopian2ca79392013-04-02 18:30:32 -07002248 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002249 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002250 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002251 sp<Client> client(mClientRef.promote());
2252
Mathias Agopian74d211a2013-04-22 16:55:35 +02002253 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002254 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2255 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002256 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002257#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002258 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002259#else
2260 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2261#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002262 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002263 getLayerStack(), s.z,
2264 s.active.transform.tx(), s.active.transform.ty(),
2265 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002266 s.crop.left, s.crop.top,
2267 s.crop.right, s.crop.bottom,
2268 s.finalCrop.left, s.finalCrop.top,
2269 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002270 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002271 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002272 s.active.transform[0][0], s.active.transform[0][1],
2273 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002274 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002275
2276 sp<const GraphicBuffer> buf0(mActiveBuffer);
2277 uint32_t w0=0, h0=0, s0=0, f0=0;
2278 if (buf0 != 0) {
2279 w0 = buf0->getWidth();
2280 h0 = buf0->getHeight();
2281 s0 = buf0->getStride();
2282 f0 = buf0->format;
2283 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002284 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002285 " "
2286 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2287 " queued-frames=%d, mRefreshPending=%d\n",
2288 mFormat, w0, h0, s0,f0,
2289 mQueuedFrames, mRefreshPending);
2290
Mathias Agopian13127d82013-03-05 17:47:11 -08002291 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002292 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002293 }
2294}
2295
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002296#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002297void Layer::miniDumpHeader(String8& result) {
2298 result.append("----------------------------------------");
2299 result.append("---------------------------------------\n");
2300 result.append(" Layer name\n");
2301 result.append(" Z | ");
2302 result.append(" Comp Type | ");
2303 result.append(" Disp Frame (LTRB) | ");
2304 result.append(" Source Crop (LTRB)\n");
2305 result.append("----------------------------------------");
2306 result.append("---------------------------------------\n");
2307}
2308
2309void Layer::miniDump(String8& result, int32_t hwcId) const {
2310 if (mHwcLayers.count(hwcId) == 0) {
2311 return;
2312 }
2313
2314 String8 name;
2315 if (mName.length() > 77) {
2316 std::string shortened;
2317 shortened.append(mName.string(), 36);
2318 shortened.append("[...]");
2319 shortened.append(mName.string() + (mName.length() - 36), 36);
2320 name = shortened.c_str();
2321 } else {
2322 name = mName;
2323 }
2324
2325 result.appendFormat(" %s\n", name.string());
2326
2327 const Layer::State& layerState(getDrawingState());
2328 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2329 result.appendFormat(" %10u | ", layerState.z);
2330 result.appendFormat("%10s | ",
2331 to_string(getCompositionType(hwcId)).c_str());
2332 const Rect& frame = hwcInfo.displayFrame;
2333 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2334 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002335 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002336 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2337 crop.right, crop.bottom);
2338
2339 result.append("- - - - - - - - - - - - - - - - - - - - ");
2340 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2341}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002342#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002343
Svetoslavd85084b2014-03-20 10:28:31 -07002344void Layer::dumpFrameStats(String8& result) const {
2345 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002346}
2347
Svetoslavd85084b2014-03-20 10:28:31 -07002348void Layer::clearFrameStats() {
2349 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002350}
2351
Jamie Gennis6547ff42013-07-16 20:12:42 -07002352void Layer::logFrameStats() {
2353 mFrameTracker.logAndResetStats(mName);
2354}
2355
Svetoslavd85084b2014-03-20 10:28:31 -07002356void Layer::getFrameStats(FrameStats* outStats) const {
2357 mFrameTracker.getStats(outStats);
2358}
2359
Brian Andersond6927fb2016-07-23 23:37:30 -07002360void Layer::dumpFrameEvents(String8& result) {
2361 result.appendFormat("- Layer %s (%s, %p)\n",
2362 getName().string(), getTypeId(), this);
2363 Mutex::Autolock lock(mFrameEventHistoryMutex);
2364 mFrameEventHistory.checkFencesForCompletion();
2365 mFrameEventHistory.dump(result);
2366}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002367
Brian Anderson3890c392016-07-25 12:48:08 -07002368void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2369 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002370 Mutex::Autolock lock(mFrameEventHistoryMutex);
2371 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002372 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002373 mFrameEventHistory.addQueue(*newTimestamps);
2374 }
2375
Brian Anderson3890c392016-07-25 12:48:08 -07002376 if (outDelta) {
2377 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002378 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002379}
Dan Stozae77c7662016-05-13 11:37:28 -07002380
2381std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2382 bool forceFlush) {
2383 std::vector<OccupancyTracker::Segment> history;
2384 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2385 &history);
2386 if (result != NO_ERROR) {
2387 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2388 result);
2389 return {};
2390 }
2391 return history;
2392}
2393
Robert Carr367c5682016-06-20 11:55:28 -07002394bool Layer::getTransformToDisplayInverse() const {
2395 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2396}
2397
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398void Layer::addChild(const sp<Layer>& layer) {
2399 mCurrentChildren.add(layer);
2400 layer->setParent(this);
2401}
2402
2403ssize_t Layer::removeChild(const sp<Layer>& layer) {
2404 layer->setParent(nullptr);
2405 return mCurrentChildren.remove(layer);
2406}
2407
Robert Carr1db73f62016-12-21 12:58:51 -08002408bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2409 sp<Handle> handle = nullptr;
2410 sp<Layer> newParent = nullptr;
2411 if (newParentHandle == nullptr) {
2412 return false;
2413 }
2414 handle = static_cast<Handle*>(newParentHandle.get());
2415 newParent = handle->owner.promote();
2416 if (newParent == nullptr) {
2417 ALOGE("Unable to promote Layer handle");
2418 return false;
2419 }
2420
2421 for (const sp<Layer>& child : mCurrentChildren) {
2422 newParent->addChild(child);
2423
2424 sp<Client> client(child->mClientRef.promote());
2425 if (client != nullptr) {
2426 client->setParentLayer(newParent);
2427 }
2428 }
2429 mCurrentChildren.clear();
2430
2431 return true;
2432}
2433
Robert Carr1f0a16a2016-10-24 16:27:39 -07002434void Layer::setParent(const sp<Layer>& layer) {
2435 mParent = layer;
2436}
2437
2438void Layer::clearSyncPoints() {
2439 for (const auto& child : mCurrentChildren) {
2440 child->clearSyncPoints();
2441 }
2442
2443 Mutex::Autolock lock(mLocalSyncPointMutex);
2444 for (auto& point : mLocalSyncPoints) {
2445 point->setFrameAvailable();
2446 }
2447 mLocalSyncPoints.clear();
2448}
2449
2450int32_t Layer::getZ() const {
2451 return mDrawingState.z;
2452}
2453
2454/**
2455 * Negatively signed children are before 'this' in Z-order.
2456 */
2457void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) {
2458 size_t i = 0;
2459 for (; i < mDrawingChildren.size(); i++) {
2460 const auto& child = mDrawingChildren[i];
2461 if (child->getZ() >= 0)
2462 break;
2463 child->traverseInZOrder(exec);
2464 }
2465 exec(this);
2466 for (; i < mDrawingChildren.size(); i++) {
2467 const auto& child = mDrawingChildren[i];
2468 child->traverseInZOrder(exec);
2469 }
2470}
2471
2472/**
2473 * Positively signed children are before 'this' in reverse Z-order.
2474 */
2475void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) {
2476 int32_t i = 0;
2477 for (i = mDrawingChildren.size()-1; i>=0; i--) {
2478 const auto& child = mDrawingChildren[i];
2479 if (child->getZ() < 0) {
2480 break;
2481 }
2482 child->traverseInReverseZOrder(exec);
2483 }
2484 exec(this);
2485 for (; i>=0; i--) {
2486 const auto& child = mDrawingChildren[i];
2487 child->traverseInReverseZOrder(exec);
2488 }
2489}
2490
2491Transform Layer::getTransform() const {
2492 Transform t;
2493 const auto& p = getParent();
2494 if (p != nullptr) {
2495 t = p->getTransform();
2496 }
2497 return t * getDrawingState().active.transform;
2498}
2499
2500void Layer::commitChildList() {
2501 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2502 const auto& child = mCurrentChildren[i];
2503 child->commitChildList();
2504 }
2505 mDrawingChildren = mCurrentChildren;
2506}
2507
Mathias Agopian13127d82013-03-05 17:47:11 -08002508// ---------------------------------------------------------------------------
2509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002510}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002511
2512#if defined(__gl_h_)
2513#error "don't include gl/gl.h in this file"
2514#endif
2515
2516#if defined(__gl2_h_)
2517#error "don't include gl2/gl2.h in this file"
2518#endif