blob: bb1fca68d76084f02b012f548793c18141d6af8d [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:
Romain Guy541f2262017-02-10 18:50:17 -08001302 case HAL_PIXEL_FORMAT_RGBA_1010102:
Mathias Agopiandd533712013-07-26 15:31:39 -07001303 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001304 }
1305 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001306 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001307}
1308
Mathias Agopian13127d82013-03-05 17:47:11 -08001309// ----------------------------------------------------------------------------
1310// local state
1311// ----------------------------------------------------------------------------
1312
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001313static void boundPoint(vec2* point, const Rect& crop) {
1314 if (point->x < crop.left) {
1315 point->x = crop.left;
1316 }
1317 if (point->x > crop.right) {
1318 point->x = crop.right;
1319 }
1320 if (point->y < crop.top) {
1321 point->y = crop.top;
1322 }
1323 if (point->y > crop.bottom) {
1324 point->y = crop.bottom;
1325 }
1326}
1327
Dan Stozac7014012014-02-14 15:03:43 -08001328void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1329 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001330{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001331 const Layer::State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001332 const Transform hwTransform(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001333 const uint32_t hw_h = hw->getHeight();
Robert Carr1f0a16a2016-10-24 16:27:39 -07001334 Rect win = computeBounds();
Mathias Agopian3f844832013-08-07 21:24:32 -07001335
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001336 vec2 lt = vec2(win.left, win.top);
1337 vec2 lb = vec2(win.left, win.bottom);
1338 vec2 rb = vec2(win.right, win.bottom);
1339 vec2 rt = vec2(win.right, win.top);
1340
Robert Carr1f0a16a2016-10-24 16:27:39 -07001341 Transform layerTransform = getTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001342 if (!useIdentityTransform) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001343 lt = layerTransform.transform(lt);
1344 lb = layerTransform.transform(lb);
1345 rb = layerTransform.transform(rb);
1346 rt = layerTransform.transform(rt);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001347 }
1348
Robert Carrb5d3d262016-03-25 15:08:13 -07001349 if (!s.finalCrop.isEmpty()) {
1350 boundPoint(&lt, s.finalCrop);
1351 boundPoint(&lb, s.finalCrop);
1352 boundPoint(&rb, s.finalCrop);
1353 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001354 }
1355
Mathias Agopianff2ed702013-09-01 21:36:12 -07001356 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Robert Carr1f0a16a2016-10-24 16:27:39 -07001357 position[0] = hwTransform.transform(lt);
1358 position[1] = hwTransform.transform(lb);
1359 position[2] = hwTransform.transform(rb);
1360 position[3] = hwTransform.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001361 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001362 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001363 }
1364}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001365
Andy McFadden4125a4f2014-01-29 17:17:11 -08001366bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001367{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001368 // if we don't have a buffer yet, we're translucent regardless of the
1369 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001370 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001371 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001372 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001373
1374 // if the layer has the opaque flag, then we're always opaque,
1375 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001376 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001377}
1378
Dan Stoza23116082015-06-18 14:58:39 -07001379bool Layer::isSecure() const
1380{
1381 const Layer::State& s(mDrawingState);
1382 return (s.flags & layer_state_t::eLayerSecure);
1383}
1384
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001385bool Layer::isProtected() const
1386{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001387 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001388 return (activeBuffer != 0) &&
1389 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1390}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001391
Mathias Agopian13127d82013-03-05 17:47:11 -08001392bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001393 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001394}
1395
1396bool Layer::isCropped() const {
1397 return !mCurrentCrop.isEmpty();
1398}
1399
1400bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1401 return mNeedsFiltering || hw->needsFiltering();
1402}
1403
1404void Layer::setVisibleRegion(const Region& visibleRegion) {
1405 // always called from main thread
1406 this->visibleRegion = visibleRegion;
1407}
1408
1409void Layer::setCoveredRegion(const Region& coveredRegion) {
1410 // always called from main thread
1411 this->coveredRegion = coveredRegion;
1412}
1413
1414void Layer::setVisibleNonTransparentRegion(const Region&
1415 setVisibleNonTransparentRegion) {
1416 // always called from main thread
1417 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1418}
1419
1420// ----------------------------------------------------------------------------
1421// transaction
1422// ----------------------------------------------------------------------------
1423
Dan Stoza7dde5992015-05-22 09:51:44 -07001424void Layer::pushPendingState() {
1425 if (!mCurrentState.modified) {
1426 return;
1427 }
1428
Dan Stoza7dde5992015-05-22 09:51:44 -07001429 // If this transaction is waiting on the receipt of a frame, generate a sync
1430 // point and send it to the remote layer.
1431 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001432 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1433 sp<Handle> handle = nullptr;
1434 sp<Layer> handleLayer = nullptr;
1435 if (strongBinder != nullptr) {
1436 handle = static_cast<Handle*>(strongBinder.get());
1437 handleLayer = handle->owner.promote();
1438 }
1439 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001440 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1441 // If we can't promote the layer we are intended to wait on,
1442 // then it is expired or otherwise invalid. Allow this transaction
1443 // to be applied as per normal (no synchronization).
1444 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001445 } else {
1446 auto syncPoint = std::make_shared<SyncPoint>(
1447 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001448 if (handleLayer->addSyncPoint(syncPoint)) {
1449 mRemoteSyncPoints.push_back(std::move(syncPoint));
1450 } else {
1451 // We already missed the frame we're supposed to synchronize
1452 // on, so go ahead and apply the state update
1453 mCurrentState.handle = nullptr;
1454 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001455 }
1456
Dan Stoza7dde5992015-05-22 09:51:44 -07001457 // Wake us up to check if the frame has been received
1458 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001459 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001460 }
1461 mPendingStates.push_back(mCurrentState);
1462}
1463
Pablo Ceballos05289c22016-04-14 15:49:55 -07001464void Layer::popPendingState(State* stateToCommit) {
1465 auto oldFlags = stateToCommit->flags;
1466 *stateToCommit = mPendingStates[0];
1467 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1468 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001469
1470 mPendingStates.removeAt(0);
1471}
1472
Pablo Ceballos05289c22016-04-14 15:49:55 -07001473bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001474 bool stateUpdateAvailable = false;
1475 while (!mPendingStates.empty()) {
1476 if (mPendingStates[0].handle != nullptr) {
1477 if (mRemoteSyncPoints.empty()) {
1478 // If we don't have a sync point for this, apply it anyway. It
1479 // will be visually wrong, but it should keep us from getting
1480 // into too much trouble.
1481 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001482 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001483 stateUpdateAvailable = true;
1484 continue;
1485 }
1486
Dan Stozacac35382016-01-27 12:21:06 -08001487 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1488 mPendingStates[0].frameNumber) {
1489 ALOGE("[%s] Unexpected sync point frame number found",
1490 mName.string());
1491
1492 // Signal our end of the sync point and then dispose of it
1493 mRemoteSyncPoints.front()->setTransactionApplied();
1494 mRemoteSyncPoints.pop_front();
1495 continue;
1496 }
1497
Dan Stoza7dde5992015-05-22 09:51:44 -07001498 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1499 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001500 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001501 stateUpdateAvailable = true;
1502
1503 // Signal our end of the sync point and then dispose of it
1504 mRemoteSyncPoints.front()->setTransactionApplied();
1505 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001506 } else {
1507 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001508 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001509 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001510 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001511 stateUpdateAvailable = true;
1512 }
1513 }
1514
1515 // If we still have pending updates, wake SurfaceFlinger back up and point
1516 // it at this layer so we can process them
1517 if (!mPendingStates.empty()) {
1518 setTransactionFlags(eTransactionNeeded);
1519 mFlinger->setTransactionFlags(eTraversalNeeded);
1520 }
1521
1522 mCurrentState.modified = false;
1523 return stateUpdateAvailable;
1524}
1525
1526void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001527 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001528 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001529 Mutex::Autolock lock(mLocalSyncPointMutex);
1530 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001531 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001532 point->setFrameAvailable();
1533 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001534 }
1535}
1536
Mathias Agopian13127d82013-03-05 17:47:11 -08001537uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001538 ATRACE_CALL();
1539
Dan Stoza7dde5992015-05-22 09:51:44 -07001540 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001541 Layer::State c = getCurrentState();
1542 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001543 return 0;
1544 }
1545
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001546 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001547
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001548 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1549 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001550
1551 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001552 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001553 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001554 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001555 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001556 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001557 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001558 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001559 this, getName().string(), mCurrentTransform,
1560 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001561 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001562 c.crop.left,
1563 c.crop.top,
1564 c.crop.right,
1565 c.crop.bottom,
1566 c.crop.getWidth(),
1567 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001568 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001569 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001570 s.crop.left,
1571 s.crop.top,
1572 s.crop.right,
1573 s.crop.bottom,
1574 s.crop.getWidth(),
1575 s.crop.getHeight(),
1576 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001577
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001578 // record the new size, form this point on, when the client request
1579 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001580 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001581 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001582 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001583
Robert Carr82364e32016-05-15 11:27:47 -07001584 const bool resizePending = (c.requested.w != c.active.w) ||
1585 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001586 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001587 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001588 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001589 // if we have a pending resize, unless we are in fixed-size mode.
1590 // the drawing state will be updated only once we receive a buffer
1591 // with the correct size.
1592 //
1593 // in particular, we want to make sure the clip (which is part
1594 // of the geometry state) is latched together with the size but is
1595 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001596 //
1597 // If a sideband stream is attached, however, we want to skip this
1598 // optimization so that transactions aren't missed when a buffer
1599 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001600
1601 flags |= eDontUpdateGeometryState;
1602 }
1603 }
1604
Mathias Agopian13127d82013-03-05 17:47:11 -08001605 // always set active to requested, unless we're asked not to
1606 // this is used by Layer, which special cases resizes.
1607 if (flags & eDontUpdateGeometryState) {
1608 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001609 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001610 if (mFreezePositionUpdates) {
1611 float tx = c.active.transform.tx();
1612 float ty = c.active.transform.ty();
1613 c.active = c.requested;
1614 c.active.transform.set(tx, ty);
1615 editCurrentState.active = c.active;
1616 } else {
1617 editCurrentState.active = editCurrentState.requested;
1618 c.active = c.requested;
1619 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001620 }
1621
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001622 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001623 // invalidate and recompute the visible regions if needed
1624 flags |= Layer::eVisibleRegion;
1625 }
1626
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001627 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001628 // invalidate and recompute the visible regions if needed
1629 flags |= eVisibleRegion;
1630 this->contentDirty = true;
1631
1632 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001633 const uint8_t type = c.active.transform.getType();
1634 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001635 (type >= Transform::SCALE));
1636 }
1637
Dan Stozac8145172016-04-28 16:29:06 -07001638 // If the layer is hidden, signal and clear out all local sync points so
1639 // that transactions for layers depending on this layer's frames becoming
1640 // visible are not blocked
1641 if (c.flags & layer_state_t::eLayerHidden) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001642 clearSyncPoints();
Dan Stozac8145172016-04-28 16:29:06 -07001643 }
1644
Mathias Agopian13127d82013-03-05 17:47:11 -08001645 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001646 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001647 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001648}
1649
Pablo Ceballos05289c22016-04-14 15:49:55 -07001650void Layer::commitTransaction(const State& stateToCommit) {
1651 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001652}
1653
Mathias Agopian13127d82013-03-05 17:47:11 -08001654uint32_t Layer::getTransactionFlags(uint32_t flags) {
1655 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1656}
1657
1658uint32_t Layer::setTransactionFlags(uint32_t flags) {
1659 return android_atomic_or(flags, &mTransactionFlags);
1660}
1661
Robert Carr82364e32016-05-15 11:27:47 -07001662bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001663 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001664 return false;
1665 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001666
1667 // We update the requested and active position simultaneously because
1668 // we want to apply the position portion of the transform matrix immediately,
1669 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001670 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001671 if (immediate && !mFreezePositionUpdates) {
1672 mCurrentState.active.transform.set(x, y);
1673 }
1674 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001675
Dan Stoza7dde5992015-05-22 09:51:44 -07001676 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001677 setTransactionFlags(eTransactionNeeded);
1678 return true;
1679}
Robert Carr82364e32016-05-15 11:27:47 -07001680
Robert Carr1f0a16a2016-10-24 16:27:39 -07001681bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1682 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1683 if (idx < 0) {
1684 return false;
1685 }
1686 if (childLayer->setLayer(z)) {
1687 mCurrentChildren.removeAt(idx);
1688 mCurrentChildren.add(childLayer);
1689 }
1690 return true;
1691}
1692
Robert Carrae060832016-11-28 10:51:00 -08001693bool Layer::setLayer(int32_t z) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001694 if (mCurrentState.z == z)
1695 return false;
1696 mCurrentState.sequence++;
1697 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001698 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001699 setTransactionFlags(eTransactionNeeded);
1700 return true;
1701}
Robert Carr1f0a16a2016-10-24 16:27:39 -07001702
Mathias Agopian13127d82013-03-05 17:47:11 -08001703bool Layer::setSize(uint32_t w, uint32_t h) {
1704 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1705 return false;
1706 mCurrentState.requested.w = w;
1707 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001708 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001709 setTransactionFlags(eTransactionNeeded);
1710 return true;
1711}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001712#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001713bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001714#else
1715bool Layer::setAlpha(uint8_t alpha) {
1716#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001717 if (mCurrentState.alpha == alpha)
1718 return false;
1719 mCurrentState.sequence++;
1720 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001721 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001722 setTransactionFlags(eTransactionNeeded);
1723 return true;
1724}
1725bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1726 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001727 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001728 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001729 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001730 setTransactionFlags(eTransactionNeeded);
1731 return true;
1732}
1733bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001734 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001735 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001736 setTransactionFlags(eTransactionNeeded);
1737 return true;
1738}
1739bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1740 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1741 if (mCurrentState.flags == newFlags)
1742 return false;
1743 mCurrentState.sequence++;
1744 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001745 mCurrentState.mask = mask;
1746 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001747 setTransactionFlags(eTransactionNeeded);
1748 return true;
1749}
Robert Carr99e27f02016-06-16 15:18:02 -07001750
1751bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001752 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001753 return false;
1754 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001755 mCurrentState.requestedCrop = crop;
1756 if (immediate) {
1757 mCurrentState.crop = crop;
1758 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001759 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001760 setTransactionFlags(eTransactionNeeded);
1761 return true;
1762}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001763bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001764 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001765 return false;
1766 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001767 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001768 mCurrentState.modified = true;
1769 setTransactionFlags(eTransactionNeeded);
1770 return true;
1771}
Mathias Agopian13127d82013-03-05 17:47:11 -08001772
Robert Carrc3574f72016-03-24 12:19:32 -07001773bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1774 if (scalingMode == mOverrideScalingMode)
1775 return false;
1776 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001777 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001778 return true;
1779}
1780
Daniel Nicoara2f5f8a52016-12-20 16:11:58 -05001781void Layer::setInfo(uint32_t type, uint32_t appId) {
1782 mCurrentState.appId = appId;
1783 mCurrentState.type = type;
1784 mCurrentState.modified = true;
1785 setTransactionFlags(eTransactionNeeded);
1786}
1787
Robert Carrc3574f72016-03-24 12:19:32 -07001788uint32_t Layer::getEffectiveScalingMode() const {
1789 if (mOverrideScalingMode >= 0) {
1790 return mOverrideScalingMode;
1791 }
1792 return mCurrentScalingMode;
1793}
1794
Mathias Agopian13127d82013-03-05 17:47:11 -08001795bool Layer::setLayerStack(uint32_t layerStack) {
1796 if (mCurrentState.layerStack == layerStack)
1797 return false;
1798 mCurrentState.sequence++;
1799 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001800 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001801 setTransactionFlags(eTransactionNeeded);
1802 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001803}
1804
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001805bool Layer::setDataSpace(android_dataspace dataSpace) {
1806 if (mCurrentState.dataSpace == dataSpace)
1807 return false;
1808 mCurrentState.sequence++;
1809 mCurrentState.dataSpace = dataSpace;
1810 mCurrentState.modified = true;
1811 setTransactionFlags(eTransactionNeeded);
1812 return true;
1813}
1814
Robert Carr1f0a16a2016-10-24 16:27:39 -07001815uint32_t Layer::getLayerStack() const {
1816 auto p = getParent();
1817 if (p == nullptr) {
1818 return getDrawingState().layerStack;
1819 }
1820 return p->getLayerStack();
1821}
1822
Dan Stoza7dde5992015-05-22 09:51:44 -07001823void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1824 uint64_t frameNumber) {
1825 mCurrentState.handle = handle;
1826 mCurrentState.frameNumber = frameNumber;
1827 // We don't set eTransactionNeeded, because just receiving a deferral
1828 // request without any other state updates shouldn't actually induce a delay
1829 mCurrentState.modified = true;
1830 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001831 mCurrentState.handle = nullptr;
1832 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001833 mCurrentState.modified = false;
1834}
1835
Dan Stozaee44edd2015-03-23 15:50:23 -07001836void Layer::useSurfaceDamage() {
1837 if (mFlinger->mForceFullDamage) {
1838 surfaceDamageRegion = Region::INVALID_REGION;
1839 } else {
1840 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1841 }
1842}
1843
1844void Layer::useEmptyDamage() {
1845 surfaceDamageRegion.clear();
1846}
1847
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001848// ----------------------------------------------------------------------------
1849// pageflip handling...
1850// ----------------------------------------------------------------------------
1851
Dan Stoza6b9454d2014-11-07 16:00:59 -08001852bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001853 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001854 return true;
1855 }
1856
Dan Stoza6b9454d2014-11-07 16:00:59 -08001857 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001858 if (mQueueItems.empty()) {
1859 return false;
1860 }
1861 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001862 nsecs_t expectedPresent =
1863 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001864
1865 // Ignore timestamps more than a second in the future
1866 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1867 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1868 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1869 expectedPresent);
1870
1871 bool isDue = timestamp < expectedPresent;
1872 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001873}
1874
Brian Andersond6927fb2016-07-23 23:37:30 -07001875bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1876 if (mBufferLatched) {
1877 Mutex::Autolock lock(mFrameEventHistoryMutex);
1878 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1879 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001880 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001881 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001882}
1883
Brian Anderson3d4039d2016-09-23 16:31:30 -07001884bool Layer::onPostComposition(
1885 const std::shared_ptr<FenceTime>& glDoneFence,
1886 const std::shared_ptr<FenceTime>& presentFence,
1887 const std::shared_ptr<FenceTime>& retireFence) {
1888 mAcquireTimeline.updateSignalTimes();
1889 mReleaseTimeline.updateSignalTimes();
1890
Brian Andersond6927fb2016-07-23 23:37:30 -07001891 // mFrameLatencyNeeded is true when a new frame was latched for the
1892 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001893 if (!mFrameLatencyNeeded)
1894 return false;
1895
Fabien Sanglard28e98082016-12-05 10:19:46 -08001896 // Update mFrameEventHistory.
1897 {
1898 Mutex::Autolock lock(mFrameEventHistoryMutex);
1899 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001900 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001901 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1902 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001903 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001904
1905 // Update mFrameTracker.
1906 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1907 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1908
Brian Anderson3d4039d2016-09-23 16:31:30 -07001909 std::shared_ptr<FenceTime> frameReadyFence =
1910 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001911 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001912 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001913 } else {
1914 // There was no fence for this frame, so assume that it was ready
1915 // to be presented at the desired present time.
1916 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1917 }
1918
Brian Anderson3d4039d2016-09-23 16:31:30 -07001919 if (presentFence->isValid()) {
1920 mFrameTracker.setActualPresentFence(
1921 std::shared_ptr<FenceTime>(presentFence));
1922 } else if (retireFence->isValid()) {
1923 mFrameTracker.setActualPresentFence(
1924 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001925 } else {
1926 // The HWC doesn't support present fences, so use the refresh
1927 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001928 mFrameTracker.setActualPresentTime(
1929 mFlinger->getHwComposer().getRefreshTimestamp(
1930 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001931 }
1932
1933 mFrameTracker.advanceFrame();
1934 mFrameLatencyNeeded = false;
1935 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001936}
1937
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001938#ifdef USE_HWC2
Brian Andersonf6386862016-10-31 16:34:13 -07001939void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001941 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001942 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001943 mReleaseTimeline.push(releaseFenceTime);
1944
1945 Mutex::Autolock lock(mFrameEventHistoryMutex);
1946 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07001947 mPreviousFrameNumber, dequeueReadyTime, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001949#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001950
Robert Carr1f0a16a2016-10-24 16:27:39 -07001951bool Layer::isHiddenByPolicy() const {
1952 const Layer::State& s(mDrawingState);
1953 const auto& parent = getParent();
1954 if (parent != nullptr && parent->isHiddenByPolicy()) {
1955 return true;
1956 }
1957 return s.flags & layer_state_t::eLayerHidden;
1958}
1959
Mathias Agopianda27af92012-09-13 18:17:13 -07001960bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001961 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001962#ifdef USE_HWC2
Robert Carr1f0a16a2016-10-24 16:27:39 -07001963 return !(isHiddenByPolicy()) && s.alpha > 0.0f
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001965#else
Robert Carr1f0a16a2016-10-24 16:27:39 -07001966 return !(isHiddenByPolicy()) && s.alpha
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001967 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1968#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001969}
1970
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001971bool Layer::allTransactionsSignaled() {
1972 auto headFrameNumber = getHeadFrameNumber();
1973 bool matchingFramesFound = false;
1974 bool allTransactionsApplied = true;
1975 Mutex::Autolock lock(mLocalSyncPointMutex);
1976
1977 for (auto& point : mLocalSyncPoints) {
1978 if (point->getFrameNumber() > headFrameNumber) {
1979 break;
1980 }
1981 matchingFramesFound = true;
1982
1983 if (!point->frameIsAvailable()) {
1984 // We haven't notified the remote layer that the frame for
1985 // this point is available yet. Notify it now, and then
1986 // abort this attempt to latch.
1987 point->setFrameAvailable();
1988 allTransactionsApplied = false;
1989 break;
1990 }
1991
1992 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1993 }
1994 return !matchingFramesFound || allTransactionsApplied;
1995}
1996
Brian Andersond6927fb2016-07-23 23:37:30 -07001997Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001998{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001999 ATRACE_CALL();
2000
Jesse Hall399184a2014-03-03 15:42:54 -08002001 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2002 // mSidebandStreamChanged was true
2003 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07002004 if (mSidebandStream != NULL) {
2005 setTransactionFlags(eTransactionNeeded);
2006 mFlinger->setTransactionFlags(eTraversalNeeded);
2007 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07002008 recomputeVisibleRegions = true;
2009
2010 const State& s(getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07002011 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08002012 }
2013
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07002015 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2016 return outDirtyRegion;
2017 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002018
Fabien Sanglard223eb912016-10-13 10:15:06 -07002019 // if we've already called updateTexImage() without going through
2020 // a composition step, we have to skip this layer at this point
2021 // because we cannot call updateTeximage() without a corresponding
2022 // compositionComplete() call.
2023 // we'll trigger an update in onPreComposition().
2024 if (mRefreshPending) {
2025 return outDirtyRegion;
2026 }
2027
2028 // If the head buffer's acquire fence hasn't signaled yet, return and
2029 // try again later
2030 if (!headFenceHasSignaled()) {
2031 mFlinger->signalLayerUpdate();
2032 return outDirtyRegion;
2033 }
2034
2035 // Capture the old state of the layer for comparisons later
2036 const State& s(getDrawingState());
2037 const bool oldOpacity = isOpaque(s);
2038 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2039
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07002040 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07002041 mFlinger->signalLayerUpdate();
2042 return outDirtyRegion;
2043 }
2044
2045 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2046 // of the buffer queue isn't modified when the buffer queue is returning
2047 // BufferItem's that weren't actually queued. This can happen in shared
2048 // buffer mode.
2049 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07002050 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2051 getProducerStickyTransform() != 0, mName.string(),
2052 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002053 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2054 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2055 mLastFrameNumberReceived);
2056 if (updateResult == BufferQueue::PRESENT_LATER) {
2057 // Producer doesn't want buffer to be displayed yet. Signal a
2058 // layer update so we check again at the next opportunity.
2059 mFlinger->signalLayerUpdate();
2060 return outDirtyRegion;
2061 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2062 // If the buffer has been rejected, remove it from the shadow queue
2063 // and return early
2064 if (queuedBuffer) {
2065 Mutex::Autolock lock(mQueueItemLock);
2066 mQueueItems.removeAt(0);
2067 android_atomic_dec(&mQueuedFrames);
2068 }
2069 return outDirtyRegion;
2070 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2071 // This can occur if something goes wrong when trying to create the
2072 // EGLImage for this buffer. If this happens, the buffer has already
2073 // been released, so we need to clean up the queue and bug out
2074 // early.
2075 if (queuedBuffer) {
2076 Mutex::Autolock lock(mQueueItemLock);
2077 mQueueItems.clear();
2078 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07002079 }
2080
Fabien Sanglard223eb912016-10-13 10:15:06 -07002081 // Once we have hit this state, the shadow queue may no longer
2082 // correctly reflect the incoming BufferQueue's contents, so even if
2083 // updateTexImage starts working, the only safe course of action is
2084 // to continue to ignore updates.
2085 mUpdateTexImageFailed = true;
2086
2087 return outDirtyRegion;
2088 }
2089
2090 if (queuedBuffer) {
2091 // Autolock scope
2092 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2093
2094 Mutex::Autolock lock(mQueueItemLock);
2095
2096 // Remove any stale buffers that have been dropped during
2097 // updateTexImage
2098 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2099 mQueueItems.removeAt(0);
2100 android_atomic_dec(&mQueuedFrames);
2101 }
2102
2103 mQueueItems.removeAt(0);
2104 }
2105
2106
2107 // Decrement the queued-frames count. Signal another event if we
2108 // have more frames pending.
2109 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2110 || mAutoRefresh) {
2111 mFlinger->signalLayerUpdate();
2112 }
2113
Fabien Sanglard223eb912016-10-13 10:15:06 -07002114 // update the active buffer
Chia-I Wu06d63de2017-01-04 14:58:51 +08002115 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2116 &mActiveBufferSlot);
Fabien Sanglard223eb912016-10-13 10:15:06 -07002117 if (mActiveBuffer == NULL) {
2118 // this can only happen if the very first buffer was rejected.
2119 return outDirtyRegion;
2120 }
2121
Brian Andersond6927fb2016-07-23 23:37:30 -07002122 mBufferLatched = true;
2123 mPreviousFrameNumber = mCurrentFrameNumber;
2124 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2125
2126 {
2127 Mutex::Autolock lock(mFrameEventHistoryMutex);
2128 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2129#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07002130 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002131 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002132 mReleaseTimeline.push(releaseFenceTime);
2133 mFrameEventHistory.addRelease(
Brian Andersonf6386862016-10-31 16:34:13 -07002134 mPreviousFrameNumber, latchTime, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07002135#endif
2136 }
2137
Fabien Sanglard223eb912016-10-13 10:15:06 -07002138 mRefreshPending = true;
2139 mFrameLatencyNeeded = true;
2140 if (oldActiveBuffer == NULL) {
2141 // the first time we receive a buffer, we need to trigger a
2142 // geometry invalidation.
2143 recomputeVisibleRegions = true;
2144 }
2145
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002146 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2147
Fabien Sanglard223eb912016-10-13 10:15:06 -07002148 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2149 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2150 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2151 if ((crop != mCurrentCrop) ||
2152 (transform != mCurrentTransform) ||
2153 (scalingMode != mCurrentScalingMode))
2154 {
2155 mCurrentCrop = crop;
2156 mCurrentTransform = transform;
2157 mCurrentScalingMode = scalingMode;
2158 recomputeVisibleRegions = true;
2159 }
2160
2161 if (oldActiveBuffer != NULL) {
2162 uint32_t bufWidth = mActiveBuffer->getWidth();
2163 uint32_t bufHeight = mActiveBuffer->getHeight();
2164 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2165 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002166 recomputeVisibleRegions = true;
2167 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002168 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002169
Fabien Sanglard223eb912016-10-13 10:15:06 -07002170 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2171 if (oldOpacity != isOpaque(s)) {
2172 recomputeVisibleRegions = true;
2173 }
Dan Stozacac35382016-01-27 12:21:06 -08002174
Fabien Sanglard223eb912016-10-13 10:15:06 -07002175 // Remove any sync points corresponding to the buffer which was just
2176 // latched
2177 {
2178 Mutex::Autolock lock(mLocalSyncPointMutex);
2179 auto point = mLocalSyncPoints.begin();
2180 while (point != mLocalSyncPoints.end()) {
2181 if (!(*point)->frameIsAvailable() ||
2182 !(*point)->transactionIsApplied()) {
2183 // This sync point must have been added since we started
2184 // latching. Don't drop it yet.
2185 ++point;
2186 continue;
2187 }
2188
2189 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2190 point = mLocalSyncPoints.erase(point);
2191 } else {
2192 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002193 }
2194 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002195 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002196
2197 // FIXME: postedRegion should be dirty & bounds
2198 Region dirtyRegion(Rect(s.active.w, s.active.h));
2199
2200 // transform the dirty region to window-manager space
Robert Carr1f0a16a2016-10-24 16:27:39 -07002201 outDirtyRegion = (getTransform().transform(dirtyRegion));
Fabien Sanglard223eb912016-10-13 10:15:06 -07002202
Mathias Agopian4fec8732012-06-29 14:12:52 -07002203 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002204}
2205
Mathias Agopiana67932f2011-04-20 14:20:59 -07002206uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002207{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002208 // TODO: should we do something special if mSecure is set?
2209 if (mProtectedByApp) {
2210 // need a hardware-protected path to external video sink
2211 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002212 }
Riley Andrews03414a12014-07-01 14:22:59 -07002213 if (mPotentialCursor) {
2214 usage |= GraphicBuffer::USAGE_CURSOR;
2215 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002216 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002217 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002218}
2219
Mathias Agopian84300952012-11-21 16:02:13 -08002220void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002221 uint32_t orientation = 0;
2222 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002223 // The transform hint is used to improve performance, but we can
2224 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002225 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002226 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002227 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002228 if (orientation & Transform::ROT_INVALID) {
2229 orientation = 0;
2230 }
2231 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002232 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002233}
2234
Mathias Agopian13127d82013-03-05 17:47:11 -08002235// ----------------------------------------------------------------------------
2236// debugging
2237// ----------------------------------------------------------------------------
2238
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002239void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002240{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002241 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002242
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002243 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002244 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002245 "+ %s %p (%s)\n",
2246 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002247 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002248
Mathias Agopian2ca79392013-04-02 18:30:32 -07002249 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002250 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002251 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002252 sp<Client> client(mClientRef.promote());
2253
Mathias Agopian74d211a2013-04-22 16:55:35 +02002254 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002255 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2256 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002257 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002258#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002259 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002260#else
2261 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2262#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002263 " client=%p\n",
Robert Carr1f0a16a2016-10-24 16:27:39 -07002264 getLayerStack(), s.z,
2265 s.active.transform.tx(), s.active.transform.ty(),
2266 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002267 s.crop.left, s.crop.top,
2268 s.crop.right, s.crop.bottom,
2269 s.finalCrop.left, s.finalCrop.top,
2270 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002271 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002272 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002273 s.active.transform[0][0], s.active.transform[0][1],
2274 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002275 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002276
2277 sp<const GraphicBuffer> buf0(mActiveBuffer);
2278 uint32_t w0=0, h0=0, s0=0, f0=0;
2279 if (buf0 != 0) {
2280 w0 = buf0->getWidth();
2281 h0 = buf0->getHeight();
2282 s0 = buf0->getStride();
2283 f0 = buf0->format;
2284 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002285 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002286 " "
2287 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2288 " queued-frames=%d, mRefreshPending=%d\n",
2289 mFormat, w0, h0, s0,f0,
2290 mQueuedFrames, mRefreshPending);
2291
Mathias Agopian13127d82013-03-05 17:47:11 -08002292 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002293 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002294 }
2295}
2296
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002297#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002298void Layer::miniDumpHeader(String8& result) {
2299 result.append("----------------------------------------");
2300 result.append("---------------------------------------\n");
2301 result.append(" Layer name\n");
2302 result.append(" Z | ");
2303 result.append(" Comp Type | ");
2304 result.append(" Disp Frame (LTRB) | ");
2305 result.append(" Source Crop (LTRB)\n");
2306 result.append("----------------------------------------");
2307 result.append("---------------------------------------\n");
2308}
2309
2310void Layer::miniDump(String8& result, int32_t hwcId) const {
2311 if (mHwcLayers.count(hwcId) == 0) {
2312 return;
2313 }
2314
2315 String8 name;
2316 if (mName.length() > 77) {
2317 std::string shortened;
2318 shortened.append(mName.string(), 36);
2319 shortened.append("[...]");
2320 shortened.append(mName.string() + (mName.length() - 36), 36);
2321 name = shortened.c_str();
2322 } else {
2323 name = mName;
2324 }
2325
2326 result.appendFormat(" %s\n", name.string());
2327
2328 const Layer::State& layerState(getDrawingState());
2329 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2330 result.appendFormat(" %10u | ", layerState.z);
2331 result.appendFormat("%10s | ",
2332 to_string(getCompositionType(hwcId)).c_str());
2333 const Rect& frame = hwcInfo.displayFrame;
2334 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2335 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002336 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002337 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2338 crop.right, crop.bottom);
2339
2340 result.append("- - - - - - - - - - - - - - - - - - - - ");
2341 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2342}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002343#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002344
Svetoslavd85084b2014-03-20 10:28:31 -07002345void Layer::dumpFrameStats(String8& result) const {
2346 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002347}
2348
Svetoslavd85084b2014-03-20 10:28:31 -07002349void Layer::clearFrameStats() {
2350 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002351}
2352
Jamie Gennis6547ff42013-07-16 20:12:42 -07002353void Layer::logFrameStats() {
2354 mFrameTracker.logAndResetStats(mName);
2355}
2356
Svetoslavd85084b2014-03-20 10:28:31 -07002357void Layer::getFrameStats(FrameStats* outStats) const {
2358 mFrameTracker.getStats(outStats);
2359}
2360
Brian Andersond6927fb2016-07-23 23:37:30 -07002361void Layer::dumpFrameEvents(String8& result) {
2362 result.appendFormat("- Layer %s (%s, %p)\n",
2363 getName().string(), getTypeId(), this);
2364 Mutex::Autolock lock(mFrameEventHistoryMutex);
2365 mFrameEventHistory.checkFencesForCompletion();
2366 mFrameEventHistory.dump(result);
2367}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002368
Brian Anderson3890c392016-07-25 12:48:08 -07002369void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2370 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002371 Mutex::Autolock lock(mFrameEventHistoryMutex);
2372 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002373 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002374 mFrameEventHistory.addQueue(*newTimestamps);
2375 }
2376
Brian Anderson3890c392016-07-25 12:48:08 -07002377 if (outDelta) {
2378 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002379 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002380}
Dan Stozae77c7662016-05-13 11:37:28 -07002381
2382std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2383 bool forceFlush) {
2384 std::vector<OccupancyTracker::Segment> history;
2385 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2386 &history);
2387 if (result != NO_ERROR) {
2388 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2389 result);
2390 return {};
2391 }
2392 return history;
2393}
2394
Robert Carr367c5682016-06-20 11:55:28 -07002395bool Layer::getTransformToDisplayInverse() const {
2396 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2397}
2398
Robert Carr1f0a16a2016-10-24 16:27:39 -07002399void Layer::addChild(const sp<Layer>& layer) {
2400 mCurrentChildren.add(layer);
2401 layer->setParent(this);
2402}
2403
2404ssize_t Layer::removeChild(const sp<Layer>& layer) {
2405 layer->setParent(nullptr);
2406 return mCurrentChildren.remove(layer);
2407}
2408
Robert Carr1db73f62016-12-21 12:58:51 -08002409bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2410 sp<Handle> handle = nullptr;
2411 sp<Layer> newParent = nullptr;
2412 if (newParentHandle == nullptr) {
2413 return false;
2414 }
2415 handle = static_cast<Handle*>(newParentHandle.get());
2416 newParent = handle->owner.promote();
2417 if (newParent == nullptr) {
2418 ALOGE("Unable to promote Layer handle");
2419 return false;
2420 }
2421
2422 for (const sp<Layer>& child : mCurrentChildren) {
2423 newParent->addChild(child);
2424
2425 sp<Client> client(child->mClientRef.promote());
2426 if (client != nullptr) {
2427 client->setParentLayer(newParent);
2428 }
2429 }
2430 mCurrentChildren.clear();
2431
2432 return true;
2433}
2434
Robert Carr1f0a16a2016-10-24 16:27:39 -07002435void Layer::setParent(const sp<Layer>& layer) {
2436 mParent = layer;
2437}
2438
2439void Layer::clearSyncPoints() {
2440 for (const auto& child : mCurrentChildren) {
2441 child->clearSyncPoints();
2442 }
2443
2444 Mutex::Autolock lock(mLocalSyncPointMutex);
2445 for (auto& point : mLocalSyncPoints) {
2446 point->setFrameAvailable();
2447 }
2448 mLocalSyncPoints.clear();
2449}
2450
2451int32_t Layer::getZ() const {
2452 return mDrawingState.z;
2453}
2454
2455/**
2456 * Negatively signed children are before 'this' in Z-order.
2457 */
2458void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) {
2459 size_t i = 0;
2460 for (; i < mDrawingChildren.size(); i++) {
2461 const auto& child = mDrawingChildren[i];
2462 if (child->getZ() >= 0)
2463 break;
2464 child->traverseInZOrder(exec);
2465 }
2466 exec(this);
2467 for (; i < mDrawingChildren.size(); i++) {
2468 const auto& child = mDrawingChildren[i];
2469 child->traverseInZOrder(exec);
2470 }
2471}
2472
2473/**
2474 * Positively signed children are before 'this' in reverse Z-order.
2475 */
2476void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) {
2477 int32_t i = 0;
2478 for (i = mDrawingChildren.size()-1; i>=0; i--) {
2479 const auto& child = mDrawingChildren[i];
2480 if (child->getZ() < 0) {
2481 break;
2482 }
2483 child->traverseInReverseZOrder(exec);
2484 }
2485 exec(this);
2486 for (; i>=0; i--) {
2487 const auto& child = mDrawingChildren[i];
2488 child->traverseInReverseZOrder(exec);
2489 }
2490}
2491
2492Transform Layer::getTransform() const {
2493 Transform t;
2494 const auto& p = getParent();
2495 if (p != nullptr) {
2496 t = p->getTransform();
2497 }
2498 return t * getDrawingState().active.transform;
2499}
2500
2501void Layer::commitChildList() {
2502 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2503 const auto& child = mCurrentChildren[i];
2504 child->commitChildList();
2505 }
2506 mDrawingChildren = mCurrentChildren;
2507}
2508
Mathias Agopian13127d82013-03-05 17:47:11 -08002509// ---------------------------------------------------------------------------
2510
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002511}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002512
2513#if defined(__gl_h_)
2514#error "don't include gl/gl.h in this file"
2515#endif
2516
2517#if defined(__gl2_h_)
2518#error "don't include gl2/gl2.h in this file"
2519#endif