blob: 395757bfe377ba73e6ec0b89e0be5833c6dce03f [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;
142
143 // drawing state & current state are identical
144 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700145
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000146#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800147 const auto& hwc = flinger->getHwComposer();
148 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
149 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000150#else
151 nsecs_t displayPeriod =
152 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
153#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700154 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Jamie Gennise8696a42012-01-15 18:54:57 -0800155}
156
Mathias Agopian3f844832013-08-07 21:24:32 -0700157void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800158 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700159 sp<IGraphicBufferProducer> producer;
160 sp<IGraphicBufferConsumer> consumer;
Irvel468051e2016-06-13 16:44:44 -0700161 BufferQueue::createBufferQueue(&producer, &consumer, nullptr, true);
Dan Stozab9b08832014-03-13 11:55:57 -0700162 mProducer = new MonitoredProducer(producer, mFlinger);
Irvel468051e2016-06-13 16:44:44 -0700163 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800164 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800165 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700166 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800167
Dan Stozac9d97202016-03-03 08:20:27 -0800168#ifndef TARGET_DISABLE_TRIPLE_BUFFERING
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700169 mProducer->setMaxDequeuedBufferCount(2);
Mathias Agopian303d5382012-02-05 01:49:16 -0800170#endif
Andy McFadden69052052012-09-14 16:10:11 -0700171
Mathias Agopian84300952012-11-21 16:02:13 -0800172 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
173 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700174}
175
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700176Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800177 sp<Client> c(mClientRef.promote());
178 if (c != 0) {
179 c->detachLayer(this);
180 }
181
Dan Stozacac35382016-01-27 12:21:06 -0800182 for (auto& point : mRemoteSyncPoints) {
183 point->setTransactionApplied();
184 }
Dan Stozac8145172016-04-28 16:29:06 -0700185 for (auto& point : mLocalSyncPoints) {
186 point->setFrameAvailable();
187 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700188 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700189 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700190}
191
Mathias Agopian13127d82013-03-05 17:47:11 -0800192// ---------------------------------------------------------------------------
193// callbacks
194// ---------------------------------------------------------------------------
195
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000196#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800197void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
198 if (mHwcLayers.empty()) {
199 return;
200 }
201 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
202}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000203#else
204void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
205 HWComposer::HWCLayerInterface* layer) {
206 if (layer) {
207 layer->onDisplayed();
208 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
209 }
210}
211#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800212
Dan Stoza6b9454d2014-11-07 16:00:59 -0800213void Layer::onFrameAvailable(const BufferItem& item) {
214 // Add this buffer from our internal queue tracker
215 { // Autolock scope
216 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700217 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
218 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700219 // Reset the frame number tracker when we receive the first buffer after
220 // a frame number reset
221 if (item.mFrameNumber == 1) {
222 mLastFrameNumberReceived = 0;
223 }
224
225 // Ensure that callbacks are handled in order
226 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
227 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
228 ms2ns(500));
229 if (result != NO_ERROR) {
230 ALOGE("[%s] Timed out waiting on callback", mName.string());
231 }
232 }
233
Dan Stoza6b9454d2014-11-07 16:00:59 -0800234 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700235 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700236
237 // Wake up any pending callbacks
238 mLastFrameNumberReceived = item.mFrameNumber;
239 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800240 }
241
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700243}
244
Dan Stoza6b9454d2014-11-07 16:00:59 -0800245void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700246 { // Autolock scope
247 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700248
Dan Stoza7dde5992015-05-22 09:51:44 -0700249 // Ensure that callbacks are handled in order
250 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
251 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
252 ms2ns(500));
253 if (result != NO_ERROR) {
254 ALOGE("[%s] Timed out waiting on callback", mName.string());
255 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700256 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700257
258 if (mQueueItems.empty()) {
259 ALOGE("Can't replace a frame on an empty queue");
260 return;
261 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700262 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700263
264 // Wake up any pending callbacks
265 mLastFrameNumberReceived = item.mFrameNumber;
266 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700267 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800268}
269
Jesse Hall399184a2014-03-03 15:42:54 -0800270void Layer::onSidebandStreamChanged() {
271 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
272 // mSidebandStreamChanged was false
273 mFlinger->signalLayerUpdate();
274 }
275}
276
Mathias Agopian67106042013-03-14 19:18:13 -0700277// called with SurfaceFlinger::mStateLock from the drawing thread after
278// the layer has been remove from the current state list (and just before
279// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800280void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800281 mSurfaceFlingerConsumer->abandon();
Mathias Agopian48d819a2009-09-10 19:41:18 -0700282}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700283
Mathias Agopian13127d82013-03-05 17:47:11 -0800284// ---------------------------------------------------------------------------
285// set-up
286// ---------------------------------------------------------------------------
287
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700288const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800289 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290}
291
Mathias Agopianf9d93272009-06-19 17:00:27 -0700292status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800293 PixelFormat format, uint32_t flags)
294{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700295 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700296 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700297
298 // never allow a surface larger than what our underlying GL implementation
299 // can handle.
300 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800301 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700302 return BAD_VALUE;
303 }
304
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700305 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700306
Riley Andrews03414a12014-07-01 14:22:59 -0700307 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700308 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700309 mCurrentOpacity = getOpacityForFormat(format);
310
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800311 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
312 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
313 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700314
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800315 return NO_ERROR;
316}
317
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700318sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800319 Mutex::Autolock _l(mLock);
320
321 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700322 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800323
324 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700325
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700326 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800327}
328
Dan Stozab9b08832014-03-13 11:55:57 -0700329sp<IGraphicBufferProducer> Layer::getProducer() const {
330 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700331}
332
Mathias Agopian13127d82013-03-05 17:47:11 -0800333// ---------------------------------------------------------------------------
334// h/w composer set-up
335// ---------------------------------------------------------------------------
336
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800337Rect Layer::getContentCrop() const {
338 // this is the crop rectangle that applies to the buffer
339 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700340 Rect crop;
341 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800342 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700343 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800344 } else if (mActiveBuffer != NULL) {
345 // otherwise we use the whole buffer
346 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700347 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800348 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700349 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700350 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700351 return crop;
352}
353
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700354static Rect reduce(const Rect& win, const Region& exclude) {
355 if (CC_LIKELY(exclude.isEmpty())) {
356 return win;
357 }
358 if (exclude.isRect()) {
359 return win.reduce(exclude.getBounds());
360 }
361 return Region(win).subtract(exclude).getBounds();
362}
363
Mathias Agopian13127d82013-03-05 17:47:11 -0800364Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700365 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700366 return computeBounds(s.activeTransparentRegion);
367}
368
369Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
370 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800371 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700372
373 if (!s.crop.isEmpty()) {
374 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800375 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700376 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700377 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800378}
379
Mathias Agopian6b442672013-07-09 21:24:52 -0700380FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800381 // the content crop is the area of the content that gets scaled to the
382 // layer's size.
Mathias Agopian6b442672013-07-09 21:24:52 -0700383 FloatRect crop(getContentCrop());
Mathias Agopian13127d82013-03-05 17:47:11 -0800384
Robert Carrb5d3d262016-03-25 15:08:13 -0700385 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800386 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700387 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800388
389 // apply the projection's clipping to the window crop in
390 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700391 // if there are no window scaling involved, this operation will map to full
392 // pixels in the buffer.
393 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
394 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700395
396 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700397 if (!s.crop.isEmpty()) {
398 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700399 }
400
Robert Carr3dcabfa2016-03-01 18:36:58 -0800401 activeCrop = s.active.transform.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000402 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
403 activeCrop.clear();
404 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700405 if (!s.finalCrop.isEmpty()) {
406 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000407 activeCrop.clear();
408 }
409 }
Robert Carr3dcabfa2016-03-01 18:36:58 -0800410 activeCrop = s.active.transform.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800411
Michael Lentine28ea2172014-11-19 18:32:37 -0800412 // This needs to be here as transform.transform(Rect) computes the
413 // transformed rect and then takes the bounding box of the result before
414 // returning. This means
415 // transform.inverse().transform(transform.transform(Rect)) != Rect
416 // in which case we need to make sure the final rect is clipped to the
417 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000418 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
419 activeCrop.clear();
420 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800421
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700422 // subtract the transparent region and snap to the bounds
423 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
424
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000425 // Transform the window crop to match the buffer coordinate system,
426 // which means using the inverse of the current transform set on the
427 // SurfaceFlingerConsumer.
428 uint32_t invTransform = mCurrentTransform;
429 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
430 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700431 * the code below applies the primary display's inverse transform to the
432 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000433 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700434 uint32_t invTransformOrient =
435 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000436 // calculate the inverse transform
437 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
438 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
439 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800440 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000441 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700442 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
443 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800444 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000445
446 int winWidth = s.active.w;
447 int winHeight = s.active.h;
448 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
449 // If the activeCrop has been rotate the ends are rotated but not
450 // the space itself so when transforming ends back we can't rely on
451 // a modification of the axes of rotation. To account for this we
452 // need to reorient the inverse rotation in terms of the current
453 // axes of rotation.
454 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
455 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
456 if (is_h_flipped == is_v_flipped) {
457 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
458 NATIVE_WINDOW_TRANSFORM_FLIP_H;
459 }
460 winWidth = s.active.h;
461 winHeight = s.active.w;
462 }
463 const Rect winCrop = activeCrop.transform(
464 invTransform, s.active.w, s.active.h);
465
466 // below, crop is intersected with winCrop expressed in crop's coordinate space
467 float xScale = crop.getWidth() / float(winWidth);
468 float yScale = crop.getHeight() / float(winHeight);
469
470 float insetL = winCrop.left * xScale;
471 float insetT = winCrop.top * yScale;
472 float insetR = (winWidth - winCrop.right ) * xScale;
473 float insetB = (winHeight - winCrop.bottom) * yScale;
474
475 crop.left += insetL;
476 crop.top += insetT;
477 crop.right -= insetR;
478 crop.bottom -= insetB;
479
Mathias Agopian13127d82013-03-05 17:47:11 -0800480 return crop;
481}
482
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000483#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800484void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000485#else
486void Layer::setGeometry(
487 const sp<const DisplayDevice>& hw,
488 HWComposer::HWCLayerInterface& layer)
489#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700490{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000491#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800492 const auto hwcId = displayDevice->getHwcDisplayId();
493 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000494#else
495 layer.setDefaultState();
496#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700497
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700498 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000499#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800500 hwcInfo.forceClientComposition = false;
501
502 if (isSecure() && !displayDevice->isSecure()) {
503 hwcInfo.forceClientComposition = true;
504 }
505
506 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000507#else
508 layer.setSkip(false);
509
510 if (isSecure() && !hw->isSecure()) {
511 layer.setSkip(true);
512 }
513#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700514
Mathias Agopian13127d82013-03-05 17:47:11 -0800515 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700516 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000517#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800518 if (!isOpaque(s) || s.alpha != 1.0f) {
519 auto blendMode = mPremultipliedAlpha ?
520 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
521 auto error = hwcLayer->setBlendMode(blendMode);
522 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
523 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
524 to_string(error).c_str(), static_cast<int32_t>(error));
525 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000526#else
527 if (!isOpaque(s) || s.alpha != 0xFF) {
528 layer.setBlending(mPremultipliedAlpha ?
529 HWC_BLENDING_PREMULT :
530 HWC_BLENDING_COVERAGE);
531 }
532#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800533
534 // apply the layer's transform, followed by the display's global transform
535 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700536 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carrb5d3d262016-03-25 15:08:13 -0700537 if (!s.crop.isEmpty()) {
538 Rect activeCrop(s.crop);
Robert Carr3dcabfa2016-03-01 18:36:58 -0800539 activeCrop = s.active.transform.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000540#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000541 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000542#else
543 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
544#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000545 activeCrop.clear();
546 }
Pablo Ceballos51450032016-08-03 10:20:45 -0700547 activeCrop = s.active.transform.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800548 // This needs to be here as transform.transform(Rect) computes the
549 // transformed rect and then takes the bounding box of the result before
550 // returning. This means
551 // transform.inverse().transform(transform.transform(Rect)) != Rect
552 // in which case we need to make sure the final rect is clipped to the
553 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000554 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
555 activeCrop.clear();
556 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700557 // mark regions outside the crop as transparent
558 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
559 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
560 s.active.w, s.active.h));
561 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
562 activeCrop.left, activeCrop.bottom));
563 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
564 s.active.w, activeCrop.bottom));
565 }
Robert Carr3dcabfa2016-03-01 18:36:58 -0800566 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700567 if (!s.finalCrop.isEmpty()) {
568 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000569 frame.clear();
570 }
571 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000572#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000573 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
574 frame.clear();
575 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800576 const Transform& tr(displayDevice->getTransform());
577 Rect transformedFrame = tr.transform(frame);
578 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700579 if (error != HWC2::Error::None) {
580 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
581 mName.string(), transformedFrame.left, transformedFrame.top,
582 transformedFrame.right, transformedFrame.bottom,
583 to_string(error).c_str(), static_cast<int32_t>(error));
584 } else {
585 hwcInfo.displayFrame = transformedFrame;
586 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587
588 FloatRect sourceCrop = computeCrop(displayDevice);
589 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700590 if (error != HWC2::Error::None) {
591 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
592 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
593 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
594 static_cast<int32_t>(error));
595 } else {
596 hwcInfo.sourceCrop = sourceCrop;
597 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598
599 error = hwcLayer->setPlaneAlpha(s.alpha);
600 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
601 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
602 static_cast<int32_t>(error));
603
604 error = hwcLayer->setZOrder(s.z);
605 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
606 mName.string(), s.z, to_string(error).c_str(),
607 static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000608#else
609 if (!frame.intersect(hw->getViewport(), &frame)) {
610 frame.clear();
611 }
612 const Transform& tr(hw->getTransform());
613 layer.setFrame(tr.transform(frame));
614 layer.setCrop(computeCrop(hw));
615 layer.setPlaneAlpha(s.alpha);
616#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800617
Mathias Agopian29a367b2011-07-12 14:51:45 -0700618 /*
619 * Transformations are applied in this order:
620 * 1) buffer orientation/flip/mirror
621 * 2) state transformation (window manager)
622 * 3) layer orientation (screen orientation)
623 * (NOTE: the matrices are multiplied in reverse order)
624 */
625
626 const Transform bufferOrientation(mCurrentTransform);
Robert Carr3dcabfa2016-03-01 18:36:58 -0800627 Transform transform(tr * s.active.transform * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700628
629 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
630 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700631 * the code below applies the primary display's inverse transform to the
632 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700633 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700634 uint32_t invTransform =
635 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700636 // calculate the inverse transform
637 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
638 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
639 NATIVE_WINDOW_TRANSFORM_FLIP_H;
640 }
641 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700642 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700643 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700644
645 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800646 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000647#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800648 if (orientation & Transform::ROT_INVALID) {
649 // we can only handle simple transformation
650 hwcInfo.forceClientComposition = true;
651 } else {
652 auto transform = static_cast<HWC2::Transform>(orientation);
653 auto error = hwcLayer->setTransform(transform);
654 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
655 "%s (%d)", mName.string(), to_string(transform).c_str(),
656 to_string(error).c_str(), static_cast<int32_t>(error));
657 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000658#else
659 if (orientation & Transform::ROT_INVALID) {
660 // we can only handle simple transformation
661 layer.setSkip(true);
662 } else {
663 layer.setTransform(orientation);
664 }
665#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700666}
667
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000668#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669void Layer::forceClientComposition(int32_t hwcId) {
670 if (mHwcLayers.count(hwcId) == 0) {
671 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
672 return;
673 }
674
675 mHwcLayers[hwcId].forceClientComposition = true;
676}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000677#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000679#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800680void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
681 // Apply this display's projection's viewport to the visible region
682 // before giving it to the HWC HAL.
683 const Transform& tr = displayDevice->getTransform();
684 const auto& viewport = displayDevice->getViewport();
685 Region visible = tr.transform(visibleRegion.intersect(viewport));
686 auto hwcId = displayDevice->getHwcDisplayId();
687 auto& hwcLayer = mHwcLayers[hwcId].layer;
688 auto error = hwcLayer->setVisibleRegion(visible);
689 if (error != HWC2::Error::None) {
690 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
691 to_string(error).c_str(), static_cast<int32_t>(error));
692 visible.dump(LOG_TAG);
693 }
694
695 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
696 if (error != HWC2::Error::None) {
697 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
698 to_string(error).c_str(), static_cast<int32_t>(error));
699 surfaceDamageRegion.dump(LOG_TAG);
700 }
701
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700702 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800703 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700704 setCompositionType(hwcId, HWC2::Composition::Sideband);
705 ALOGV("[%s] Requesting Sideband composition", mName.string());
706 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707 if (error != HWC2::Error::None) {
708 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
709 mName.string(), mSidebandStream->handle(),
710 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800711 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700712 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800713 }
714
Dan Stoza0a21df72016-07-20 12:52:38 -0700715 // Client layers
716 if (mHwcLayers[hwcId].forceClientComposition ||
717 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700718 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700720 return;
721 }
722
Dan Stoza0a21df72016-07-20 12:52:38 -0700723 // SolidColor layers
724 if (mActiveBuffer == nullptr) {
725 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700726
727 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700728 error = hwcLayer->setColor({0, 0, 0, 255});
729 if (error != HWC2::Error::None) {
730 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
731 to_string(error).c_str(), static_cast<int32_t>(error));
732 }
Dan Stozac6c89542016-07-27 10:16:52 -0700733
734 // Clear out the transform, because it doesn't make sense absent a
735 // source buffer
736 error = hwcLayer->setTransform(HWC2::Transform::None);
737 if (error != HWC2::Error::None) {
738 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
739 to_string(error).c_str(), static_cast<int32_t>(error));
740 }
741
Dan Stoza0a21df72016-07-20 12:52:38 -0700742 return;
743 }
744
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700745 // Device or Cursor layers
746 if (mPotentialCursor) {
747 ALOGV("[%s] Requesting Cursor composition", mName.string());
748 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 } else {
750 ALOGV("[%s] Requesting Device composition", mName.string());
751 setCompositionType(hwcId, HWC2::Composition::Device);
752 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700753
754 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
755 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
756 if (error != HWC2::Error::None) {
757 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
758 mActiveBuffer->handle, to_string(error).c_str(),
759 static_cast<int32_t>(error));
760 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800761}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000762#else
763void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
764 HWComposer::HWCLayerInterface& layer) {
765 // we have to set the visible region on every frame because
766 // we currently free it during onLayerDisplayed(), which is called
767 // after HWComposer::commit() -- every frame.
768 // Apply this display's projection's viewport to the visible region
769 // before giving it to the HWC HAL.
770 const Transform& tr = hw->getTransform();
771 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
772 layer.setVisibleRegionScreen(visible);
773 layer.setSurfaceDamage(surfaceDamageRegion);
774 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700775
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000776 if (mSidebandStream.get()) {
777 layer.setSidebandStream(mSidebandStream);
778 } else {
779 // NOTE: buffer can be NULL if the client never drew into this
780 // layer yet, or if we ran out of memory
781 layer.setBuffer(mActiveBuffer);
782 }
783}
784#endif
785
786#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
788 auto hwcId = displayDevice->getHwcDisplayId();
789 if (mHwcLayers.count(hwcId) == 0 ||
790 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
791 return;
792 }
793
794 // This gives us only the "orientation" component of the transform
795 const State& s(getCurrentState());
796
797 // Apply the layer's transform, followed by the display's global transform
798 // Here we're guaranteed that the layer's transform preserves rects
799 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700800 if (!s.crop.isEmpty()) {
801 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 }
803 // Subtract the transparent region and snap to the bounds
804 Rect bounds = reduce(win, s.activeTransparentRegion);
Dan Stozabaf416d2016-03-10 11:57:08 -0800805 Rect frame(s.active.transform.transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800806 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700807 if (!s.finalCrop.isEmpty()) {
808 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000809 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 auto& displayTransform(displayDevice->getTransform());
811 auto position = displayTransform.transform(frame);
812
813 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
814 position.top);
815 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
816 "to (%d, %d): %s (%d)", mName.string(), position.left,
817 position.top, to_string(error).c_str(),
818 static_cast<int32_t>(error));
819}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000820#else
821void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
822 HWComposer::HWCLayerInterface& layer) {
823 int fenceFd = -1;
824
825 // TODO: there is a possible optimization here: we only need to set the
826 // acquire fence the first time a new buffer is acquired on EACH display.
827
828 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
829 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
830 if (fence->isValid()) {
831 fenceFd = fence->dup();
832 if (fenceFd == -1) {
833 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
834 }
835 }
836 }
837 layer.setAcquireFenceFd(fenceFd);
838}
839
840Rect Layer::getPosition(
841 const sp<const DisplayDevice>& hw)
842{
843 // this gives us only the "orientation" component of the transform
844 const State& s(getCurrentState());
845
846 // apply the layer's transform, followed by the display's global transform
847 // here we're guaranteed that the layer's transform preserves rects
848 Rect win(s.active.w, s.active.h);
849 if (!s.crop.isEmpty()) {
850 win.intersect(s.crop, &win);
851 }
852 // subtract the transparent region and snap to the bounds
853 Rect bounds = reduce(win, s.activeTransparentRegion);
854 Rect frame(s.active.transform.transform(bounds));
855 frame.intersect(hw->getViewport(), &frame);
856 if (!s.finalCrop.isEmpty()) {
857 frame.intersect(s.finalCrop, &frame);
858 }
859 const Transform& tr(hw->getTransform());
860 return Rect(tr.transform(frame));
861}
862#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700863
Mathias Agopian13127d82013-03-05 17:47:11 -0800864// ---------------------------------------------------------------------------
865// drawing...
866// ---------------------------------------------------------------------------
867
868void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800869 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800870}
871
Dan Stozac7014012014-02-14 15:03:43 -0800872void Layer::draw(const sp<const DisplayDevice>& hw,
873 bool useIdentityTransform) const {
874 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800875}
876
Dan Stozac7014012014-02-14 15:03:43 -0800877void Layer::draw(const sp<const DisplayDevice>& hw) const {
878 onDraw(hw, Region(hw->bounds()), false);
879}
880
881void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
882 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800883{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800884 ATRACE_CALL();
885
Mathias Agopiana67932f2011-04-20 14:20:59 -0700886 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800887 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -0700888 // in fact never been drawn into. This happens frequently with
889 // SurfaceView because the WindowManager can't know when the client
890 // has drawn the first time.
891
892 // If there is nothing under us, we paint the screen in black, otherwise
893 // we just skip this update.
894
895 // figure out if there is something below us
896 Region under;
Mathias Agopianf7ae69d2011-08-23 12:34:29 -0700897 const SurfaceFlinger::LayerVector& drawingLayers(
898 mFlinger->mDrawingState.layersSortedByZ);
Mathias Agopian179169e2010-05-06 20:21:45 -0700899 const size_t count = drawingLayers.size();
900 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800901 const sp<Layer>& layer(drawingLayers[i]);
902 if (layer.get() == static_cast<Layer const*>(this))
Mathias Agopian179169e2010-05-06 20:21:45 -0700903 break;
Mathias Agopian42977342012-08-05 00:40:46 -0700904 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Mathias Agopian179169e2010-05-06 20:21:45 -0700905 }
906 // if not everything below us is covered, we plug the holes!
907 Region holes(clip.subtract(under));
908 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -0800909 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -0700910 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800911 return;
912 }
Mathias Agopiana67932f2011-04-20 14:20:59 -0700913
Andy McFadden97eba892012-12-11 15:21:45 -0800914 // Bind the current buffer to the GL texture, and wait for it to be
915 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800916 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
917 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -0800918 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -0700919 // Go ahead and draw the buffer anyway; no matter what we do the screen
920 // is probably going to have something visibly wrong.
921 }
922
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
924
Mathias Agopian875d8e12013-06-07 15:35:48 -0700925 RenderEngine& engine(mFlinger->getRenderEngine());
926
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700927 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -0700928 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -0700929 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -0700930
931 // Query the texture matrix given our current filtering mode.
932 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800933 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
934 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -0700935
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700936 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
937
938 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700939 * the code below applies the primary display's inverse transform to
940 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700941 */
942
943 // create a 4x4 transform matrix from the display transform flags
944 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
945 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
946 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
947
948 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -0700949 uint32_t transform =
950 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700951 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
952 tr = tr * rot90;
953 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
954 tr = tr * flipH;
955 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
956 tr = tr * flipV;
957
958 // calculate the inverse
959 tr = inverse(tr);
960
961 // and finally apply it to the original texture matrix
962 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
963 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
964 }
965
Jamie Genniscbb1a952012-05-08 17:05:52 -0700966 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -0700967 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
968 mTexture.setFiltering(useFiltering);
969 mTexture.setMatrix(textureMatrix);
970
971 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -0700972 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -0700973 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700974 }
Dan Stozac7014012014-02-14 15:03:43 -0800975 drawWithOpenGL(hw, clip, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -0700976 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800977}
978
Mathias Agopian13127d82013-03-05 17:47:11 -0800979
Dan Stozac7014012014-02-14 15:03:43 -0800980void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -0800981 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -0800982 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -0800983{
Mathias Agopian19733a32013-08-28 18:13:56 -0700984 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -0800985 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -0700986 engine.setupFillWithColor(red, green, blue, alpha);
987 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -0800988}
989
990void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -0800991 const sp<const DisplayDevice>& hw) const {
992 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -0800993}
994
Dan Stozac7014012014-02-14 15:03:43 -0800995void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
996 const Region& /* clip */, bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700997 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800998
Dan Stozac7014012014-02-14 15:03:43 -0800999 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001000
Mathias Agopian13127d82013-03-05 17:47:11 -08001001 /*
1002 * NOTE: the way we compute the texture coordinates here produces
1003 * different results than when we take the HWC path -- in the later case
1004 * the "source crop" is rounded to texel boundaries.
1005 * This can produce significantly different results when the texture
1006 * is scaled by a large amount.
1007 *
1008 * The GL code below is more logical (imho), and the difference with
1009 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001010 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001011 * GL composition when a buffer scaling is applied (maybe with some
1012 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1013 * like more of a hack.
1014 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001015 Rect win(computeBounds());
1016
Robert Carrb5d3d262016-03-25 15:08:13 -07001017 if (!s.finalCrop.isEmpty()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001018 win = s.active.transform.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001019 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001020 win.clear();
1021 }
1022 win = s.active.transform.inverse().transform(win);
1023 if (!win.intersect(computeBounds(), &win)) {
1024 win.clear();
1025 }
1026 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001027
Mathias Agopian3f844832013-08-07 21:24:32 -07001028 float left = float(win.left) / float(s.active.w);
1029 float top = float(win.top) / float(s.active.h);
1030 float right = float(win.right) / float(s.active.w);
1031 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001032
Mathias Agopian875d8e12013-06-07 15:35:48 -07001033 // TODO: we probably want to generate the texture coords with the mesh
1034 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001035 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1036 texCoords[0] = vec2(left, 1.0f - top);
1037 texCoords[1] = vec2(left, 1.0f - bottom);
1038 texCoords[2] = vec2(right, 1.0f - bottom);
1039 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001040
Mathias Agopian875d8e12013-06-07 15:35:48 -07001041 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001042 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001043 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001044 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001045}
1046
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001047#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001048void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1049 bool callIntoHwc) {
1050 if (mHwcLayers.count(hwcId) == 0) {
1051 ALOGE("setCompositionType called without a valid HWC layer");
1052 return;
1053 }
1054 auto& hwcInfo = mHwcLayers[hwcId];
1055 auto& hwcLayer = hwcInfo.layer;
1056 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1057 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1058 if (hwcInfo.compositionType != type) {
1059 ALOGV(" actually setting");
1060 hwcInfo.compositionType = type;
1061 if (callIntoHwc) {
1062 auto error = hwcLayer->setCompositionType(type);
1063 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1064 "composition type %s: %s (%d)", mName.string(),
1065 to_string(type).c_str(), to_string(error).c_str(),
1066 static_cast<int32_t>(error));
1067 }
1068 }
1069}
1070
1071HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001072 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1073 // If we're querying the composition type for a display that does not
1074 // have a HWC counterpart, then it will always be Client
1075 return HWC2::Composition::Client;
1076 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001077 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001078 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001079 return HWC2::Composition::Invalid;
1080 }
1081 return mHwcLayers.at(hwcId).compositionType;
1082}
1083
1084void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1085 if (mHwcLayers.count(hwcId) == 0) {
1086 ALOGE("setClearClientTarget called without a valid HWC layer");
1087 return;
1088 }
1089 mHwcLayers[hwcId].clearClientTarget = clear;
1090}
1091
1092bool Layer::getClearClientTarget(int32_t hwcId) const {
1093 if (mHwcLayers.count(hwcId) == 0) {
1094 ALOGE("getClearClientTarget called without a valid HWC layer");
1095 return false;
1096 }
1097 return mHwcLayers.at(hwcId).clearClientTarget;
1098}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001099#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001100
Ruben Brunk1681d952014-06-27 15:51:55 -07001101uint32_t Layer::getProducerStickyTransform() const {
1102 int producerStickyTransform = 0;
1103 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1104 if (ret != OK) {
1105 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1106 strerror(-ret), ret);
1107 return 0;
1108 }
1109 return static_cast<uint32_t>(producerStickyTransform);
1110}
1111
Dan Stozac5da2712016-07-20 15:38:12 -07001112bool Layer::latchUnsignaledBuffers() {
1113 static bool propertyLoaded = false;
1114 static bool latch = false;
1115 static std::mutex mutex;
1116 std::lock_guard<std::mutex> lock(mutex);
1117 if (!propertyLoaded) {
1118 char value[PROPERTY_VALUE_MAX] = {};
1119 property_get("debug.sf.latch_unsignaled", value, "0");
1120 latch = atoi(value);
1121 propertyLoaded = true;
1122 }
1123 return latch;
1124}
1125
Dan Stozacac35382016-01-27 12:21:06 -08001126uint64_t Layer::getHeadFrameNumber() const {
1127 Mutex::Autolock lock(mQueueItemLock);
1128 if (!mQueueItems.empty()) {
1129 return mQueueItems[0].mFrameNumber;
1130 } else {
1131 return mCurrentFrameNumber;
1132 }
1133}
1134
Dan Stoza1ce65812016-06-15 16:26:27 -07001135bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001136#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001137 if (latchUnsignaledBuffers()) {
1138 return true;
1139 }
1140
Dan Stoza1ce65812016-06-15 16:26:27 -07001141 Mutex::Autolock lock(mQueueItemLock);
1142 if (mQueueItems.empty()) {
1143 return true;
1144 }
1145 if (mQueueItems[0].mIsDroppable) {
1146 // Even though this buffer's fence may not have signaled yet, it could
1147 // be replaced by another buffer before it has a chance to, which means
1148 // that it's possible to get into a situation where a buffer is never
1149 // able to be latched. To avoid this, grab this buffer anyway.
1150 return true;
1151 }
1152 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001153#else
1154 return true;
1155#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001156}
1157
Dan Stozacac35382016-01-27 12:21:06 -08001158bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1159 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1160 // Don't bother with a SyncPoint, since we've already latched the
1161 // relevant frame
1162 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001163 }
1164
Dan Stozacac35382016-01-27 12:21:06 -08001165 Mutex::Autolock lock(mLocalSyncPointMutex);
1166 mLocalSyncPoints.push_back(point);
1167 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001168}
1169
Mathias Agopian13127d82013-03-05 17:47:11 -08001170void Layer::setFiltering(bool filtering) {
1171 mFiltering = filtering;
1172}
1173
1174bool Layer::getFiltering() const {
1175 return mFiltering;
1176}
1177
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001178// As documented in libhardware header, formats in the range
1179// 0x100 - 0x1FF are specific to the HAL implementation, and
1180// are known to have no alpha channel
1181// TODO: move definition for device-specific range into
1182// hardware.h, instead of using hard-coded values here.
1183#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1184
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001185bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001186 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1187 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001188 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001189 switch (format) {
1190 case HAL_PIXEL_FORMAT_RGBA_8888:
1191 case HAL_PIXEL_FORMAT_BGRA_8888:
Mathias Agopiandd533712013-07-26 15:31:39 -07001192 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001193 }
1194 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001195 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001196}
1197
Mathias Agopian13127d82013-03-05 17:47:11 -08001198// ----------------------------------------------------------------------------
1199// local state
1200// ----------------------------------------------------------------------------
1201
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001202static void boundPoint(vec2* point, const Rect& crop) {
1203 if (point->x < crop.left) {
1204 point->x = crop.left;
1205 }
1206 if (point->x > crop.right) {
1207 point->x = crop.right;
1208 }
1209 if (point->y < crop.top) {
1210 point->y = crop.top;
1211 }
1212 if (point->y > crop.bottom) {
1213 point->y = crop.bottom;
1214 }
1215}
1216
Dan Stozac7014012014-02-14 15:03:43 -08001217void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1218 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001219{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001220 const Layer::State& s(getDrawingState());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001221 const Transform tr(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001222 const uint32_t hw_h = hw->getHeight();
1223 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -07001224 if (!s.crop.isEmpty()) {
1225 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -08001226 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -07001227 // subtract the transparent region and snap to the bounds
Mathias Agopianf3e85d42013-05-10 18:01:12 -07001228 win = reduce(win, s.activeTransparentRegion);
Mathias Agopian3f844832013-08-07 21:24:32 -07001229
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001230 vec2 lt = vec2(win.left, win.top);
1231 vec2 lb = vec2(win.left, win.bottom);
1232 vec2 rb = vec2(win.right, win.bottom);
1233 vec2 rt = vec2(win.right, win.top);
1234
1235 if (!useIdentityTransform) {
1236 lt = s.active.transform.transform(lt);
1237 lb = s.active.transform.transform(lb);
1238 rb = s.active.transform.transform(rb);
1239 rt = s.active.transform.transform(rt);
1240 }
1241
Robert Carrb5d3d262016-03-25 15:08:13 -07001242 if (!s.finalCrop.isEmpty()) {
1243 boundPoint(&lt, s.finalCrop);
1244 boundPoint(&lb, s.finalCrop);
1245 boundPoint(&rb, s.finalCrop);
1246 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001247 }
1248
Mathias Agopianff2ed702013-09-01 21:36:12 -07001249 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001250 position[0] = tr.transform(lt);
1251 position[1] = tr.transform(lb);
1252 position[2] = tr.transform(rb);
1253 position[3] = tr.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001254 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001255 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001256 }
1257}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001258
Andy McFadden4125a4f2014-01-29 17:17:11 -08001259bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001260{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001261 // if we don't have a buffer yet, we're translucent regardless of the
1262 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001263 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001264 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001265 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001266
1267 // if the layer has the opaque flag, then we're always opaque,
1268 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001269 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001270}
1271
Dan Stoza23116082015-06-18 14:58:39 -07001272bool Layer::isSecure() const
1273{
1274 const Layer::State& s(mDrawingState);
1275 return (s.flags & layer_state_t::eLayerSecure);
1276}
1277
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001278bool Layer::isProtected() const
1279{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001280 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001281 return (activeBuffer != 0) &&
1282 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1283}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001284
Mathias Agopian13127d82013-03-05 17:47:11 -08001285bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001286 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001287}
1288
1289bool Layer::isCropped() const {
1290 return !mCurrentCrop.isEmpty();
1291}
1292
1293bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1294 return mNeedsFiltering || hw->needsFiltering();
1295}
1296
1297void Layer::setVisibleRegion(const Region& visibleRegion) {
1298 // always called from main thread
1299 this->visibleRegion = visibleRegion;
1300}
1301
1302void Layer::setCoveredRegion(const Region& coveredRegion) {
1303 // always called from main thread
1304 this->coveredRegion = coveredRegion;
1305}
1306
1307void Layer::setVisibleNonTransparentRegion(const Region&
1308 setVisibleNonTransparentRegion) {
1309 // always called from main thread
1310 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1311}
1312
1313// ----------------------------------------------------------------------------
1314// transaction
1315// ----------------------------------------------------------------------------
1316
Dan Stoza7dde5992015-05-22 09:51:44 -07001317void Layer::pushPendingState() {
1318 if (!mCurrentState.modified) {
1319 return;
1320 }
1321
Dan Stoza7dde5992015-05-22 09:51:44 -07001322 // If this transaction is waiting on the receipt of a frame, generate a sync
1323 // point and send it to the remote layer.
1324 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001325 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1326 sp<Handle> handle = nullptr;
1327 sp<Layer> handleLayer = nullptr;
1328 if (strongBinder != nullptr) {
1329 handle = static_cast<Handle*>(strongBinder.get());
1330 handleLayer = handle->owner.promote();
1331 }
1332 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001333 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1334 // If we can't promote the layer we are intended to wait on,
1335 // then it is expired or otherwise invalid. Allow this transaction
1336 // to be applied as per normal (no synchronization).
1337 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001338 } else {
1339 auto syncPoint = std::make_shared<SyncPoint>(
1340 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001341 if (handleLayer->addSyncPoint(syncPoint)) {
1342 mRemoteSyncPoints.push_back(std::move(syncPoint));
1343 } else {
1344 // We already missed the frame we're supposed to synchronize
1345 // on, so go ahead and apply the state update
1346 mCurrentState.handle = nullptr;
1347 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001348 }
1349
Dan Stoza7dde5992015-05-22 09:51:44 -07001350 // Wake us up to check if the frame has been received
1351 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001352 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001353 }
1354 mPendingStates.push_back(mCurrentState);
1355}
1356
Pablo Ceballos05289c22016-04-14 15:49:55 -07001357void Layer::popPendingState(State* stateToCommit) {
1358 auto oldFlags = stateToCommit->flags;
1359 *stateToCommit = mPendingStates[0];
1360 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1361 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001362
1363 mPendingStates.removeAt(0);
1364}
1365
Pablo Ceballos05289c22016-04-14 15:49:55 -07001366bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001367 bool stateUpdateAvailable = false;
1368 while (!mPendingStates.empty()) {
1369 if (mPendingStates[0].handle != nullptr) {
1370 if (mRemoteSyncPoints.empty()) {
1371 // If we don't have a sync point for this, apply it anyway. It
1372 // will be visually wrong, but it should keep us from getting
1373 // into too much trouble.
1374 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001375 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001376 stateUpdateAvailable = true;
1377 continue;
1378 }
1379
Dan Stozacac35382016-01-27 12:21:06 -08001380 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1381 mPendingStates[0].frameNumber) {
1382 ALOGE("[%s] Unexpected sync point frame number found",
1383 mName.string());
1384
1385 // Signal our end of the sync point and then dispose of it
1386 mRemoteSyncPoints.front()->setTransactionApplied();
1387 mRemoteSyncPoints.pop_front();
1388 continue;
1389 }
1390
Dan Stoza7dde5992015-05-22 09:51:44 -07001391 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1392 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001393 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001394 stateUpdateAvailable = true;
1395
1396 // Signal our end of the sync point and then dispose of it
1397 mRemoteSyncPoints.front()->setTransactionApplied();
1398 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001399 } else {
1400 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001401 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001402 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001403 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001404 stateUpdateAvailable = true;
1405 }
1406 }
1407
1408 // If we still have pending updates, wake SurfaceFlinger back up and point
1409 // it at this layer so we can process them
1410 if (!mPendingStates.empty()) {
1411 setTransactionFlags(eTransactionNeeded);
1412 mFlinger->setTransactionFlags(eTraversalNeeded);
1413 }
1414
1415 mCurrentState.modified = false;
1416 return stateUpdateAvailable;
1417}
1418
1419void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001420 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001421 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001422 Mutex::Autolock lock(mLocalSyncPointMutex);
1423 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001424 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001425 point->setFrameAvailable();
1426 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001427 }
1428}
1429
Mathias Agopian13127d82013-03-05 17:47:11 -08001430uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001431 ATRACE_CALL();
1432
Dan Stoza7dde5992015-05-22 09:51:44 -07001433 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001434 Layer::State c = getCurrentState();
1435 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001436 return 0;
1437 }
1438
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001439 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001440
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001441 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1442 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001443
1444 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001445 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001446 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001447 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001448 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001449 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001450 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001451 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001452 this, getName().string(), mCurrentTransform,
1453 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001454 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001455 c.crop.left,
1456 c.crop.top,
1457 c.crop.right,
1458 c.crop.bottom,
1459 c.crop.getWidth(),
1460 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001461 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001462 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001463 s.crop.left,
1464 s.crop.top,
1465 s.crop.right,
1466 s.crop.bottom,
1467 s.crop.getWidth(),
1468 s.crop.getHeight(),
1469 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001471 // record the new size, form this point on, when the client request
1472 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001473 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001474 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001475 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001476
Robert Carr82364e32016-05-15 11:27:47 -07001477 const bool resizePending = (c.requested.w != c.active.w) ||
1478 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001479 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001480 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001481 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001482 // if we have a pending resize, unless we are in fixed-size mode.
1483 // the drawing state will be updated only once we receive a buffer
1484 // with the correct size.
1485 //
1486 // in particular, we want to make sure the clip (which is part
1487 // of the geometry state) is latched together with the size but is
1488 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001489 //
1490 // If a sideband stream is attached, however, we want to skip this
1491 // optimization so that transactions aren't missed when a buffer
1492 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001493
1494 flags |= eDontUpdateGeometryState;
1495 }
1496 }
1497
Mathias Agopian13127d82013-03-05 17:47:11 -08001498 // always set active to requested, unless we're asked not to
1499 // this is used by Layer, which special cases resizes.
1500 if (flags & eDontUpdateGeometryState) {
1501 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001502 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001503 if (mFreezePositionUpdates) {
1504 float tx = c.active.transform.tx();
1505 float ty = c.active.transform.ty();
1506 c.active = c.requested;
1507 c.active.transform.set(tx, ty);
1508 editCurrentState.active = c.active;
1509 } else {
1510 editCurrentState.active = editCurrentState.requested;
1511 c.active = c.requested;
1512 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001513 }
1514
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001515 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001516 // invalidate and recompute the visible regions if needed
1517 flags |= Layer::eVisibleRegion;
1518 }
1519
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001520 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001521 // invalidate and recompute the visible regions if needed
1522 flags |= eVisibleRegion;
1523 this->contentDirty = true;
1524
1525 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001526 const uint8_t type = c.active.transform.getType();
1527 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001528 (type >= Transform::SCALE));
1529 }
1530
Dan Stozac8145172016-04-28 16:29:06 -07001531 // If the layer is hidden, signal and clear out all local sync points so
1532 // that transactions for layers depending on this layer's frames becoming
1533 // visible are not blocked
1534 if (c.flags & layer_state_t::eLayerHidden) {
1535 Mutex::Autolock lock(mLocalSyncPointMutex);
1536 for (auto& point : mLocalSyncPoints) {
1537 point->setFrameAvailable();
1538 }
1539 mLocalSyncPoints.clear();
1540 }
1541
Mathias Agopian13127d82013-03-05 17:47:11 -08001542 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001543 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001544 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001545}
1546
Pablo Ceballos05289c22016-04-14 15:49:55 -07001547void Layer::commitTransaction(const State& stateToCommit) {
1548 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001549}
1550
Mathias Agopian13127d82013-03-05 17:47:11 -08001551uint32_t Layer::getTransactionFlags(uint32_t flags) {
1552 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1553}
1554
1555uint32_t Layer::setTransactionFlags(uint32_t flags) {
1556 return android_atomic_or(flags, &mTransactionFlags);
1557}
1558
Robert Carr82364e32016-05-15 11:27:47 -07001559bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001560 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001561 return false;
1562 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001563
1564 // We update the requested and active position simultaneously because
1565 // we want to apply the position portion of the transform matrix immediately,
1566 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001567 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001568 if (immediate && !mFreezePositionUpdates) {
1569 mCurrentState.active.transform.set(x, y);
1570 }
1571 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001572
Dan Stoza7dde5992015-05-22 09:51:44 -07001573 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001574 setTransactionFlags(eTransactionNeeded);
1575 return true;
1576}
Robert Carr82364e32016-05-15 11:27:47 -07001577
Mathias Agopian13127d82013-03-05 17:47:11 -08001578bool Layer::setLayer(uint32_t z) {
1579 if (mCurrentState.z == z)
1580 return false;
1581 mCurrentState.sequence++;
1582 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001583 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001584 setTransactionFlags(eTransactionNeeded);
1585 return true;
1586}
1587bool Layer::setSize(uint32_t w, uint32_t h) {
1588 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1589 return false;
1590 mCurrentState.requested.w = w;
1591 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001592 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001593 setTransactionFlags(eTransactionNeeded);
1594 return true;
1595}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001596#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001597bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001598#else
1599bool Layer::setAlpha(uint8_t alpha) {
1600#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001601 if (mCurrentState.alpha == alpha)
1602 return false;
1603 mCurrentState.sequence++;
1604 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001605 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001606 setTransactionFlags(eTransactionNeeded);
1607 return true;
1608}
1609bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1610 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001611 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001612 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001613 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001614 setTransactionFlags(eTransactionNeeded);
1615 return true;
1616}
1617bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001618 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001619 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001620 setTransactionFlags(eTransactionNeeded);
1621 return true;
1622}
1623bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1624 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1625 if (mCurrentState.flags == newFlags)
1626 return false;
1627 mCurrentState.sequence++;
1628 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001629 mCurrentState.mask = mask;
1630 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001631 setTransactionFlags(eTransactionNeeded);
1632 return true;
1633}
Robert Carr99e27f02016-06-16 15:18:02 -07001634
1635bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001636 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001637 return false;
1638 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001639 mCurrentState.requestedCrop = crop;
1640 if (immediate) {
1641 mCurrentState.crop = crop;
1642 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001643 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001644 setTransactionFlags(eTransactionNeeded);
1645 return true;
1646}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001647bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001648 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001649 return false;
1650 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001651 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001652 mCurrentState.modified = true;
1653 setTransactionFlags(eTransactionNeeded);
1654 return true;
1655}
Mathias Agopian13127d82013-03-05 17:47:11 -08001656
Robert Carrc3574f72016-03-24 12:19:32 -07001657bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1658 if (scalingMode == mOverrideScalingMode)
1659 return false;
1660 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001661 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001662 return true;
1663}
1664
1665uint32_t Layer::getEffectiveScalingMode() const {
1666 if (mOverrideScalingMode >= 0) {
1667 return mOverrideScalingMode;
1668 }
1669 return mCurrentScalingMode;
1670}
1671
Mathias Agopian13127d82013-03-05 17:47:11 -08001672bool Layer::setLayerStack(uint32_t layerStack) {
1673 if (mCurrentState.layerStack == layerStack)
1674 return false;
1675 mCurrentState.sequence++;
1676 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001677 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001678 setTransactionFlags(eTransactionNeeded);
1679 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001680}
1681
Dan Stoza7dde5992015-05-22 09:51:44 -07001682void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1683 uint64_t frameNumber) {
1684 mCurrentState.handle = handle;
1685 mCurrentState.frameNumber = frameNumber;
1686 // We don't set eTransactionNeeded, because just receiving a deferral
1687 // request without any other state updates shouldn't actually induce a delay
1688 mCurrentState.modified = true;
1689 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001690 mCurrentState.handle = nullptr;
1691 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001692 mCurrentState.modified = false;
1693}
1694
Dan Stozaee44edd2015-03-23 15:50:23 -07001695void Layer::useSurfaceDamage() {
1696 if (mFlinger->mForceFullDamage) {
1697 surfaceDamageRegion = Region::INVALID_REGION;
1698 } else {
1699 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1700 }
1701}
1702
1703void Layer::useEmptyDamage() {
1704 surfaceDamageRegion.clear();
1705}
1706
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001707// ----------------------------------------------------------------------------
1708// pageflip handling...
1709// ----------------------------------------------------------------------------
1710
Dan Stoza6b9454d2014-11-07 16:00:59 -08001711bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001712 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001713 return true;
1714 }
1715
Dan Stoza6b9454d2014-11-07 16:00:59 -08001716 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001717 if (mQueueItems.empty()) {
1718 return false;
1719 }
1720 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001721 nsecs_t expectedPresent =
1722 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001723
1724 // Ignore timestamps more than a second in the future
1725 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1726 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1727 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1728 expectedPresent);
1729
1730 bool isDue = timestamp < expectedPresent;
1731 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001732}
1733
Brian Andersond6927fb2016-07-23 23:37:30 -07001734bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1735 if (mBufferLatched) {
1736 Mutex::Autolock lock(mFrameEventHistoryMutex);
1737 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1738 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001739 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001740 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001741}
1742
Brian Anderson3d4039d2016-09-23 16:31:30 -07001743bool Layer::onPostComposition(
1744 const std::shared_ptr<FenceTime>& glDoneFence,
1745 const std::shared_ptr<FenceTime>& presentFence,
1746 const std::shared_ptr<FenceTime>& retireFence) {
1747 mAcquireTimeline.updateSignalTimes();
1748 mReleaseTimeline.updateSignalTimes();
1749
Brian Andersond6927fb2016-07-23 23:37:30 -07001750 // mFrameLatencyNeeded is true when a new frame was latched for the
1751 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001752 if (!mFrameLatencyNeeded)
1753 return false;
1754
Fabien Sanglard28e98082016-12-05 10:19:46 -08001755 // Update mFrameEventHistory.
1756 {
1757 Mutex::Autolock lock(mFrameEventHistoryMutex);
1758 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001759 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001760 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1761 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001762 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001763
1764 // Update mFrameTracker.
1765 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1766 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1767
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768 std::shared_ptr<FenceTime> frameReadyFence =
1769 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001770 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001771 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001772 } else {
1773 // There was no fence for this frame, so assume that it was ready
1774 // to be presented at the desired present time.
1775 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1776 }
1777
Brian Anderson3d4039d2016-09-23 16:31:30 -07001778 if (presentFence->isValid()) {
1779 mFrameTracker.setActualPresentFence(
1780 std::shared_ptr<FenceTime>(presentFence));
1781 } else if (retireFence->isValid()) {
1782 mFrameTracker.setActualPresentFence(
1783 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001784 } else {
1785 // The HWC doesn't support present fences, so use the refresh
1786 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001787 mFrameTracker.setActualPresentTime(
1788 mFlinger->getHwComposer().getRefreshTimestamp(
1789 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001790 }
1791
1792 mFrameTracker.advanceFrame();
1793 mFrameLatencyNeeded = false;
1794 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001795}
1796
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001797#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001798void Layer::releasePendingBuffer() {
1799 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001800 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001801 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001802 mReleaseTimeline.push(releaseFenceTime);
1803
1804 Mutex::Autolock lock(mFrameEventHistoryMutex);
1805 mFrameEventHistory.addRelease(
1806 mPreviousFrameNumber, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001808#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809
Mathias Agopianda27af92012-09-13 18:17:13 -07001810bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001811 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001812#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001813 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1814 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001815#else
1816 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1817 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1818#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001819}
1820
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001821bool Layer::allTransactionsSignaled() {
1822 auto headFrameNumber = getHeadFrameNumber();
1823 bool matchingFramesFound = false;
1824 bool allTransactionsApplied = true;
1825 Mutex::Autolock lock(mLocalSyncPointMutex);
1826
1827 for (auto& point : mLocalSyncPoints) {
1828 if (point->getFrameNumber() > headFrameNumber) {
1829 break;
1830 }
1831 matchingFramesFound = true;
1832
1833 if (!point->frameIsAvailable()) {
1834 // We haven't notified the remote layer that the frame for
1835 // this point is available yet. Notify it now, and then
1836 // abort this attempt to latch.
1837 point->setFrameAvailable();
1838 allTransactionsApplied = false;
1839 break;
1840 }
1841
1842 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1843 }
1844 return !matchingFramesFound || allTransactionsApplied;
1845}
1846
Brian Andersond6927fb2016-07-23 23:37:30 -07001847Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001848{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001849 ATRACE_CALL();
1850
Jesse Hall399184a2014-03-03 15:42:54 -08001851 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1852 // mSidebandStreamChanged was true
1853 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07001854 if (mSidebandStream != NULL) {
1855 setTransactionFlags(eTransactionNeeded);
1856 mFlinger->setTransactionFlags(eTraversalNeeded);
1857 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07001858 recomputeVisibleRegions = true;
1859
1860 const State& s(getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001861 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08001862 }
1863
Mathias Agopian4fec8732012-06-29 14:12:52 -07001864 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07001865 if (mQueuedFrames <= 0 && !mAutoRefresh) {
1866 return outDirtyRegion;
1867 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001868
Fabien Sanglard223eb912016-10-13 10:15:06 -07001869 // if we've already called updateTexImage() without going through
1870 // a composition step, we have to skip this layer at this point
1871 // because we cannot call updateTeximage() without a corresponding
1872 // compositionComplete() call.
1873 // we'll trigger an update in onPreComposition().
1874 if (mRefreshPending) {
1875 return outDirtyRegion;
1876 }
1877
1878 // If the head buffer's acquire fence hasn't signaled yet, return and
1879 // try again later
1880 if (!headFenceHasSignaled()) {
1881 mFlinger->signalLayerUpdate();
1882 return outDirtyRegion;
1883 }
1884
1885 // Capture the old state of the layer for comparisons later
1886 const State& s(getDrawingState());
1887 const bool oldOpacity = isOpaque(s);
1888 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1889
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001890 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07001891 mFlinger->signalLayerUpdate();
1892 return outDirtyRegion;
1893 }
1894
1895 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1896 // of the buffer queue isn't modified when the buffer queue is returning
1897 // BufferItem's that weren't actually queued. This can happen in shared
1898 // buffer mode.
1899 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07001900 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1901 getProducerStickyTransform() != 0, mName.string(),
1902 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07001903 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1904 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1905 mLastFrameNumberReceived);
1906 if (updateResult == BufferQueue::PRESENT_LATER) {
1907 // Producer doesn't want buffer to be displayed yet. Signal a
1908 // layer update so we check again at the next opportunity.
1909 mFlinger->signalLayerUpdate();
1910 return outDirtyRegion;
1911 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1912 // If the buffer has been rejected, remove it from the shadow queue
1913 // and return early
1914 if (queuedBuffer) {
1915 Mutex::Autolock lock(mQueueItemLock);
1916 mQueueItems.removeAt(0);
1917 android_atomic_dec(&mQueuedFrames);
1918 }
1919 return outDirtyRegion;
1920 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1921 // This can occur if something goes wrong when trying to create the
1922 // EGLImage for this buffer. If this happens, the buffer has already
1923 // been released, so we need to clean up the queue and bug out
1924 // early.
1925 if (queuedBuffer) {
1926 Mutex::Autolock lock(mQueueItemLock);
1927 mQueueItems.clear();
1928 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07001929 }
1930
Fabien Sanglard223eb912016-10-13 10:15:06 -07001931 // Once we have hit this state, the shadow queue may no longer
1932 // correctly reflect the incoming BufferQueue's contents, so even if
1933 // updateTexImage starts working, the only safe course of action is
1934 // to continue to ignore updates.
1935 mUpdateTexImageFailed = true;
1936
1937 return outDirtyRegion;
1938 }
1939
1940 if (queuedBuffer) {
1941 // Autolock scope
1942 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1943
1944 Mutex::Autolock lock(mQueueItemLock);
1945
1946 // Remove any stale buffers that have been dropped during
1947 // updateTexImage
1948 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1949 mQueueItems.removeAt(0);
1950 android_atomic_dec(&mQueuedFrames);
1951 }
1952
1953 mQueueItems.removeAt(0);
1954 }
1955
1956
1957 // Decrement the queued-frames count. Signal another event if we
1958 // have more frames pending.
1959 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1960 || mAutoRefresh) {
1961 mFlinger->signalLayerUpdate();
1962 }
1963
Fabien Sanglard223eb912016-10-13 10:15:06 -07001964 // update the active buffer
1965 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1966 if (mActiveBuffer == NULL) {
1967 // this can only happen if the very first buffer was rejected.
1968 return outDirtyRegion;
1969 }
1970
Brian Andersond6927fb2016-07-23 23:37:30 -07001971 mBufferLatched = true;
1972 mPreviousFrameNumber = mCurrentFrameNumber;
1973 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1974
1975 {
1976 Mutex::Autolock lock(mFrameEventHistoryMutex);
1977 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
1978#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07001979 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001980 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001981 mReleaseTimeline.push(releaseFenceTime);
1982 mFrameEventHistory.addRelease(
1983 mPreviousFrameNumber, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07001984#endif
1985 }
1986
Fabien Sanglard223eb912016-10-13 10:15:06 -07001987 mRefreshPending = true;
1988 mFrameLatencyNeeded = true;
1989 if (oldActiveBuffer == NULL) {
1990 // the first time we receive a buffer, we need to trigger a
1991 // geometry invalidation.
1992 recomputeVisibleRegions = true;
1993 }
1994
1995 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1996 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1997 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1998 if ((crop != mCurrentCrop) ||
1999 (transform != mCurrentTransform) ||
2000 (scalingMode != mCurrentScalingMode))
2001 {
2002 mCurrentCrop = crop;
2003 mCurrentTransform = transform;
2004 mCurrentScalingMode = scalingMode;
2005 recomputeVisibleRegions = true;
2006 }
2007
2008 if (oldActiveBuffer != NULL) {
2009 uint32_t bufWidth = mActiveBuffer->getWidth();
2010 uint32_t bufHeight = mActiveBuffer->getHeight();
2011 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2012 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002013 recomputeVisibleRegions = true;
2014 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002015 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002016
Fabien Sanglard223eb912016-10-13 10:15:06 -07002017 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2018 if (oldOpacity != isOpaque(s)) {
2019 recomputeVisibleRegions = true;
2020 }
Dan Stozacac35382016-01-27 12:21:06 -08002021
Fabien Sanglard223eb912016-10-13 10:15:06 -07002022 // Remove any sync points corresponding to the buffer which was just
2023 // latched
2024 {
2025 Mutex::Autolock lock(mLocalSyncPointMutex);
2026 auto point = mLocalSyncPoints.begin();
2027 while (point != mLocalSyncPoints.end()) {
2028 if (!(*point)->frameIsAvailable() ||
2029 !(*point)->transactionIsApplied()) {
2030 // This sync point must have been added since we started
2031 // latching. Don't drop it yet.
2032 ++point;
2033 continue;
2034 }
2035
2036 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2037 point = mLocalSyncPoints.erase(point);
2038 } else {
2039 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002040 }
2041 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002042 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002043
2044 // FIXME: postedRegion should be dirty & bounds
2045 Region dirtyRegion(Rect(s.active.w, s.active.h));
2046
2047 // transform the dirty region to window-manager space
2048 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2049
Mathias Agopian4fec8732012-06-29 14:12:52 -07002050 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051}
2052
Mathias Agopiana67932f2011-04-20 14:20:59 -07002053uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002054{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002055 // TODO: should we do something special if mSecure is set?
2056 if (mProtectedByApp) {
2057 // need a hardware-protected path to external video sink
2058 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002059 }
Riley Andrews03414a12014-07-01 14:22:59 -07002060 if (mPotentialCursor) {
2061 usage |= GraphicBuffer::USAGE_CURSOR;
2062 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002063 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002064 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002065}
2066
Mathias Agopian84300952012-11-21 16:02:13 -08002067void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002068 uint32_t orientation = 0;
2069 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002070 // The transform hint is used to improve performance, but we can
2071 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002072 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002073 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002074 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002075 if (orientation & Transform::ROT_INVALID) {
2076 orientation = 0;
2077 }
2078 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002079 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002080}
2081
Mathias Agopian13127d82013-03-05 17:47:11 -08002082// ----------------------------------------------------------------------------
2083// debugging
2084// ----------------------------------------------------------------------------
2085
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002086void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002087{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002088 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002089
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002090 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002091 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002092 "+ %s %p (%s)\n",
2093 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002094 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002095
Mathias Agopian2ca79392013-04-02 18:30:32 -07002096 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002097 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002098 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002099 sp<Client> client(mClientRef.promote());
2100
Mathias Agopian74d211a2013-04-22 16:55:35 +02002101 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002102 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2103 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002104 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002105#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002107#else
2108 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2109#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002110 " client=%p\n",
Robert Carr3dcabfa2016-03-01 18:36:58 -08002111 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07002112 s.crop.left, s.crop.top,
2113 s.crop.right, s.crop.bottom,
2114 s.finalCrop.left, s.finalCrop.top,
2115 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002116 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002117 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002118 s.active.transform[0][0], s.active.transform[0][1],
2119 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002120 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002121
2122 sp<const GraphicBuffer> buf0(mActiveBuffer);
2123 uint32_t w0=0, h0=0, s0=0, f0=0;
2124 if (buf0 != 0) {
2125 w0 = buf0->getWidth();
2126 h0 = buf0->getHeight();
2127 s0 = buf0->getStride();
2128 f0 = buf0->format;
2129 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002130 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002131 " "
2132 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2133 " queued-frames=%d, mRefreshPending=%d\n",
2134 mFormat, w0, h0, s0,f0,
2135 mQueuedFrames, mRefreshPending);
2136
Mathias Agopian13127d82013-03-05 17:47:11 -08002137 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002138 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002139 }
2140}
2141
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002142#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002143void Layer::miniDumpHeader(String8& result) {
2144 result.append("----------------------------------------");
2145 result.append("---------------------------------------\n");
2146 result.append(" Layer name\n");
2147 result.append(" Z | ");
2148 result.append(" Comp Type | ");
2149 result.append(" Disp Frame (LTRB) | ");
2150 result.append(" Source Crop (LTRB)\n");
2151 result.append("----------------------------------------");
2152 result.append("---------------------------------------\n");
2153}
2154
2155void Layer::miniDump(String8& result, int32_t hwcId) const {
2156 if (mHwcLayers.count(hwcId) == 0) {
2157 return;
2158 }
2159
2160 String8 name;
2161 if (mName.length() > 77) {
2162 std::string shortened;
2163 shortened.append(mName.string(), 36);
2164 shortened.append("[...]");
2165 shortened.append(mName.string() + (mName.length() - 36), 36);
2166 name = shortened.c_str();
2167 } else {
2168 name = mName;
2169 }
2170
2171 result.appendFormat(" %s\n", name.string());
2172
2173 const Layer::State& layerState(getDrawingState());
2174 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2175 result.appendFormat(" %10u | ", layerState.z);
2176 result.appendFormat("%10s | ",
2177 to_string(getCompositionType(hwcId)).c_str());
2178 const Rect& frame = hwcInfo.displayFrame;
2179 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2180 frame.right, frame.bottom);
2181 const FloatRect& crop = hwcInfo.sourceCrop;
2182 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2183 crop.right, crop.bottom);
2184
2185 result.append("- - - - - - - - - - - - - - - - - - - - ");
2186 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2187}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002188#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002189
Svetoslavd85084b2014-03-20 10:28:31 -07002190void Layer::dumpFrameStats(String8& result) const {
2191 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002192}
2193
Svetoslavd85084b2014-03-20 10:28:31 -07002194void Layer::clearFrameStats() {
2195 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002196}
2197
Jamie Gennis6547ff42013-07-16 20:12:42 -07002198void Layer::logFrameStats() {
2199 mFrameTracker.logAndResetStats(mName);
2200}
2201
Svetoslavd85084b2014-03-20 10:28:31 -07002202void Layer::getFrameStats(FrameStats* outStats) const {
2203 mFrameTracker.getStats(outStats);
2204}
2205
Brian Andersond6927fb2016-07-23 23:37:30 -07002206void Layer::dumpFrameEvents(String8& result) {
2207 result.appendFormat("- Layer %s (%s, %p)\n",
2208 getName().string(), getTypeId(), this);
2209 Mutex::Autolock lock(mFrameEventHistoryMutex);
2210 mFrameEventHistory.checkFencesForCompletion();
2211 mFrameEventHistory.dump(result);
2212}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002213
Brian Anderson3890c392016-07-25 12:48:08 -07002214void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2215 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002216 Mutex::Autolock lock(mFrameEventHistoryMutex);
2217 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002218 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002219 mFrameEventHistory.addQueue(*newTimestamps);
2220 }
2221
Brian Anderson3890c392016-07-25 12:48:08 -07002222 if (outDelta) {
2223 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002224 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002225}
Dan Stozae77c7662016-05-13 11:37:28 -07002226
2227std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2228 bool forceFlush) {
2229 std::vector<OccupancyTracker::Segment> history;
2230 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2231 &history);
2232 if (result != NO_ERROR) {
2233 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2234 result);
2235 return {};
2236 }
2237 return history;
2238}
2239
Robert Carr367c5682016-06-20 11:55:28 -07002240bool Layer::getTransformToDisplayInverse() const {
2241 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2242}
2243
Mathias Agopian13127d82013-03-05 17:47:11 -08002244// ---------------------------------------------------------------------------
2245
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002246}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002247
2248#if defined(__gl_h_)
2249#error "don't include gl/gl.h in this file"
2250#endif
2251
2252#if defined(__gl2_h_)
2253#error "don't include gl2/gl2.h in this file"
2254#endif