blob: 9eaf57be92d1e2dbb6c59f13e12c7f5fadb166f0 [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
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800168 if (mFlinger->isLayerTripleBufferingDisabled()) {
169 mProducer->setMaxDequeuedBufferCount(2);
170 }
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
Dan Stoza71bded52016-10-19 11:10:33 -0700380gfx::FloatRect 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.
Dan Stoza71bded52016-10-19 11:10:33 -0700383 gfx::FloatRect crop = getContentCrop().toFloatRect();
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
Dan Stoza71bded52016-10-19 11:10:33 -0700588 gfx::FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 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 }
Fabien Sanglard85789802016-12-07 13:08:24 -0800975 drawWithOpenGL(hw, 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,
Fabien Sanglard85789802016-12-07 13:08:24 -0800996 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:
Romain Guyff415142016-12-13 16:51:25 -08001192 case HAL_PIXEL_FORMAT_RGBA_FP16:
Mathias Agopiandd533712013-07-26 15:31:39 -07001193 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001194 }
1195 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001196 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001197}
1198
Mathias Agopian13127d82013-03-05 17:47:11 -08001199// ----------------------------------------------------------------------------
1200// local state
1201// ----------------------------------------------------------------------------
1202
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001203static void boundPoint(vec2* point, const Rect& crop) {
1204 if (point->x < crop.left) {
1205 point->x = crop.left;
1206 }
1207 if (point->x > crop.right) {
1208 point->x = crop.right;
1209 }
1210 if (point->y < crop.top) {
1211 point->y = crop.top;
1212 }
1213 if (point->y > crop.bottom) {
1214 point->y = crop.bottom;
1215 }
1216}
1217
Dan Stozac7014012014-02-14 15:03:43 -08001218void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1219 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001220{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001221 const Layer::State& s(getDrawingState());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001222 const Transform tr(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001223 const uint32_t hw_h = hw->getHeight();
1224 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -07001225 if (!s.crop.isEmpty()) {
1226 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -08001227 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -07001228 // subtract the transparent region and snap to the bounds
Mathias Agopianf3e85d42013-05-10 18:01:12 -07001229 win = reduce(win, s.activeTransparentRegion);
Mathias Agopian3f844832013-08-07 21:24:32 -07001230
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001231 vec2 lt = vec2(win.left, win.top);
1232 vec2 lb = vec2(win.left, win.bottom);
1233 vec2 rb = vec2(win.right, win.bottom);
1234 vec2 rt = vec2(win.right, win.top);
1235
1236 if (!useIdentityTransform) {
1237 lt = s.active.transform.transform(lt);
1238 lb = s.active.transform.transform(lb);
1239 rb = s.active.transform.transform(rb);
1240 rt = s.active.transform.transform(rt);
1241 }
1242
Robert Carrb5d3d262016-03-25 15:08:13 -07001243 if (!s.finalCrop.isEmpty()) {
1244 boundPoint(&lt, s.finalCrop);
1245 boundPoint(&lb, s.finalCrop);
1246 boundPoint(&rb, s.finalCrop);
1247 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001248 }
1249
Mathias Agopianff2ed702013-09-01 21:36:12 -07001250 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001251 position[0] = tr.transform(lt);
1252 position[1] = tr.transform(lb);
1253 position[2] = tr.transform(rb);
1254 position[3] = tr.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001255 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001256 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001257 }
1258}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001259
Andy McFadden4125a4f2014-01-29 17:17:11 -08001260bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001261{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001262 // if we don't have a buffer yet, we're translucent regardless of the
1263 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001264 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001265 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001266 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001267
1268 // if the layer has the opaque flag, then we're always opaque,
1269 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001270 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001271}
1272
Dan Stoza23116082015-06-18 14:58:39 -07001273bool Layer::isSecure() const
1274{
1275 const Layer::State& s(mDrawingState);
1276 return (s.flags & layer_state_t::eLayerSecure);
1277}
1278
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001279bool Layer::isProtected() const
1280{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001281 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001282 return (activeBuffer != 0) &&
1283 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1284}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001285
Mathias Agopian13127d82013-03-05 17:47:11 -08001286bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001287 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001288}
1289
1290bool Layer::isCropped() const {
1291 return !mCurrentCrop.isEmpty();
1292}
1293
1294bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1295 return mNeedsFiltering || hw->needsFiltering();
1296}
1297
1298void Layer::setVisibleRegion(const Region& visibleRegion) {
1299 // always called from main thread
1300 this->visibleRegion = visibleRegion;
1301}
1302
1303void Layer::setCoveredRegion(const Region& coveredRegion) {
1304 // always called from main thread
1305 this->coveredRegion = coveredRegion;
1306}
1307
1308void Layer::setVisibleNonTransparentRegion(const Region&
1309 setVisibleNonTransparentRegion) {
1310 // always called from main thread
1311 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1312}
1313
1314// ----------------------------------------------------------------------------
1315// transaction
1316// ----------------------------------------------------------------------------
1317
Dan Stoza7dde5992015-05-22 09:51:44 -07001318void Layer::pushPendingState() {
1319 if (!mCurrentState.modified) {
1320 return;
1321 }
1322
Dan Stoza7dde5992015-05-22 09:51:44 -07001323 // If this transaction is waiting on the receipt of a frame, generate a sync
1324 // point and send it to the remote layer.
1325 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001326 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1327 sp<Handle> handle = nullptr;
1328 sp<Layer> handleLayer = nullptr;
1329 if (strongBinder != nullptr) {
1330 handle = static_cast<Handle*>(strongBinder.get());
1331 handleLayer = handle->owner.promote();
1332 }
1333 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001334 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1335 // If we can't promote the layer we are intended to wait on,
1336 // then it is expired or otherwise invalid. Allow this transaction
1337 // to be applied as per normal (no synchronization).
1338 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001339 } else {
1340 auto syncPoint = std::make_shared<SyncPoint>(
1341 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001342 if (handleLayer->addSyncPoint(syncPoint)) {
1343 mRemoteSyncPoints.push_back(std::move(syncPoint));
1344 } else {
1345 // We already missed the frame we're supposed to synchronize
1346 // on, so go ahead and apply the state update
1347 mCurrentState.handle = nullptr;
1348 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001349 }
1350
Dan Stoza7dde5992015-05-22 09:51:44 -07001351 // Wake us up to check if the frame has been received
1352 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001353 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001354 }
1355 mPendingStates.push_back(mCurrentState);
1356}
1357
Pablo Ceballos05289c22016-04-14 15:49:55 -07001358void Layer::popPendingState(State* stateToCommit) {
1359 auto oldFlags = stateToCommit->flags;
1360 *stateToCommit = mPendingStates[0];
1361 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1362 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001363
1364 mPendingStates.removeAt(0);
1365}
1366
Pablo Ceballos05289c22016-04-14 15:49:55 -07001367bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001368 bool stateUpdateAvailable = false;
1369 while (!mPendingStates.empty()) {
1370 if (mPendingStates[0].handle != nullptr) {
1371 if (mRemoteSyncPoints.empty()) {
1372 // If we don't have a sync point for this, apply it anyway. It
1373 // will be visually wrong, but it should keep us from getting
1374 // into too much trouble.
1375 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001376 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001377 stateUpdateAvailable = true;
1378 continue;
1379 }
1380
Dan Stozacac35382016-01-27 12:21:06 -08001381 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1382 mPendingStates[0].frameNumber) {
1383 ALOGE("[%s] Unexpected sync point frame number found",
1384 mName.string());
1385
1386 // Signal our end of the sync point and then dispose of it
1387 mRemoteSyncPoints.front()->setTransactionApplied();
1388 mRemoteSyncPoints.pop_front();
1389 continue;
1390 }
1391
Dan Stoza7dde5992015-05-22 09:51:44 -07001392 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1393 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001394 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001395 stateUpdateAvailable = true;
1396
1397 // Signal our end of the sync point and then dispose of it
1398 mRemoteSyncPoints.front()->setTransactionApplied();
1399 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001400 } else {
1401 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001402 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001403 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001404 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001405 stateUpdateAvailable = true;
1406 }
1407 }
1408
1409 // If we still have pending updates, wake SurfaceFlinger back up and point
1410 // it at this layer so we can process them
1411 if (!mPendingStates.empty()) {
1412 setTransactionFlags(eTransactionNeeded);
1413 mFlinger->setTransactionFlags(eTraversalNeeded);
1414 }
1415
1416 mCurrentState.modified = false;
1417 return stateUpdateAvailable;
1418}
1419
1420void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001421 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001422 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001423 Mutex::Autolock lock(mLocalSyncPointMutex);
1424 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001425 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001426 point->setFrameAvailable();
1427 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001428 }
1429}
1430
Mathias Agopian13127d82013-03-05 17:47:11 -08001431uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001432 ATRACE_CALL();
1433
Dan Stoza7dde5992015-05-22 09:51:44 -07001434 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001435 Layer::State c = getCurrentState();
1436 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001437 return 0;
1438 }
1439
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001440 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001441
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001442 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1443 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001444
1445 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001446 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001447 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001448 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001449 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001450 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001451 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001452 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001453 this, getName().string(), mCurrentTransform,
1454 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001455 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001456 c.crop.left,
1457 c.crop.top,
1458 c.crop.right,
1459 c.crop.bottom,
1460 c.crop.getWidth(),
1461 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001462 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001463 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001464 s.crop.left,
1465 s.crop.top,
1466 s.crop.right,
1467 s.crop.bottom,
1468 s.crop.getWidth(),
1469 s.crop.getHeight(),
1470 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001471
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001472 // record the new size, form this point on, when the client request
1473 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001474 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001475 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001476 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001477
Robert Carr82364e32016-05-15 11:27:47 -07001478 const bool resizePending = (c.requested.w != c.active.w) ||
1479 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001480 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001481 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001482 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001483 // if we have a pending resize, unless we are in fixed-size mode.
1484 // the drawing state will be updated only once we receive a buffer
1485 // with the correct size.
1486 //
1487 // in particular, we want to make sure the clip (which is part
1488 // of the geometry state) is latched together with the size but is
1489 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001490 //
1491 // If a sideband stream is attached, however, we want to skip this
1492 // optimization so that transactions aren't missed when a buffer
1493 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001494
1495 flags |= eDontUpdateGeometryState;
1496 }
1497 }
1498
Mathias Agopian13127d82013-03-05 17:47:11 -08001499 // always set active to requested, unless we're asked not to
1500 // this is used by Layer, which special cases resizes.
1501 if (flags & eDontUpdateGeometryState) {
1502 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001503 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001504 if (mFreezePositionUpdates) {
1505 float tx = c.active.transform.tx();
1506 float ty = c.active.transform.ty();
1507 c.active = c.requested;
1508 c.active.transform.set(tx, ty);
1509 editCurrentState.active = c.active;
1510 } else {
1511 editCurrentState.active = editCurrentState.requested;
1512 c.active = c.requested;
1513 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001514 }
1515
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001516 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001517 // invalidate and recompute the visible regions if needed
1518 flags |= Layer::eVisibleRegion;
1519 }
1520
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001521 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001522 // invalidate and recompute the visible regions if needed
1523 flags |= eVisibleRegion;
1524 this->contentDirty = true;
1525
1526 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001527 const uint8_t type = c.active.transform.getType();
1528 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001529 (type >= Transform::SCALE));
1530 }
1531
Dan Stozac8145172016-04-28 16:29:06 -07001532 // If the layer is hidden, signal and clear out all local sync points so
1533 // that transactions for layers depending on this layer's frames becoming
1534 // visible are not blocked
1535 if (c.flags & layer_state_t::eLayerHidden) {
1536 Mutex::Autolock lock(mLocalSyncPointMutex);
1537 for (auto& point : mLocalSyncPoints) {
1538 point->setFrameAvailable();
1539 }
1540 mLocalSyncPoints.clear();
1541 }
1542
Mathias Agopian13127d82013-03-05 17:47:11 -08001543 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001544 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001545 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001546}
1547
Pablo Ceballos05289c22016-04-14 15:49:55 -07001548void Layer::commitTransaction(const State& stateToCommit) {
1549 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001550}
1551
Mathias Agopian13127d82013-03-05 17:47:11 -08001552uint32_t Layer::getTransactionFlags(uint32_t flags) {
1553 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1554}
1555
1556uint32_t Layer::setTransactionFlags(uint32_t flags) {
1557 return android_atomic_or(flags, &mTransactionFlags);
1558}
1559
Robert Carr82364e32016-05-15 11:27:47 -07001560bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001561 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001562 return false;
1563 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001564
1565 // We update the requested and active position simultaneously because
1566 // we want to apply the position portion of the transform matrix immediately,
1567 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001568 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001569 if (immediate && !mFreezePositionUpdates) {
1570 mCurrentState.active.transform.set(x, y);
1571 }
1572 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001573
Dan Stoza7dde5992015-05-22 09:51:44 -07001574 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001575 setTransactionFlags(eTransactionNeeded);
1576 return true;
1577}
Robert Carr82364e32016-05-15 11:27:47 -07001578
Mathias Agopian13127d82013-03-05 17:47:11 -08001579bool Layer::setLayer(uint32_t z) {
1580 if (mCurrentState.z == z)
1581 return false;
1582 mCurrentState.sequence++;
1583 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001584 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001585 setTransactionFlags(eTransactionNeeded);
1586 return true;
1587}
1588bool Layer::setSize(uint32_t w, uint32_t h) {
1589 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1590 return false;
1591 mCurrentState.requested.w = w;
1592 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001593 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001594 setTransactionFlags(eTransactionNeeded);
1595 return true;
1596}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001597#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001598bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001599#else
1600bool Layer::setAlpha(uint8_t alpha) {
1601#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001602 if (mCurrentState.alpha == alpha)
1603 return false;
1604 mCurrentState.sequence++;
1605 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001606 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001607 setTransactionFlags(eTransactionNeeded);
1608 return true;
1609}
1610bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1611 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001612 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001613 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001614 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001615 setTransactionFlags(eTransactionNeeded);
1616 return true;
1617}
1618bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001619 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001620 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001621 setTransactionFlags(eTransactionNeeded);
1622 return true;
1623}
1624bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1625 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1626 if (mCurrentState.flags == newFlags)
1627 return false;
1628 mCurrentState.sequence++;
1629 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001630 mCurrentState.mask = mask;
1631 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001632 setTransactionFlags(eTransactionNeeded);
1633 return true;
1634}
Robert Carr99e27f02016-06-16 15:18:02 -07001635
1636bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001637 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001638 return false;
1639 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001640 mCurrentState.requestedCrop = crop;
1641 if (immediate) {
1642 mCurrentState.crop = crop;
1643 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001644 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001645 setTransactionFlags(eTransactionNeeded);
1646 return true;
1647}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001648bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001649 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001650 return false;
1651 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001652 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001653 mCurrentState.modified = true;
1654 setTransactionFlags(eTransactionNeeded);
1655 return true;
1656}
Mathias Agopian13127d82013-03-05 17:47:11 -08001657
Robert Carrc3574f72016-03-24 12:19:32 -07001658bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1659 if (scalingMode == mOverrideScalingMode)
1660 return false;
1661 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001662 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001663 return true;
1664}
1665
1666uint32_t Layer::getEffectiveScalingMode() const {
1667 if (mOverrideScalingMode >= 0) {
1668 return mOverrideScalingMode;
1669 }
1670 return mCurrentScalingMode;
1671}
1672
Mathias Agopian13127d82013-03-05 17:47:11 -08001673bool Layer::setLayerStack(uint32_t layerStack) {
1674 if (mCurrentState.layerStack == layerStack)
1675 return false;
1676 mCurrentState.sequence++;
1677 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001678 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001679 setTransactionFlags(eTransactionNeeded);
1680 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001681}
1682
Dan Stoza7dde5992015-05-22 09:51:44 -07001683void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1684 uint64_t frameNumber) {
1685 mCurrentState.handle = handle;
1686 mCurrentState.frameNumber = frameNumber;
1687 // We don't set eTransactionNeeded, because just receiving a deferral
1688 // request without any other state updates shouldn't actually induce a delay
1689 mCurrentState.modified = true;
1690 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001691 mCurrentState.handle = nullptr;
1692 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001693 mCurrentState.modified = false;
1694}
1695
Dan Stozaee44edd2015-03-23 15:50:23 -07001696void Layer::useSurfaceDamage() {
1697 if (mFlinger->mForceFullDamage) {
1698 surfaceDamageRegion = Region::INVALID_REGION;
1699 } else {
1700 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1701 }
1702}
1703
1704void Layer::useEmptyDamage() {
1705 surfaceDamageRegion.clear();
1706}
1707
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001708// ----------------------------------------------------------------------------
1709// pageflip handling...
1710// ----------------------------------------------------------------------------
1711
Dan Stoza6b9454d2014-11-07 16:00:59 -08001712bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001713 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001714 return true;
1715 }
1716
Dan Stoza6b9454d2014-11-07 16:00:59 -08001717 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001718 if (mQueueItems.empty()) {
1719 return false;
1720 }
1721 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001722 nsecs_t expectedPresent =
1723 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001724
1725 // Ignore timestamps more than a second in the future
1726 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1727 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1728 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1729 expectedPresent);
1730
1731 bool isDue = timestamp < expectedPresent;
1732 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001733}
1734
Brian Andersond6927fb2016-07-23 23:37:30 -07001735bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1736 if (mBufferLatched) {
1737 Mutex::Autolock lock(mFrameEventHistoryMutex);
1738 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1739 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001740 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001741 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001742}
1743
Brian Anderson3d4039d2016-09-23 16:31:30 -07001744bool Layer::onPostComposition(
1745 const std::shared_ptr<FenceTime>& glDoneFence,
1746 const std::shared_ptr<FenceTime>& presentFence,
1747 const std::shared_ptr<FenceTime>& retireFence) {
1748 mAcquireTimeline.updateSignalTimes();
1749 mReleaseTimeline.updateSignalTimes();
1750
Brian Andersond6927fb2016-07-23 23:37:30 -07001751 // mFrameLatencyNeeded is true when a new frame was latched for the
1752 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001753 if (!mFrameLatencyNeeded)
1754 return false;
1755
Fabien Sanglard28e98082016-12-05 10:19:46 -08001756 // Update mFrameEventHistory.
1757 {
1758 Mutex::Autolock lock(mFrameEventHistoryMutex);
1759 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001761 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1762 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001763 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001764
1765 // Update mFrameTracker.
1766 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1767 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1768
Brian Anderson3d4039d2016-09-23 16:31:30 -07001769 std::shared_ptr<FenceTime> frameReadyFence =
1770 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001771 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001772 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001773 } else {
1774 // There was no fence for this frame, so assume that it was ready
1775 // to be presented at the desired present time.
1776 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1777 }
1778
Brian Anderson3d4039d2016-09-23 16:31:30 -07001779 if (presentFence->isValid()) {
1780 mFrameTracker.setActualPresentFence(
1781 std::shared_ptr<FenceTime>(presentFence));
1782 } else if (retireFence->isValid()) {
1783 mFrameTracker.setActualPresentFence(
1784 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001785 } else {
1786 // The HWC doesn't support present fences, so use the refresh
1787 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001788 mFrameTracker.setActualPresentTime(
1789 mFlinger->getHwComposer().getRefreshTimestamp(
1790 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001791 }
1792
1793 mFrameTracker.advanceFrame();
1794 mFrameLatencyNeeded = false;
1795 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001796}
1797
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001798#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001799void Layer::releasePendingBuffer() {
1800 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001801 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001802 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001803 mReleaseTimeline.push(releaseFenceTime);
1804
1805 Mutex::Autolock lock(mFrameEventHistoryMutex);
1806 mFrameEventHistory.addRelease(
1807 mPreviousFrameNumber, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001808}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001809#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001810
Mathias Agopianda27af92012-09-13 18:17:13 -07001811bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001812 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001813#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1815 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001816#else
1817 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1818 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1819#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001820}
1821
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001822bool Layer::allTransactionsSignaled() {
1823 auto headFrameNumber = getHeadFrameNumber();
1824 bool matchingFramesFound = false;
1825 bool allTransactionsApplied = true;
1826 Mutex::Autolock lock(mLocalSyncPointMutex);
1827
1828 for (auto& point : mLocalSyncPoints) {
1829 if (point->getFrameNumber() > headFrameNumber) {
1830 break;
1831 }
1832 matchingFramesFound = true;
1833
1834 if (!point->frameIsAvailable()) {
1835 // We haven't notified the remote layer that the frame for
1836 // this point is available yet. Notify it now, and then
1837 // abort this attempt to latch.
1838 point->setFrameAvailable();
1839 allTransactionsApplied = false;
1840 break;
1841 }
1842
1843 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1844 }
1845 return !matchingFramesFound || allTransactionsApplied;
1846}
1847
Brian Andersond6927fb2016-07-23 23:37:30 -07001848Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001849{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001850 ATRACE_CALL();
1851
Jesse Hall399184a2014-03-03 15:42:54 -08001852 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1853 // mSidebandStreamChanged was true
1854 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07001855 if (mSidebandStream != NULL) {
1856 setTransactionFlags(eTransactionNeeded);
1857 mFlinger->setTransactionFlags(eTraversalNeeded);
1858 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07001859 recomputeVisibleRegions = true;
1860
1861 const State& s(getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001862 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08001863 }
1864
Mathias Agopian4fec8732012-06-29 14:12:52 -07001865 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07001866 if (mQueuedFrames <= 0 && !mAutoRefresh) {
1867 return outDirtyRegion;
1868 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001869
Fabien Sanglard223eb912016-10-13 10:15:06 -07001870 // if we've already called updateTexImage() without going through
1871 // a composition step, we have to skip this layer at this point
1872 // because we cannot call updateTeximage() without a corresponding
1873 // compositionComplete() call.
1874 // we'll trigger an update in onPreComposition().
1875 if (mRefreshPending) {
1876 return outDirtyRegion;
1877 }
1878
1879 // If the head buffer's acquire fence hasn't signaled yet, return and
1880 // try again later
1881 if (!headFenceHasSignaled()) {
1882 mFlinger->signalLayerUpdate();
1883 return outDirtyRegion;
1884 }
1885
1886 // Capture the old state of the layer for comparisons later
1887 const State& s(getDrawingState());
1888 const bool oldOpacity = isOpaque(s);
1889 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1890
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001891 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07001892 mFlinger->signalLayerUpdate();
1893 return outDirtyRegion;
1894 }
1895
1896 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1897 // of the buffer queue isn't modified when the buffer queue is returning
1898 // BufferItem's that weren't actually queued. This can happen in shared
1899 // buffer mode.
1900 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07001901 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1902 getProducerStickyTransform() != 0, mName.string(),
1903 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07001904 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1905 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1906 mLastFrameNumberReceived);
1907 if (updateResult == BufferQueue::PRESENT_LATER) {
1908 // Producer doesn't want buffer to be displayed yet. Signal a
1909 // layer update so we check again at the next opportunity.
1910 mFlinger->signalLayerUpdate();
1911 return outDirtyRegion;
1912 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1913 // If the buffer has been rejected, remove it from the shadow queue
1914 // and return early
1915 if (queuedBuffer) {
1916 Mutex::Autolock lock(mQueueItemLock);
1917 mQueueItems.removeAt(0);
1918 android_atomic_dec(&mQueuedFrames);
1919 }
1920 return outDirtyRegion;
1921 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1922 // This can occur if something goes wrong when trying to create the
1923 // EGLImage for this buffer. If this happens, the buffer has already
1924 // been released, so we need to clean up the queue and bug out
1925 // early.
1926 if (queuedBuffer) {
1927 Mutex::Autolock lock(mQueueItemLock);
1928 mQueueItems.clear();
1929 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07001930 }
1931
Fabien Sanglard223eb912016-10-13 10:15:06 -07001932 // Once we have hit this state, the shadow queue may no longer
1933 // correctly reflect the incoming BufferQueue's contents, so even if
1934 // updateTexImage starts working, the only safe course of action is
1935 // to continue to ignore updates.
1936 mUpdateTexImageFailed = true;
1937
1938 return outDirtyRegion;
1939 }
1940
1941 if (queuedBuffer) {
1942 // Autolock scope
1943 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1944
1945 Mutex::Autolock lock(mQueueItemLock);
1946
1947 // Remove any stale buffers that have been dropped during
1948 // updateTexImage
1949 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1950 mQueueItems.removeAt(0);
1951 android_atomic_dec(&mQueuedFrames);
1952 }
1953
1954 mQueueItems.removeAt(0);
1955 }
1956
1957
1958 // Decrement the queued-frames count. Signal another event if we
1959 // have more frames pending.
1960 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1961 || mAutoRefresh) {
1962 mFlinger->signalLayerUpdate();
1963 }
1964
Fabien Sanglard223eb912016-10-13 10:15:06 -07001965 // update the active buffer
1966 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1967 if (mActiveBuffer == NULL) {
1968 // this can only happen if the very first buffer was rejected.
1969 return outDirtyRegion;
1970 }
1971
Brian Andersond6927fb2016-07-23 23:37:30 -07001972 mBufferLatched = true;
1973 mPreviousFrameNumber = mCurrentFrameNumber;
1974 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1975
1976 {
1977 Mutex::Autolock lock(mFrameEventHistoryMutex);
1978 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
1979#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07001980 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001981 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001982 mReleaseTimeline.push(releaseFenceTime);
1983 mFrameEventHistory.addRelease(
1984 mPreviousFrameNumber, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07001985#endif
1986 }
1987
Fabien Sanglard223eb912016-10-13 10:15:06 -07001988 mRefreshPending = true;
1989 mFrameLatencyNeeded = true;
1990 if (oldActiveBuffer == NULL) {
1991 // the first time we receive a buffer, we need to trigger a
1992 // geometry invalidation.
1993 recomputeVisibleRegions = true;
1994 }
1995
1996 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1997 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1998 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1999 if ((crop != mCurrentCrop) ||
2000 (transform != mCurrentTransform) ||
2001 (scalingMode != mCurrentScalingMode))
2002 {
2003 mCurrentCrop = crop;
2004 mCurrentTransform = transform;
2005 mCurrentScalingMode = scalingMode;
2006 recomputeVisibleRegions = true;
2007 }
2008
2009 if (oldActiveBuffer != NULL) {
2010 uint32_t bufWidth = mActiveBuffer->getWidth();
2011 uint32_t bufHeight = mActiveBuffer->getHeight();
2012 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2013 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002014 recomputeVisibleRegions = true;
2015 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002016 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002017
Fabien Sanglard223eb912016-10-13 10:15:06 -07002018 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2019 if (oldOpacity != isOpaque(s)) {
2020 recomputeVisibleRegions = true;
2021 }
Dan Stozacac35382016-01-27 12:21:06 -08002022
Fabien Sanglard223eb912016-10-13 10:15:06 -07002023 // Remove any sync points corresponding to the buffer which was just
2024 // latched
2025 {
2026 Mutex::Autolock lock(mLocalSyncPointMutex);
2027 auto point = mLocalSyncPoints.begin();
2028 while (point != mLocalSyncPoints.end()) {
2029 if (!(*point)->frameIsAvailable() ||
2030 !(*point)->transactionIsApplied()) {
2031 // This sync point must have been added since we started
2032 // latching. Don't drop it yet.
2033 ++point;
2034 continue;
2035 }
2036
2037 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2038 point = mLocalSyncPoints.erase(point);
2039 } else {
2040 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002041 }
2042 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002043 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002044
2045 // FIXME: postedRegion should be dirty & bounds
2046 Region dirtyRegion(Rect(s.active.w, s.active.h));
2047
2048 // transform the dirty region to window-manager space
2049 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2050
Mathias Agopian4fec8732012-06-29 14:12:52 -07002051 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002052}
2053
Mathias Agopiana67932f2011-04-20 14:20:59 -07002054uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002055{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002056 // TODO: should we do something special if mSecure is set?
2057 if (mProtectedByApp) {
2058 // need a hardware-protected path to external video sink
2059 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002060 }
Riley Andrews03414a12014-07-01 14:22:59 -07002061 if (mPotentialCursor) {
2062 usage |= GraphicBuffer::USAGE_CURSOR;
2063 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002064 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002065 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002066}
2067
Mathias Agopian84300952012-11-21 16:02:13 -08002068void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002069 uint32_t orientation = 0;
2070 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002071 // The transform hint is used to improve performance, but we can
2072 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002073 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002074 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002075 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002076 if (orientation & Transform::ROT_INVALID) {
2077 orientation = 0;
2078 }
2079 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002080 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002081}
2082
Mathias Agopian13127d82013-03-05 17:47:11 -08002083// ----------------------------------------------------------------------------
2084// debugging
2085// ----------------------------------------------------------------------------
2086
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002087void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002088{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002089 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002090
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002091 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002092 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002093 "+ %s %p (%s)\n",
2094 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002095 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002096
Mathias Agopian2ca79392013-04-02 18:30:32 -07002097 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002098 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002099 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002100 sp<Client> client(mClientRef.promote());
2101
Mathias Agopian74d211a2013-04-22 16:55:35 +02002102 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002103 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2104 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002105 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002106#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002108#else
2109 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2110#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002111 " client=%p\n",
Robert Carr3dcabfa2016-03-01 18:36:58 -08002112 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 -07002113 s.crop.left, s.crop.top,
2114 s.crop.right, s.crop.bottom,
2115 s.finalCrop.left, s.finalCrop.top,
2116 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002117 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002118 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002119 s.active.transform[0][0], s.active.transform[0][1],
2120 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002121 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002122
2123 sp<const GraphicBuffer> buf0(mActiveBuffer);
2124 uint32_t w0=0, h0=0, s0=0, f0=0;
2125 if (buf0 != 0) {
2126 w0 = buf0->getWidth();
2127 h0 = buf0->getHeight();
2128 s0 = buf0->getStride();
2129 f0 = buf0->format;
2130 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002131 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002132 " "
2133 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2134 " queued-frames=%d, mRefreshPending=%d\n",
2135 mFormat, w0, h0, s0,f0,
2136 mQueuedFrames, mRefreshPending);
2137
Mathias Agopian13127d82013-03-05 17:47:11 -08002138 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002139 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002140 }
2141}
2142
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002143#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002144void Layer::miniDumpHeader(String8& result) {
2145 result.append("----------------------------------------");
2146 result.append("---------------------------------------\n");
2147 result.append(" Layer name\n");
2148 result.append(" Z | ");
2149 result.append(" Comp Type | ");
2150 result.append(" Disp Frame (LTRB) | ");
2151 result.append(" Source Crop (LTRB)\n");
2152 result.append("----------------------------------------");
2153 result.append("---------------------------------------\n");
2154}
2155
2156void Layer::miniDump(String8& result, int32_t hwcId) const {
2157 if (mHwcLayers.count(hwcId) == 0) {
2158 return;
2159 }
2160
2161 String8 name;
2162 if (mName.length() > 77) {
2163 std::string shortened;
2164 shortened.append(mName.string(), 36);
2165 shortened.append("[...]");
2166 shortened.append(mName.string() + (mName.length() - 36), 36);
2167 name = shortened.c_str();
2168 } else {
2169 name = mName;
2170 }
2171
2172 result.appendFormat(" %s\n", name.string());
2173
2174 const Layer::State& layerState(getDrawingState());
2175 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2176 result.appendFormat(" %10u | ", layerState.z);
2177 result.appendFormat("%10s | ",
2178 to_string(getCompositionType(hwcId)).c_str());
2179 const Rect& frame = hwcInfo.displayFrame;
2180 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2181 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002182 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002183 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2184 crop.right, crop.bottom);
2185
2186 result.append("- - - - - - - - - - - - - - - - - - - - ");
2187 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2188}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002189#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002190
Svetoslavd85084b2014-03-20 10:28:31 -07002191void Layer::dumpFrameStats(String8& result) const {
2192 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002193}
2194
Svetoslavd85084b2014-03-20 10:28:31 -07002195void Layer::clearFrameStats() {
2196 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002197}
2198
Jamie Gennis6547ff42013-07-16 20:12:42 -07002199void Layer::logFrameStats() {
2200 mFrameTracker.logAndResetStats(mName);
2201}
2202
Svetoslavd85084b2014-03-20 10:28:31 -07002203void Layer::getFrameStats(FrameStats* outStats) const {
2204 mFrameTracker.getStats(outStats);
2205}
2206
Brian Andersond6927fb2016-07-23 23:37:30 -07002207void Layer::dumpFrameEvents(String8& result) {
2208 result.appendFormat("- Layer %s (%s, %p)\n",
2209 getName().string(), getTypeId(), this);
2210 Mutex::Autolock lock(mFrameEventHistoryMutex);
2211 mFrameEventHistory.checkFencesForCompletion();
2212 mFrameEventHistory.dump(result);
2213}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002214
Brian Anderson3890c392016-07-25 12:48:08 -07002215void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2216 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002217 Mutex::Autolock lock(mFrameEventHistoryMutex);
2218 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002219 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002220 mFrameEventHistory.addQueue(*newTimestamps);
2221 }
2222
Brian Anderson3890c392016-07-25 12:48:08 -07002223 if (outDelta) {
2224 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002225 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002226}
Dan Stozae77c7662016-05-13 11:37:28 -07002227
2228std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2229 bool forceFlush) {
2230 std::vector<OccupancyTracker::Segment> history;
2231 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2232 &history);
2233 if (result != NO_ERROR) {
2234 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2235 result);
2236 return {};
2237 }
2238 return history;
2239}
2240
Robert Carr367c5682016-06-20 11:55:28 -07002241bool Layer::getTransformToDisplayInverse() const {
2242 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2243}
2244
Mathias Agopian13127d82013-03-05 17:47:11 -08002245// ---------------------------------------------------------------------------
2246
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002247}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002248
2249#if defined(__gl_h_)
2250#error "don't include gl/gl.h in this file"
2251#endif
2252
2253#if defined(__gl2_h_)
2254#error "don't include gl2/gl2.h in this file"
2255#endif