blob: 89f968f6a099eb5f8ad0caca83bafc365dbbc3ae [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),
Dan Stozacac35382016-01-27 12:21:06 -080083 mCurrentFrameNumber(0),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080084 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080085 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080086 mFiltering(false),
87 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070088 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000089#ifndef USE_HWC2
90 mIsGlesComposition(false),
91#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080092 mProtectedByApp(false),
93 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070094 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070095 mPotentialCursor(false),
96 mQueueItemLock(),
97 mQueueItemCondition(),
98 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -070099 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800100 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700101 mAutoRefresh(false),
102 mFreezePositionUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800103{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000104#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800105 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000106#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800107
Mathias Agopiana67932f2011-04-20 14:20:59 -0700108 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700109 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700110 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700111
112 uint32_t layerFlags = 0;
113 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800114 layerFlags |= layer_state_t::eLayerHidden;
115 if (flags & ISurfaceComposerClient::eOpaque)
116 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700117 if (flags & ISurfaceComposerClient::eSecure)
118 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700119
120 if (flags & ISurfaceComposerClient::eNonPremultiplied)
121 mPremultipliedAlpha = false;
122
123 mName = name;
124
125 mCurrentState.active.w = w;
126 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800127 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700128 mCurrentState.crop.makeInvalid();
129 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700130 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000131#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800132 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000133#else
134 mCurrentState.alpha = 0xFF;
135#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700136 mCurrentState.layerStack = 0;
137 mCurrentState.flags = layerFlags;
138 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700139 mCurrentState.requested = mCurrentState.active;
140
141 // drawing state & current state are identical
142 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700143
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000144#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800145 const auto& hwc = flinger->getHwComposer();
146 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
147 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000148#else
149 nsecs_t displayPeriod =
150 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
151#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700152 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Jamie Gennise8696a42012-01-15 18:54:57 -0800153}
154
Mathias Agopian3f844832013-08-07 21:24:32 -0700155void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800156 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700157 sp<IGraphicBufferProducer> producer;
158 sp<IGraphicBufferConsumer> consumer;
Irvel468051e2016-06-13 16:44:44 -0700159 BufferQueue::createBufferQueue(&producer, &consumer, nullptr, true);
Dan Stozab9b08832014-03-13 11:55:57 -0700160 mProducer = new MonitoredProducer(producer, mFlinger);
Irvel468051e2016-06-13 16:44:44 -0700161 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800162 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800163 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700164 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800165
Dan Stozac9d97202016-03-03 08:20:27 -0800166#ifndef TARGET_DISABLE_TRIPLE_BUFFERING
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700167 mProducer->setMaxDequeuedBufferCount(2);
Mathias Agopian303d5382012-02-05 01:49:16 -0800168#endif
Andy McFadden69052052012-09-14 16:10:11 -0700169
Mathias Agopian84300952012-11-21 16:02:13 -0800170 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
171 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700172}
173
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700174Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800175 sp<Client> c(mClientRef.promote());
176 if (c != 0) {
177 c->detachLayer(this);
178 }
179
Dan Stozacac35382016-01-27 12:21:06 -0800180 for (auto& point : mRemoteSyncPoints) {
181 point->setTransactionApplied();
182 }
Dan Stozac8145172016-04-28 16:29:06 -0700183 for (auto& point : mLocalSyncPoints) {
184 point->setFrameAvailable();
185 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700186 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700187 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700188}
189
Mathias Agopian13127d82013-03-05 17:47:11 -0800190// ---------------------------------------------------------------------------
191// callbacks
192// ---------------------------------------------------------------------------
193
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000194#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800195void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
196 if (mHwcLayers.empty()) {
197 return;
198 }
199 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
200}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000201#else
202void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
203 HWComposer::HWCLayerInterface* layer) {
204 if (layer) {
205 layer->onDisplayed();
206 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
207 }
208}
209#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800210
Dan Stoza6b9454d2014-11-07 16:00:59 -0800211void Layer::onFrameAvailable(const BufferItem& item) {
212 // Add this buffer from our internal queue tracker
213 { // Autolock scope
214 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700215 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
216 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700217 // Reset the frame number tracker when we receive the first buffer after
218 // a frame number reset
219 if (item.mFrameNumber == 1) {
220 mLastFrameNumberReceived = 0;
221 }
222
223 // Ensure that callbacks are handled in order
224 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
225 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
226 ms2ns(500));
227 if (result != NO_ERROR) {
228 ALOGE("[%s] Timed out waiting on callback", mName.string());
229 }
230 }
231
Dan Stoza6b9454d2014-11-07 16:00:59 -0800232 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700233 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700234
235 // Wake up any pending callbacks
236 mLastFrameNumberReceived = item.mFrameNumber;
237 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800238 }
239
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800240 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700241}
242
Dan Stoza6b9454d2014-11-07 16:00:59 -0800243void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700244 { // Autolock scope
245 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700246
Dan Stoza7dde5992015-05-22 09:51:44 -0700247 // Ensure that callbacks are handled in order
248 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
249 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
250 ms2ns(500));
251 if (result != NO_ERROR) {
252 ALOGE("[%s] Timed out waiting on callback", mName.string());
253 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700254 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700255
256 if (mQueueItems.empty()) {
257 ALOGE("Can't replace a frame on an empty queue");
258 return;
259 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700260 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700261
262 // Wake up any pending callbacks
263 mLastFrameNumberReceived = item.mFrameNumber;
264 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700265 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800266}
267
Jesse Hall399184a2014-03-03 15:42:54 -0800268void Layer::onSidebandStreamChanged() {
269 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
270 // mSidebandStreamChanged was false
271 mFlinger->signalLayerUpdate();
272 }
273}
274
Mathias Agopian67106042013-03-14 19:18:13 -0700275// called with SurfaceFlinger::mStateLock from the drawing thread after
276// the layer has been remove from the current state list (and just before
277// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800278void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800279 mSurfaceFlingerConsumer->abandon();
Mathias Agopian48d819a2009-09-10 19:41:18 -0700280}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700281
Mathias Agopian13127d82013-03-05 17:47:11 -0800282// ---------------------------------------------------------------------------
283// set-up
284// ---------------------------------------------------------------------------
285
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700286const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800287 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800288}
289
Mathias Agopianf9d93272009-06-19 17:00:27 -0700290status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291 PixelFormat format, uint32_t flags)
292{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700293 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700294 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700295
296 // never allow a surface larger than what our underlying GL implementation
297 // can handle.
298 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800299 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700300 return BAD_VALUE;
301 }
302
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700303 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700304
Riley Andrews03414a12014-07-01 14:22:59 -0700305 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700306 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700307 mCurrentOpacity = getOpacityForFormat(format);
308
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800309 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
310 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
311 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700312
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800313 return NO_ERROR;
314}
315
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700316sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800317 Mutex::Autolock _l(mLock);
318
319 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700320 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800321
322 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700323
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700324 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800325}
326
Dan Stozab9b08832014-03-13 11:55:57 -0700327sp<IGraphicBufferProducer> Layer::getProducer() const {
328 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700329}
330
Mathias Agopian13127d82013-03-05 17:47:11 -0800331// ---------------------------------------------------------------------------
332// h/w composer set-up
333// ---------------------------------------------------------------------------
334
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800335Rect Layer::getContentCrop() const {
336 // this is the crop rectangle that applies to the buffer
337 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700338 Rect crop;
339 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800340 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700341 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800342 } else if (mActiveBuffer != NULL) {
343 // otherwise we use the whole buffer
344 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700345 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800346 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700347 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700348 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700349 return crop;
350}
351
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700352static Rect reduce(const Rect& win, const Region& exclude) {
353 if (CC_LIKELY(exclude.isEmpty())) {
354 return win;
355 }
356 if (exclude.isRect()) {
357 return win.reduce(exclude.getBounds());
358 }
359 return Region(win).subtract(exclude).getBounds();
360}
361
Mathias Agopian13127d82013-03-05 17:47:11 -0800362Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700363 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700364 return computeBounds(s.activeTransparentRegion);
365}
366
367Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
368 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800369 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700370
371 if (!s.crop.isEmpty()) {
372 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800373 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700374 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700375 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800376}
377
Mathias Agopian6b442672013-07-09 21:24:52 -0700378FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800379 // the content crop is the area of the content that gets scaled to the
380 // layer's size.
Mathias Agopian6b442672013-07-09 21:24:52 -0700381 FloatRect crop(getContentCrop());
Mathias Agopian13127d82013-03-05 17:47:11 -0800382
Robert Carrb5d3d262016-03-25 15:08:13 -0700383 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800384 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700385 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800386
387 // apply the projection's clipping to the window crop in
388 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700389 // if there are no window scaling involved, this operation will map to full
390 // pixels in the buffer.
391 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
392 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700393
394 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700395 if (!s.crop.isEmpty()) {
396 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700397 }
398
Robert Carr3dcabfa2016-03-01 18:36:58 -0800399 activeCrop = s.active.transform.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000400 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
401 activeCrop.clear();
402 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700403 if (!s.finalCrop.isEmpty()) {
404 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000405 activeCrop.clear();
406 }
407 }
Robert Carr3dcabfa2016-03-01 18:36:58 -0800408 activeCrop = s.active.transform.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800409
Michael Lentine28ea2172014-11-19 18:32:37 -0800410 // This needs to be here as transform.transform(Rect) computes the
411 // transformed rect and then takes the bounding box of the result before
412 // returning. This means
413 // transform.inverse().transform(transform.transform(Rect)) != Rect
414 // in which case we need to make sure the final rect is clipped to the
415 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000416 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
417 activeCrop.clear();
418 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800419
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700420 // subtract the transparent region and snap to the bounds
421 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
422
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000423 // Transform the window crop to match the buffer coordinate system,
424 // which means using the inverse of the current transform set on the
425 // SurfaceFlingerConsumer.
426 uint32_t invTransform = mCurrentTransform;
427 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
428 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700429 * the code below applies the primary display's inverse transform to the
430 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000431 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700432 uint32_t invTransformOrient =
433 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000434 // calculate the inverse transform
435 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
436 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
437 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800438 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000439 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700440 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
441 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800442 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000443
444 int winWidth = s.active.w;
445 int winHeight = s.active.h;
446 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
447 // If the activeCrop has been rotate the ends are rotated but not
448 // the space itself so when transforming ends back we can't rely on
449 // a modification of the axes of rotation. To account for this we
450 // need to reorient the inverse rotation in terms of the current
451 // axes of rotation.
452 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
453 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
454 if (is_h_flipped == is_v_flipped) {
455 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
456 NATIVE_WINDOW_TRANSFORM_FLIP_H;
457 }
458 winWidth = s.active.h;
459 winHeight = s.active.w;
460 }
461 const Rect winCrop = activeCrop.transform(
462 invTransform, s.active.w, s.active.h);
463
464 // below, crop is intersected with winCrop expressed in crop's coordinate space
465 float xScale = crop.getWidth() / float(winWidth);
466 float yScale = crop.getHeight() / float(winHeight);
467
468 float insetL = winCrop.left * xScale;
469 float insetT = winCrop.top * yScale;
470 float insetR = (winWidth - winCrop.right ) * xScale;
471 float insetB = (winHeight - winCrop.bottom) * yScale;
472
473 crop.left += insetL;
474 crop.top += insetT;
475 crop.right -= insetR;
476 crop.bottom -= insetB;
477
Mathias Agopian13127d82013-03-05 17:47:11 -0800478 return crop;
479}
480
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000481#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800482void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000483#else
484void Layer::setGeometry(
485 const sp<const DisplayDevice>& hw,
486 HWComposer::HWCLayerInterface& layer)
487#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700488{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000489#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800490 const auto hwcId = displayDevice->getHwcDisplayId();
491 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000492#else
493 layer.setDefaultState();
494#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700495
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700496 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000497#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800498 hwcInfo.forceClientComposition = false;
499
500 if (isSecure() && !displayDevice->isSecure()) {
501 hwcInfo.forceClientComposition = true;
502 }
503
504 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000505#else
506 layer.setSkip(false);
507
508 if (isSecure() && !hw->isSecure()) {
509 layer.setSkip(true);
510 }
511#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700512
Mathias Agopian13127d82013-03-05 17:47:11 -0800513 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700514 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000515#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800516 if (!isOpaque(s) || s.alpha != 1.0f) {
517 auto blendMode = mPremultipliedAlpha ?
518 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
519 auto error = hwcLayer->setBlendMode(blendMode);
520 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
521 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
522 to_string(error).c_str(), static_cast<int32_t>(error));
523 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000524#else
525 if (!isOpaque(s) || s.alpha != 0xFF) {
526 layer.setBlending(mPremultipliedAlpha ?
527 HWC_BLENDING_PREMULT :
528 HWC_BLENDING_COVERAGE);
529 }
530#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800531
532 // apply the layer's transform, followed by the display's global transform
533 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700534 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carrb5d3d262016-03-25 15:08:13 -0700535 if (!s.crop.isEmpty()) {
536 Rect activeCrop(s.crop);
Robert Carr3dcabfa2016-03-01 18:36:58 -0800537 activeCrop = s.active.transform.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000538#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000539 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000540#else
541 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
542#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000543 activeCrop.clear();
544 }
Pablo Ceballos51450032016-08-03 10:20:45 -0700545 activeCrop = s.active.transform.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800546 // This needs to be here as transform.transform(Rect) computes the
547 // transformed rect and then takes the bounding box of the result before
548 // returning. This means
549 // transform.inverse().transform(transform.transform(Rect)) != Rect
550 // in which case we need to make sure the final rect is clipped to the
551 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000552 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
553 activeCrop.clear();
554 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700555 // mark regions outside the crop as transparent
556 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
557 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
558 s.active.w, s.active.h));
559 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
560 activeCrop.left, activeCrop.bottom));
561 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
562 s.active.w, activeCrop.bottom));
563 }
Robert Carr3dcabfa2016-03-01 18:36:58 -0800564 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700565 if (!s.finalCrop.isEmpty()) {
566 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000567 frame.clear();
568 }
569 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000570#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000571 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
572 frame.clear();
573 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800574 const Transform& tr(displayDevice->getTransform());
575 Rect transformedFrame = tr.transform(frame);
576 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700577 if (error != HWC2::Error::None) {
578 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
579 mName.string(), transformedFrame.left, transformedFrame.top,
580 transformedFrame.right, transformedFrame.bottom,
581 to_string(error).c_str(), static_cast<int32_t>(error));
582 } else {
583 hwcInfo.displayFrame = transformedFrame;
584 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800585
586 FloatRect sourceCrop = computeCrop(displayDevice);
587 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700588 if (error != HWC2::Error::None) {
589 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
590 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
591 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
592 static_cast<int32_t>(error));
593 } else {
594 hwcInfo.sourceCrop = sourceCrop;
595 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800596
597 error = hwcLayer->setPlaneAlpha(s.alpha);
598 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
599 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
600 static_cast<int32_t>(error));
601
602 error = hwcLayer->setZOrder(s.z);
603 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
604 mName.string(), s.z, to_string(error).c_str(),
605 static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000606#else
607 if (!frame.intersect(hw->getViewport(), &frame)) {
608 frame.clear();
609 }
610 const Transform& tr(hw->getTransform());
611 layer.setFrame(tr.transform(frame));
612 layer.setCrop(computeCrop(hw));
613 layer.setPlaneAlpha(s.alpha);
614#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800615
Mathias Agopian29a367b2011-07-12 14:51:45 -0700616 /*
617 * Transformations are applied in this order:
618 * 1) buffer orientation/flip/mirror
619 * 2) state transformation (window manager)
620 * 3) layer orientation (screen orientation)
621 * (NOTE: the matrices are multiplied in reverse order)
622 */
623
624 const Transform bufferOrientation(mCurrentTransform);
Robert Carr3dcabfa2016-03-01 18:36:58 -0800625 Transform transform(tr * s.active.transform * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700626
627 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
628 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700629 * the code below applies the primary display's inverse transform to the
630 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700631 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700632 uint32_t invTransform =
633 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700634 // calculate the inverse transform
635 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
636 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
637 NATIVE_WINDOW_TRANSFORM_FLIP_H;
638 }
639 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700640 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700641 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700642
643 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800644 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000645#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800646 if (orientation & Transform::ROT_INVALID) {
647 // we can only handle simple transformation
648 hwcInfo.forceClientComposition = true;
649 } else {
650 auto transform = static_cast<HWC2::Transform>(orientation);
651 auto error = hwcLayer->setTransform(transform);
652 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
653 "%s (%d)", mName.string(), to_string(transform).c_str(),
654 to_string(error).c_str(), static_cast<int32_t>(error));
655 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000656#else
657 if (orientation & Transform::ROT_INVALID) {
658 // we can only handle simple transformation
659 layer.setSkip(true);
660 } else {
661 layer.setTransform(orientation);
662 }
663#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700664}
665
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000666#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667void Layer::forceClientComposition(int32_t hwcId) {
668 if (mHwcLayers.count(hwcId) == 0) {
669 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
670 return;
671 }
672
673 mHwcLayers[hwcId].forceClientComposition = true;
674}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000675#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000677#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800678void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
679 // Apply this display's projection's viewport to the visible region
680 // before giving it to the HWC HAL.
681 const Transform& tr = displayDevice->getTransform();
682 const auto& viewport = displayDevice->getViewport();
683 Region visible = tr.transform(visibleRegion.intersect(viewport));
684 auto hwcId = displayDevice->getHwcDisplayId();
685 auto& hwcLayer = mHwcLayers[hwcId].layer;
686 auto error = hwcLayer->setVisibleRegion(visible);
687 if (error != HWC2::Error::None) {
688 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
689 to_string(error).c_str(), static_cast<int32_t>(error));
690 visible.dump(LOG_TAG);
691 }
692
693 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
694 if (error != HWC2::Error::None) {
695 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
696 to_string(error).c_str(), static_cast<int32_t>(error));
697 surfaceDamageRegion.dump(LOG_TAG);
698 }
699
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700700 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800701 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700702 setCompositionType(hwcId, HWC2::Composition::Sideband);
703 ALOGV("[%s] Requesting Sideband composition", mName.string());
704 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800705 if (error != HWC2::Error::None) {
706 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
707 mName.string(), mSidebandStream->handle(),
708 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800709 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700710 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800711 }
712
Dan Stoza0a21df72016-07-20 12:52:38 -0700713 // Client layers
714 if (mHwcLayers[hwcId].forceClientComposition ||
715 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700716 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800717 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700718 return;
719 }
720
Dan Stoza0a21df72016-07-20 12:52:38 -0700721 // SolidColor layers
722 if (mActiveBuffer == nullptr) {
723 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700724
725 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700726 error = hwcLayer->setColor({0, 0, 0, 255});
727 if (error != HWC2::Error::None) {
728 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
729 to_string(error).c_str(), static_cast<int32_t>(error));
730 }
Dan Stozac6c89542016-07-27 10:16:52 -0700731
732 // Clear out the transform, because it doesn't make sense absent a
733 // source buffer
734 error = hwcLayer->setTransform(HWC2::Transform::None);
735 if (error != HWC2::Error::None) {
736 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
737 to_string(error).c_str(), static_cast<int32_t>(error));
738 }
739
Dan Stoza0a21df72016-07-20 12:52:38 -0700740 return;
741 }
742
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700743 // Device or Cursor layers
744 if (mPotentialCursor) {
745 ALOGV("[%s] Requesting Cursor composition", mName.string());
746 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747 } else {
748 ALOGV("[%s] Requesting Device composition", mName.string());
749 setCompositionType(hwcId, HWC2::Composition::Device);
750 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700751
752 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
753 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
754 if (error != HWC2::Error::None) {
755 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
756 mActiveBuffer->handle, to_string(error).c_str(),
757 static_cast<int32_t>(error));
758 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000760#else
761void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
762 HWComposer::HWCLayerInterface& layer) {
763 // we have to set the visible region on every frame because
764 // we currently free it during onLayerDisplayed(), which is called
765 // after HWComposer::commit() -- every frame.
766 // Apply this display's projection's viewport to the visible region
767 // before giving it to the HWC HAL.
768 const Transform& tr = hw->getTransform();
769 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
770 layer.setVisibleRegionScreen(visible);
771 layer.setSurfaceDamage(surfaceDamageRegion);
772 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700773
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000774 if (mSidebandStream.get()) {
775 layer.setSidebandStream(mSidebandStream);
776 } else {
777 // NOTE: buffer can be NULL if the client never drew into this
778 // layer yet, or if we ran out of memory
779 layer.setBuffer(mActiveBuffer);
780 }
781}
782#endif
783
784#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
786 auto hwcId = displayDevice->getHwcDisplayId();
787 if (mHwcLayers.count(hwcId) == 0 ||
788 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
789 return;
790 }
791
792 // This gives us only the "orientation" component of the transform
793 const State& s(getCurrentState());
794
795 // Apply the layer's transform, followed by the display's global transform
796 // Here we're guaranteed that the layer's transform preserves rects
797 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700798 if (!s.crop.isEmpty()) {
799 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 }
801 // Subtract the transparent region and snap to the bounds
802 Rect bounds = reduce(win, s.activeTransparentRegion);
Dan Stozabaf416d2016-03-10 11:57:08 -0800803 Rect frame(s.active.transform.transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700805 if (!s.finalCrop.isEmpty()) {
806 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000807 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800808 auto& displayTransform(displayDevice->getTransform());
809 auto position = displayTransform.transform(frame);
810
811 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
812 position.top);
813 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
814 "to (%d, %d): %s (%d)", mName.string(), position.left,
815 position.top, to_string(error).c_str(),
816 static_cast<int32_t>(error));
817}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000818#else
819void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
820 HWComposer::HWCLayerInterface& layer) {
821 int fenceFd = -1;
822
823 // TODO: there is a possible optimization here: we only need to set the
824 // acquire fence the first time a new buffer is acquired on EACH display.
825
826 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
827 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
828 if (fence->isValid()) {
829 fenceFd = fence->dup();
830 if (fenceFd == -1) {
831 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
832 }
833 }
834 }
835 layer.setAcquireFenceFd(fenceFd);
836}
837
838Rect Layer::getPosition(
839 const sp<const DisplayDevice>& hw)
840{
841 // this gives us only the "orientation" component of the transform
842 const State& s(getCurrentState());
843
844 // apply the layer's transform, followed by the display's global transform
845 // here we're guaranteed that the layer's transform preserves rects
846 Rect win(s.active.w, s.active.h);
847 if (!s.crop.isEmpty()) {
848 win.intersect(s.crop, &win);
849 }
850 // subtract the transparent region and snap to the bounds
851 Rect bounds = reduce(win, s.activeTransparentRegion);
852 Rect frame(s.active.transform.transform(bounds));
853 frame.intersect(hw->getViewport(), &frame);
854 if (!s.finalCrop.isEmpty()) {
855 frame.intersect(s.finalCrop, &frame);
856 }
857 const Transform& tr(hw->getTransform());
858 return Rect(tr.transform(frame));
859}
860#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700861
Mathias Agopian13127d82013-03-05 17:47:11 -0800862// ---------------------------------------------------------------------------
863// drawing...
864// ---------------------------------------------------------------------------
865
866void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800867 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800868}
869
Dan Stozac7014012014-02-14 15:03:43 -0800870void Layer::draw(const sp<const DisplayDevice>& hw,
871 bool useIdentityTransform) const {
872 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800873}
874
Dan Stozac7014012014-02-14 15:03:43 -0800875void Layer::draw(const sp<const DisplayDevice>& hw) const {
876 onDraw(hw, Region(hw->bounds()), false);
877}
878
879void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
880 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800881{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800882 ATRACE_CALL();
883
Mathias Agopiana67932f2011-04-20 14:20:59 -0700884 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800885 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -0700886 // in fact never been drawn into. This happens frequently with
887 // SurfaceView because the WindowManager can't know when the client
888 // has drawn the first time.
889
890 // If there is nothing under us, we paint the screen in black, otherwise
891 // we just skip this update.
892
893 // figure out if there is something below us
894 Region under;
Mathias Agopianf7ae69d2011-08-23 12:34:29 -0700895 const SurfaceFlinger::LayerVector& drawingLayers(
896 mFlinger->mDrawingState.layersSortedByZ);
Mathias Agopian179169e2010-05-06 20:21:45 -0700897 const size_t count = drawingLayers.size();
898 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800899 const sp<Layer>& layer(drawingLayers[i]);
900 if (layer.get() == static_cast<Layer const*>(this))
Mathias Agopian179169e2010-05-06 20:21:45 -0700901 break;
Mathias Agopian42977342012-08-05 00:40:46 -0700902 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Mathias Agopian179169e2010-05-06 20:21:45 -0700903 }
904 // if not everything below us is covered, we plug the holes!
905 Region holes(clip.subtract(under));
906 if (!holes.isEmpty()) {
Mathias Agopian1b031492012-06-20 17:51:20 -0700907 clearWithOpenGL(hw, holes, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -0700908 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800909 return;
910 }
Mathias Agopiana67932f2011-04-20 14:20:59 -0700911
Andy McFadden97eba892012-12-11 15:21:45 -0800912 // Bind the current buffer to the GL texture, and wait for it to be
913 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800914 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
915 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -0800916 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -0700917 // Go ahead and draw the buffer anyway; no matter what we do the screen
918 // is probably going to have something visibly wrong.
919 }
920
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700921 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
922
Mathias Agopian875d8e12013-06-07 15:35:48 -0700923 RenderEngine& engine(mFlinger->getRenderEngine());
924
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700925 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -0700926 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -0700927 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -0700928
929 // Query the texture matrix given our current filtering mode.
930 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800931 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
932 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -0700933
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700934 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
935
936 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700937 * the code below applies the primary display's inverse transform to
938 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700939 */
940
941 // create a 4x4 transform matrix from the display transform flags
942 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
943 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
944 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
945
946 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -0700947 uint32_t transform =
948 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700949 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
950 tr = tr * rot90;
951 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
952 tr = tr * flipH;
953 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
954 tr = tr * flipV;
955
956 // calculate the inverse
957 tr = inverse(tr);
958
959 // and finally apply it to the original texture matrix
960 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
961 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
962 }
963
Jamie Genniscbb1a952012-05-08 17:05:52 -0700964 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -0700965 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
966 mTexture.setFiltering(useFiltering);
967 mTexture.setMatrix(textureMatrix);
968
969 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -0700970 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -0700971 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700972 }
Dan Stozac7014012014-02-14 15:03:43 -0800973 drawWithOpenGL(hw, clip, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -0700974 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800975}
976
Mathias Agopian13127d82013-03-05 17:47:11 -0800977
Dan Stozac7014012014-02-14 15:03:43 -0800978void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
979 const Region& /* clip */, float red, float green, float blue,
980 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -0800981{
Mathias Agopian19733a32013-08-28 18:13:56 -0700982 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -0800983 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -0700984 engine.setupFillWithColor(red, green, blue, alpha);
985 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -0800986}
987
988void Layer::clearWithOpenGL(
989 const sp<const DisplayDevice>& hw, const Region& clip) const {
990 clearWithOpenGL(hw, clip, 0,0,0,0);
991}
992
Dan Stozac7014012014-02-14 15:03:43 -0800993void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
994 const Region& /* clip */, bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700995 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800996
Dan Stozac7014012014-02-14 15:03:43 -0800997 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800998
Mathias Agopian13127d82013-03-05 17:47:11 -0800999 /*
1000 * NOTE: the way we compute the texture coordinates here produces
1001 * different results than when we take the HWC path -- in the later case
1002 * the "source crop" is rounded to texel boundaries.
1003 * This can produce significantly different results when the texture
1004 * is scaled by a large amount.
1005 *
1006 * The GL code below is more logical (imho), and the difference with
1007 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001008 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001009 * GL composition when a buffer scaling is applied (maybe with some
1010 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1011 * like more of a hack.
1012 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001013 Rect win(computeBounds());
1014
Robert Carrb5d3d262016-03-25 15:08:13 -07001015 if (!s.finalCrop.isEmpty()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001016 win = s.active.transform.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001017 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001018 win.clear();
1019 }
1020 win = s.active.transform.inverse().transform(win);
1021 if (!win.intersect(computeBounds(), &win)) {
1022 win.clear();
1023 }
1024 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001025
Mathias Agopian3f844832013-08-07 21:24:32 -07001026 float left = float(win.left) / float(s.active.w);
1027 float top = float(win.top) / float(s.active.h);
1028 float right = float(win.right) / float(s.active.w);
1029 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001030
Mathias Agopian875d8e12013-06-07 15:35:48 -07001031 // TODO: we probably want to generate the texture coords with the mesh
1032 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001033 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1034 texCoords[0] = vec2(left, 1.0f - top);
1035 texCoords[1] = vec2(left, 1.0f - bottom);
1036 texCoords[2] = vec2(right, 1.0f - bottom);
1037 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001038
Mathias Agopian875d8e12013-06-07 15:35:48 -07001039 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001040 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001041 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001042 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001043}
1044
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001045#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001046void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1047 bool callIntoHwc) {
1048 if (mHwcLayers.count(hwcId) == 0) {
1049 ALOGE("setCompositionType called without a valid HWC layer");
1050 return;
1051 }
1052 auto& hwcInfo = mHwcLayers[hwcId];
1053 auto& hwcLayer = hwcInfo.layer;
1054 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1055 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1056 if (hwcInfo.compositionType != type) {
1057 ALOGV(" actually setting");
1058 hwcInfo.compositionType = type;
1059 if (callIntoHwc) {
1060 auto error = hwcLayer->setCompositionType(type);
1061 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1062 "composition type %s: %s (%d)", mName.string(),
1063 to_string(type).c_str(), to_string(error).c_str(),
1064 static_cast<int32_t>(error));
1065 }
1066 }
1067}
1068
1069HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001070 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1071 // If we're querying the composition type for a display that does not
1072 // have a HWC counterpart, then it will always be Client
1073 return HWC2::Composition::Client;
1074 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001075 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001076 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001077 return HWC2::Composition::Invalid;
1078 }
1079 return mHwcLayers.at(hwcId).compositionType;
1080}
1081
1082void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1083 if (mHwcLayers.count(hwcId) == 0) {
1084 ALOGE("setClearClientTarget called without a valid HWC layer");
1085 return;
1086 }
1087 mHwcLayers[hwcId].clearClientTarget = clear;
1088}
1089
1090bool Layer::getClearClientTarget(int32_t hwcId) const {
1091 if (mHwcLayers.count(hwcId) == 0) {
1092 ALOGE("getClearClientTarget called without a valid HWC layer");
1093 return false;
1094 }
1095 return mHwcLayers.at(hwcId).clearClientTarget;
1096}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001097#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001098
Ruben Brunk1681d952014-06-27 15:51:55 -07001099uint32_t Layer::getProducerStickyTransform() const {
1100 int producerStickyTransform = 0;
1101 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1102 if (ret != OK) {
1103 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1104 strerror(-ret), ret);
1105 return 0;
1106 }
1107 return static_cast<uint32_t>(producerStickyTransform);
1108}
1109
Dan Stozac5da2712016-07-20 15:38:12 -07001110bool Layer::latchUnsignaledBuffers() {
1111 static bool propertyLoaded = false;
1112 static bool latch = false;
1113 static std::mutex mutex;
1114 std::lock_guard<std::mutex> lock(mutex);
1115 if (!propertyLoaded) {
1116 char value[PROPERTY_VALUE_MAX] = {};
1117 property_get("debug.sf.latch_unsignaled", value, "0");
1118 latch = atoi(value);
1119 propertyLoaded = true;
1120 }
1121 return latch;
1122}
1123
Dan Stozacac35382016-01-27 12:21:06 -08001124uint64_t Layer::getHeadFrameNumber() const {
1125 Mutex::Autolock lock(mQueueItemLock);
1126 if (!mQueueItems.empty()) {
1127 return mQueueItems[0].mFrameNumber;
1128 } else {
1129 return mCurrentFrameNumber;
1130 }
1131}
1132
Dan Stoza1ce65812016-06-15 16:26:27 -07001133bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001134#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001135 if (latchUnsignaledBuffers()) {
1136 return true;
1137 }
1138
Dan Stoza1ce65812016-06-15 16:26:27 -07001139 Mutex::Autolock lock(mQueueItemLock);
1140 if (mQueueItems.empty()) {
1141 return true;
1142 }
1143 if (mQueueItems[0].mIsDroppable) {
1144 // Even though this buffer's fence may not have signaled yet, it could
1145 // be replaced by another buffer before it has a chance to, which means
1146 // that it's possible to get into a situation where a buffer is never
1147 // able to be latched. To avoid this, grab this buffer anyway.
1148 return true;
1149 }
1150 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001151#else
1152 return true;
1153#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001154}
1155
Dan Stozacac35382016-01-27 12:21:06 -08001156bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1157 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1158 // Don't bother with a SyncPoint, since we've already latched the
1159 // relevant frame
1160 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001161 }
1162
Dan Stozacac35382016-01-27 12:21:06 -08001163 Mutex::Autolock lock(mLocalSyncPointMutex);
1164 mLocalSyncPoints.push_back(point);
1165 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001166}
1167
Mathias Agopian13127d82013-03-05 17:47:11 -08001168void Layer::setFiltering(bool filtering) {
1169 mFiltering = filtering;
1170}
1171
1172bool Layer::getFiltering() const {
1173 return mFiltering;
1174}
1175
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001176// As documented in libhardware header, formats in the range
1177// 0x100 - 0x1FF are specific to the HAL implementation, and
1178// are known to have no alpha channel
1179// TODO: move definition for device-specific range into
1180// hardware.h, instead of using hard-coded values here.
1181#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1182
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001183bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001184 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1185 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001186 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001187 switch (format) {
1188 case HAL_PIXEL_FORMAT_RGBA_8888:
1189 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001190 case HAL_PIXEL_FORMAT_RGBA_FP16:
Mathias Agopiandd533712013-07-26 15:31:39 -07001191 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001192 }
1193 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001194 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001195}
1196
Mathias Agopian13127d82013-03-05 17:47:11 -08001197// ----------------------------------------------------------------------------
1198// local state
1199// ----------------------------------------------------------------------------
1200
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001201static void boundPoint(vec2* point, const Rect& crop) {
1202 if (point->x < crop.left) {
1203 point->x = crop.left;
1204 }
1205 if (point->x > crop.right) {
1206 point->x = crop.right;
1207 }
1208 if (point->y < crop.top) {
1209 point->y = crop.top;
1210 }
1211 if (point->y > crop.bottom) {
1212 point->y = crop.bottom;
1213 }
1214}
1215
Dan Stozac7014012014-02-14 15:03:43 -08001216void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1217 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001218{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001219 const Layer::State& s(getDrawingState());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001220 const Transform tr(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001221 const uint32_t hw_h = hw->getHeight();
1222 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -07001223 if (!s.crop.isEmpty()) {
1224 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -08001225 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -07001226 // subtract the transparent region and snap to the bounds
Mathias Agopianf3e85d42013-05-10 18:01:12 -07001227 win = reduce(win, s.activeTransparentRegion);
Mathias Agopian3f844832013-08-07 21:24:32 -07001228
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001229 vec2 lt = vec2(win.left, win.top);
1230 vec2 lb = vec2(win.left, win.bottom);
1231 vec2 rb = vec2(win.right, win.bottom);
1232 vec2 rt = vec2(win.right, win.top);
1233
1234 if (!useIdentityTransform) {
1235 lt = s.active.transform.transform(lt);
1236 lb = s.active.transform.transform(lb);
1237 rb = s.active.transform.transform(rb);
1238 rt = s.active.transform.transform(rt);
1239 }
1240
Robert Carrb5d3d262016-03-25 15:08:13 -07001241 if (!s.finalCrop.isEmpty()) {
1242 boundPoint(&lt, s.finalCrop);
1243 boundPoint(&lb, s.finalCrop);
1244 boundPoint(&rb, s.finalCrop);
1245 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001246 }
1247
Mathias Agopianff2ed702013-09-01 21:36:12 -07001248 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001249 position[0] = tr.transform(lt);
1250 position[1] = tr.transform(lb);
1251 position[2] = tr.transform(rb);
1252 position[3] = tr.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001253 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001254 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001255 }
1256}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001257
Andy McFadden4125a4f2014-01-29 17:17:11 -08001258bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001259{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001260 // if we don't have a buffer yet, we're translucent regardless of the
1261 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001262 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001263 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001264 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001265
1266 // if the layer has the opaque flag, then we're always opaque,
1267 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001268 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001269}
1270
Dan Stoza23116082015-06-18 14:58:39 -07001271bool Layer::isSecure() const
1272{
1273 const Layer::State& s(mDrawingState);
1274 return (s.flags & layer_state_t::eLayerSecure);
1275}
1276
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001277bool Layer::isProtected() const
1278{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001279 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001280 return (activeBuffer != 0) &&
1281 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1282}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001283
Mathias Agopian13127d82013-03-05 17:47:11 -08001284bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001285 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001286}
1287
1288bool Layer::isCropped() const {
1289 return !mCurrentCrop.isEmpty();
1290}
1291
1292bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1293 return mNeedsFiltering || hw->needsFiltering();
1294}
1295
1296void Layer::setVisibleRegion(const Region& visibleRegion) {
1297 // always called from main thread
1298 this->visibleRegion = visibleRegion;
1299}
1300
1301void Layer::setCoveredRegion(const Region& coveredRegion) {
1302 // always called from main thread
1303 this->coveredRegion = coveredRegion;
1304}
1305
1306void Layer::setVisibleNonTransparentRegion(const Region&
1307 setVisibleNonTransparentRegion) {
1308 // always called from main thread
1309 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1310}
1311
1312// ----------------------------------------------------------------------------
1313// transaction
1314// ----------------------------------------------------------------------------
1315
Dan Stoza7dde5992015-05-22 09:51:44 -07001316void Layer::pushPendingState() {
1317 if (!mCurrentState.modified) {
1318 return;
1319 }
1320
Dan Stoza7dde5992015-05-22 09:51:44 -07001321 // If this transaction is waiting on the receipt of a frame, generate a sync
1322 // point and send it to the remote layer.
1323 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001324 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1325 sp<Handle> handle = nullptr;
1326 sp<Layer> handleLayer = nullptr;
1327 if (strongBinder != nullptr) {
1328 handle = static_cast<Handle*>(strongBinder.get());
1329 handleLayer = handle->owner.promote();
1330 }
1331 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001332 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1333 // If we can't promote the layer we are intended to wait on,
1334 // then it is expired or otherwise invalid. Allow this transaction
1335 // to be applied as per normal (no synchronization).
1336 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001337 } else {
1338 auto syncPoint = std::make_shared<SyncPoint>(
1339 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001340 if (handleLayer->addSyncPoint(syncPoint)) {
1341 mRemoteSyncPoints.push_back(std::move(syncPoint));
1342 } else {
1343 // We already missed the frame we're supposed to synchronize
1344 // on, so go ahead and apply the state update
1345 mCurrentState.handle = nullptr;
1346 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001347 }
1348
Dan Stoza7dde5992015-05-22 09:51:44 -07001349 // Wake us up to check if the frame has been received
1350 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001351 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001352 }
1353 mPendingStates.push_back(mCurrentState);
1354}
1355
Pablo Ceballos05289c22016-04-14 15:49:55 -07001356void Layer::popPendingState(State* stateToCommit) {
1357 auto oldFlags = stateToCommit->flags;
1358 *stateToCommit = mPendingStates[0];
1359 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1360 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001361
1362 mPendingStates.removeAt(0);
1363}
1364
Pablo Ceballos05289c22016-04-14 15:49:55 -07001365bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001366 bool stateUpdateAvailable = false;
1367 while (!mPendingStates.empty()) {
1368 if (mPendingStates[0].handle != nullptr) {
1369 if (mRemoteSyncPoints.empty()) {
1370 // If we don't have a sync point for this, apply it anyway. It
1371 // will be visually wrong, but it should keep us from getting
1372 // into too much trouble.
1373 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001374 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001375 stateUpdateAvailable = true;
1376 continue;
1377 }
1378
Dan Stozacac35382016-01-27 12:21:06 -08001379 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1380 mPendingStates[0].frameNumber) {
1381 ALOGE("[%s] Unexpected sync point frame number found",
1382 mName.string());
1383
1384 // Signal our end of the sync point and then dispose of it
1385 mRemoteSyncPoints.front()->setTransactionApplied();
1386 mRemoteSyncPoints.pop_front();
1387 continue;
1388 }
1389
Dan Stoza7dde5992015-05-22 09:51:44 -07001390 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1391 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001392 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001393 stateUpdateAvailable = true;
1394
1395 // Signal our end of the sync point and then dispose of it
1396 mRemoteSyncPoints.front()->setTransactionApplied();
1397 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001398 } else {
1399 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001400 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001401 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001402 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001403 stateUpdateAvailable = true;
1404 }
1405 }
1406
1407 // If we still have pending updates, wake SurfaceFlinger back up and point
1408 // it at this layer so we can process them
1409 if (!mPendingStates.empty()) {
1410 setTransactionFlags(eTransactionNeeded);
1411 mFlinger->setTransactionFlags(eTraversalNeeded);
1412 }
1413
1414 mCurrentState.modified = false;
1415 return stateUpdateAvailable;
1416}
1417
1418void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001419 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001420 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001421 Mutex::Autolock lock(mLocalSyncPointMutex);
1422 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001423 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001424 point->setFrameAvailable();
1425 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001426 }
1427}
1428
Mathias Agopian13127d82013-03-05 17:47:11 -08001429uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001430 ATRACE_CALL();
1431
Dan Stoza7dde5992015-05-22 09:51:44 -07001432 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001433 Layer::State c = getCurrentState();
1434 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001435 return 0;
1436 }
1437
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001438 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001439
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001440 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1441 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001442
1443 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001444 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001445 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001446 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001447 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001448 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001449 " drawing={ 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",
Robert Carrc3574f72016-03-24 12:19:32 -07001451 this, getName().string(), mCurrentTransform,
1452 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001453 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001454 c.crop.left,
1455 c.crop.top,
1456 c.crop.right,
1457 c.crop.bottom,
1458 c.crop.getWidth(),
1459 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001460 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001461 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001462 s.crop.left,
1463 s.crop.top,
1464 s.crop.right,
1465 s.crop.bottom,
1466 s.crop.getWidth(),
1467 s.crop.getHeight(),
1468 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001469
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001470 // record the new size, form this point on, when the client request
1471 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001472 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001473 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001474 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001475
Robert Carr82364e32016-05-15 11:27:47 -07001476 const bool resizePending = (c.requested.w != c.active.w) ||
1477 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001478 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001479 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001480 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001481 // if we have a pending resize, unless we are in fixed-size mode.
1482 // the drawing state will be updated only once we receive a buffer
1483 // with the correct size.
1484 //
1485 // in particular, we want to make sure the clip (which is part
1486 // of the geometry state) is latched together with the size but is
1487 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001488 //
1489 // If a sideband stream is attached, however, we want to skip this
1490 // optimization so that transactions aren't missed when a buffer
1491 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001492
1493 flags |= eDontUpdateGeometryState;
1494 }
1495 }
1496
Mathias Agopian13127d82013-03-05 17:47:11 -08001497 // always set active to requested, unless we're asked not to
1498 // this is used by Layer, which special cases resizes.
1499 if (flags & eDontUpdateGeometryState) {
1500 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001501 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001502 if (mFreezePositionUpdates) {
1503 float tx = c.active.transform.tx();
1504 float ty = c.active.transform.ty();
1505 c.active = c.requested;
1506 c.active.transform.set(tx, ty);
1507 editCurrentState.active = c.active;
1508 } else {
1509 editCurrentState.active = editCurrentState.requested;
1510 c.active = c.requested;
1511 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001512 }
1513
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001514 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001515 // invalidate and recompute the visible regions if needed
1516 flags |= Layer::eVisibleRegion;
1517 }
1518
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001519 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001520 // invalidate and recompute the visible regions if needed
1521 flags |= eVisibleRegion;
1522 this->contentDirty = true;
1523
1524 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001525 const uint8_t type = c.active.transform.getType();
1526 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001527 (type >= Transform::SCALE));
1528 }
1529
Dan Stozac8145172016-04-28 16:29:06 -07001530 // If the layer is hidden, signal and clear out all local sync points so
1531 // that transactions for layers depending on this layer's frames becoming
1532 // visible are not blocked
1533 if (c.flags & layer_state_t::eLayerHidden) {
1534 Mutex::Autolock lock(mLocalSyncPointMutex);
1535 for (auto& point : mLocalSyncPoints) {
1536 point->setFrameAvailable();
1537 }
1538 mLocalSyncPoints.clear();
1539 }
1540
Mathias Agopian13127d82013-03-05 17:47:11 -08001541 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001542 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001543 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001544}
1545
Pablo Ceballos05289c22016-04-14 15:49:55 -07001546void Layer::commitTransaction(const State& stateToCommit) {
1547 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001548}
1549
Mathias Agopian13127d82013-03-05 17:47:11 -08001550uint32_t Layer::getTransactionFlags(uint32_t flags) {
1551 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1552}
1553
1554uint32_t Layer::setTransactionFlags(uint32_t flags) {
1555 return android_atomic_or(flags, &mTransactionFlags);
1556}
1557
Robert Carr82364e32016-05-15 11:27:47 -07001558bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001559 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001560 return false;
1561 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001562
1563 // We update the requested and active position simultaneously because
1564 // we want to apply the position portion of the transform matrix immediately,
1565 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001566 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001567 if (immediate && !mFreezePositionUpdates) {
1568 mCurrentState.active.transform.set(x, y);
1569 }
1570 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001571
Dan Stoza7dde5992015-05-22 09:51:44 -07001572 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001573 setTransactionFlags(eTransactionNeeded);
1574 return true;
1575}
Robert Carr82364e32016-05-15 11:27:47 -07001576
Mathias Agopian13127d82013-03-05 17:47:11 -08001577bool Layer::setLayer(uint32_t z) {
1578 if (mCurrentState.z == z)
1579 return false;
1580 mCurrentState.sequence++;
1581 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001582 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001583 setTransactionFlags(eTransactionNeeded);
1584 return true;
1585}
1586bool Layer::setSize(uint32_t w, uint32_t h) {
1587 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1588 return false;
1589 mCurrentState.requested.w = w;
1590 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001591 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001592 setTransactionFlags(eTransactionNeeded);
1593 return true;
1594}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001595#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001596bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001597#else
1598bool Layer::setAlpha(uint8_t alpha) {
1599#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001600 if (mCurrentState.alpha == alpha)
1601 return false;
1602 mCurrentState.sequence++;
1603 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001604 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001605 setTransactionFlags(eTransactionNeeded);
1606 return true;
1607}
1608bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1609 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001610 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001611 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001612 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001613 setTransactionFlags(eTransactionNeeded);
1614 return true;
1615}
1616bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001617 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001618 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001619 setTransactionFlags(eTransactionNeeded);
1620 return true;
1621}
1622bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1623 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1624 if (mCurrentState.flags == newFlags)
1625 return false;
1626 mCurrentState.sequence++;
1627 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001628 mCurrentState.mask = mask;
1629 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001630 setTransactionFlags(eTransactionNeeded);
1631 return true;
1632}
Robert Carr99e27f02016-06-16 15:18:02 -07001633
1634bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001635 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001636 return false;
1637 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001638 mCurrentState.requestedCrop = crop;
1639 if (immediate) {
1640 mCurrentState.crop = crop;
1641 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001642 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001643 setTransactionFlags(eTransactionNeeded);
1644 return true;
1645}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001646bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001647 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001648 return false;
1649 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001650 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001651 mCurrentState.modified = true;
1652 setTransactionFlags(eTransactionNeeded);
1653 return true;
1654}
Mathias Agopian13127d82013-03-05 17:47:11 -08001655
Robert Carrc3574f72016-03-24 12:19:32 -07001656bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1657 if (scalingMode == mOverrideScalingMode)
1658 return false;
1659 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001660 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001661 return true;
1662}
1663
1664uint32_t Layer::getEffectiveScalingMode() const {
1665 if (mOverrideScalingMode >= 0) {
1666 return mOverrideScalingMode;
1667 }
1668 return mCurrentScalingMode;
1669}
1670
Mathias Agopian13127d82013-03-05 17:47:11 -08001671bool Layer::setLayerStack(uint32_t layerStack) {
1672 if (mCurrentState.layerStack == layerStack)
1673 return false;
1674 mCurrentState.sequence++;
1675 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001676 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001677 setTransactionFlags(eTransactionNeeded);
1678 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001679}
1680
Dan Stoza7dde5992015-05-22 09:51:44 -07001681void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1682 uint64_t frameNumber) {
1683 mCurrentState.handle = handle;
1684 mCurrentState.frameNumber = frameNumber;
1685 // We don't set eTransactionNeeded, because just receiving a deferral
1686 // request without any other state updates shouldn't actually induce a delay
1687 mCurrentState.modified = true;
1688 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001689 mCurrentState.handle = nullptr;
1690 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001691 mCurrentState.modified = false;
1692}
1693
Dan Stozaee44edd2015-03-23 15:50:23 -07001694void Layer::useSurfaceDamage() {
1695 if (mFlinger->mForceFullDamage) {
1696 surfaceDamageRegion = Region::INVALID_REGION;
1697 } else {
1698 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1699 }
1700}
1701
1702void Layer::useEmptyDamage() {
1703 surfaceDamageRegion.clear();
1704}
1705
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001706// ----------------------------------------------------------------------------
1707// pageflip handling...
1708// ----------------------------------------------------------------------------
1709
Dan Stoza6b9454d2014-11-07 16:00:59 -08001710bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001711 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001712 return true;
1713 }
1714
Dan Stoza6b9454d2014-11-07 16:00:59 -08001715 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001716 if (mQueueItems.empty()) {
1717 return false;
1718 }
1719 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001720 nsecs_t expectedPresent =
1721 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001722
1723 // Ignore timestamps more than a second in the future
1724 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1725 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1726 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1727 expectedPresent);
1728
1729 bool isDue = timestamp < expectedPresent;
1730 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731}
1732
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001733bool Layer::onPreComposition() {
1734 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001735 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001736}
1737
Dan Stozae77c7662016-05-13 11:37:28 -07001738bool Layer::onPostComposition() {
1739 bool frameLatencyNeeded = mFrameLatencyNeeded;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001740 if (mFrameLatencyNeeded) {
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001741 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
Jamie Gennis82dbc742012-11-08 19:23:28 -08001742 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1743
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001744 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
Jamie Gennis789a6c32013-02-25 13:37:54 -08001745 if (frameReadyFence->isValid()) {
Jamie Gennis82dbc742012-11-08 19:23:28 -08001746 mFrameTracker.setFrameReadyFence(frameReadyFence);
1747 } else {
1748 // There was no fence for this frame, so assume that it was ready
1749 // to be presented at the desired present time.
1750 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1751 }
1752
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001753 const HWComposer& hwc = mFlinger->getHwComposer();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001754#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001755 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001756#else
1757 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1758#endif
Jamie Gennis789a6c32013-02-25 13:37:54 -08001759 if (presentFence->isValid()) {
Jamie Gennis82dbc742012-11-08 19:23:28 -08001760 mFrameTracker.setActualPresentFence(presentFence);
1761 } else {
1762 // The HWC doesn't support present fences, so use the refresh
1763 // timestamp instead.
1764 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1765 mFrameTracker.setActualPresentTime(presentTime);
1766 }
1767
1768 mFrameTracker.advanceFrame();
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001769 mFrameLatencyNeeded = false;
1770 }
Dan Stozae77c7662016-05-13 11:37:28 -07001771 return frameLatencyNeeded;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001772}
1773
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001774#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001775void Layer::releasePendingBuffer() {
1776 mSurfaceFlingerConsumer->releasePendingBuffer();
1777}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001778#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779
Mathias Agopianda27af92012-09-13 18:17:13 -07001780bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001781 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001782#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001783 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1784 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001785#else
1786 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1787 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1788#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001789}
1790
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001791bool Layer::allTransactionsSignaled() {
1792 auto headFrameNumber = getHeadFrameNumber();
1793 bool matchingFramesFound = false;
1794 bool allTransactionsApplied = true;
1795 Mutex::Autolock lock(mLocalSyncPointMutex);
1796
1797 for (auto& point : mLocalSyncPoints) {
1798 if (point->getFrameNumber() > headFrameNumber) {
1799 break;
1800 }
1801 matchingFramesFound = true;
1802
1803 if (!point->frameIsAvailable()) {
1804 // We haven't notified the remote layer that the frame for
1805 // this point is available yet. Notify it now, and then
1806 // abort this attempt to latch.
1807 point->setFrameAvailable();
1808 allTransactionsApplied = false;
1809 break;
1810 }
1811
1812 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1813 }
1814 return !matchingFramesFound || allTransactionsApplied;
1815}
1816
Mathias Agopian4fec8732012-06-29 14:12:52 -07001817Region Layer::latchBuffer(bool& recomputeVisibleRegions)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001818{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001819 ATRACE_CALL();
1820
Jesse Hall399184a2014-03-03 15:42:54 -08001821 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1822 // mSidebandStreamChanged was true
1823 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07001824 if (mSidebandStream != NULL) {
1825 setTransactionFlags(eTransactionNeeded);
1826 mFlinger->setTransactionFlags(eTraversalNeeded);
1827 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07001828 recomputeVisibleRegions = true;
1829
1830 const State& s(getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001831 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08001832 }
1833
Mathias Agopian4fec8732012-06-29 14:12:52 -07001834 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07001835 if (mQueuedFrames <= 0 && !mAutoRefresh) {
1836 return outDirtyRegion;
1837 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001838
Fabien Sanglard223eb912016-10-13 10:15:06 -07001839 // if we've already called updateTexImage() without going through
1840 // a composition step, we have to skip this layer at this point
1841 // because we cannot call updateTeximage() without a corresponding
1842 // compositionComplete() call.
1843 // we'll trigger an update in onPreComposition().
1844 if (mRefreshPending) {
1845 return outDirtyRegion;
1846 }
1847
1848 // If the head buffer's acquire fence hasn't signaled yet, return and
1849 // try again later
1850 if (!headFenceHasSignaled()) {
1851 mFlinger->signalLayerUpdate();
1852 return outDirtyRegion;
1853 }
1854
1855 // Capture the old state of the layer for comparisons later
1856 const State& s(getDrawingState());
1857 const bool oldOpacity = isOpaque(s);
1858 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1859
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001860 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07001861 mFlinger->signalLayerUpdate();
1862 return outDirtyRegion;
1863 }
1864
1865 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1866 // of the buffer queue isn't modified when the buffer queue is returning
1867 // BufferItem's that weren't actually queued. This can happen in shared
1868 // buffer mode.
1869 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07001870 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1871 getProducerStickyTransform() != 0, mName.string(),
1872 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07001873 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1874 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1875 mLastFrameNumberReceived);
1876 if (updateResult == BufferQueue::PRESENT_LATER) {
1877 // Producer doesn't want buffer to be displayed yet. Signal a
1878 // layer update so we check again at the next opportunity.
1879 mFlinger->signalLayerUpdate();
1880 return outDirtyRegion;
1881 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1882 // If the buffer has been rejected, remove it from the shadow queue
1883 // and return early
1884 if (queuedBuffer) {
1885 Mutex::Autolock lock(mQueueItemLock);
1886 mQueueItems.removeAt(0);
1887 android_atomic_dec(&mQueuedFrames);
1888 }
1889 return outDirtyRegion;
1890 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1891 // This can occur if something goes wrong when trying to create the
1892 // EGLImage for this buffer. If this happens, the buffer has already
1893 // been released, so we need to clean up the queue and bug out
1894 // early.
1895 if (queuedBuffer) {
1896 Mutex::Autolock lock(mQueueItemLock);
1897 mQueueItems.clear();
1898 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07001899 }
1900
Fabien Sanglard223eb912016-10-13 10:15:06 -07001901 // Once we have hit this state, the shadow queue may no longer
1902 // correctly reflect the incoming BufferQueue's contents, so even if
1903 // updateTexImage starts working, the only safe course of action is
1904 // to continue to ignore updates.
1905 mUpdateTexImageFailed = true;
1906
1907 return outDirtyRegion;
1908 }
1909
1910 if (queuedBuffer) {
1911 // Autolock scope
1912 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1913
1914 Mutex::Autolock lock(mQueueItemLock);
1915
1916 // Remove any stale buffers that have been dropped during
1917 // updateTexImage
1918 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1919 mQueueItems.removeAt(0);
1920 android_atomic_dec(&mQueuedFrames);
1921 }
1922
1923 mQueueItems.removeAt(0);
1924 }
1925
1926
1927 // Decrement the queued-frames count. Signal another event if we
1928 // have more frames pending.
1929 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1930 || mAutoRefresh) {
1931 mFlinger->signalLayerUpdate();
1932 }
1933
Fabien Sanglard223eb912016-10-13 10:15:06 -07001934 // update the active buffer
1935 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1936 if (mActiveBuffer == NULL) {
1937 // this can only happen if the very first buffer was rejected.
1938 return outDirtyRegion;
1939 }
1940
1941 mRefreshPending = true;
1942 mFrameLatencyNeeded = true;
1943 if (oldActiveBuffer == NULL) {
1944 // the first time we receive a buffer, we need to trigger a
1945 // geometry invalidation.
1946 recomputeVisibleRegions = true;
1947 }
1948
1949 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1950 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1951 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1952 if ((crop != mCurrentCrop) ||
1953 (transform != mCurrentTransform) ||
1954 (scalingMode != mCurrentScalingMode))
1955 {
1956 mCurrentCrop = crop;
1957 mCurrentTransform = transform;
1958 mCurrentScalingMode = scalingMode;
1959 recomputeVisibleRegions = true;
1960 }
1961
1962 if (oldActiveBuffer != NULL) {
1963 uint32_t bufWidth = mActiveBuffer->getWidth();
1964 uint32_t bufHeight = mActiveBuffer->getHeight();
1965 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
1966 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07001967 recomputeVisibleRegions = true;
1968 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07001969 }
Mathias Agopian702634a2012-05-23 17:50:31 -07001970
Fabien Sanglard223eb912016-10-13 10:15:06 -07001971 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
1972 if (oldOpacity != isOpaque(s)) {
1973 recomputeVisibleRegions = true;
1974 }
Dan Stozacac35382016-01-27 12:21:06 -08001975
Fabien Sanglard223eb912016-10-13 10:15:06 -07001976 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
Dan Stozacac35382016-01-27 12:21:06 -08001977
Fabien Sanglard223eb912016-10-13 10:15:06 -07001978 // Remove any sync points corresponding to the buffer which was just
1979 // latched
1980 {
1981 Mutex::Autolock lock(mLocalSyncPointMutex);
1982 auto point = mLocalSyncPoints.begin();
1983 while (point != mLocalSyncPoints.end()) {
1984 if (!(*point)->frameIsAvailable() ||
1985 !(*point)->transactionIsApplied()) {
1986 // This sync point must have been added since we started
1987 // latching. Don't drop it yet.
1988 ++point;
1989 continue;
1990 }
1991
1992 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
1993 point = mLocalSyncPoints.erase(point);
1994 } else {
1995 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08001996 }
1997 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07001998 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07001999
2000 // FIXME: postedRegion should be dirty & bounds
2001 Region dirtyRegion(Rect(s.active.w, s.active.h));
2002
2003 // transform the dirty region to window-manager space
2004 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2005
Mathias Agopian4fec8732012-06-29 14:12:52 -07002006 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002007}
2008
Mathias Agopiana67932f2011-04-20 14:20:59 -07002009uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002010{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002011 // TODO: should we do something special if mSecure is set?
2012 if (mProtectedByApp) {
2013 // need a hardware-protected path to external video sink
2014 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002015 }
Riley Andrews03414a12014-07-01 14:22:59 -07002016 if (mPotentialCursor) {
2017 usage |= GraphicBuffer::USAGE_CURSOR;
2018 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002019 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002020 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002021}
2022
Mathias Agopian84300952012-11-21 16:02:13 -08002023void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002024 uint32_t orientation = 0;
2025 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002026 // The transform hint is used to improve performance, but we can
2027 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002028 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002029 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002030 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002031 if (orientation & Transform::ROT_INVALID) {
2032 orientation = 0;
2033 }
2034 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002035 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002036}
2037
Mathias Agopian13127d82013-03-05 17:47:11 -08002038// ----------------------------------------------------------------------------
2039// debugging
2040// ----------------------------------------------------------------------------
2041
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002042void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002043{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002044 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002045
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002046 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002047 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002048 "+ %s %p (%s)\n",
2049 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002050 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002051
Mathias Agopian2ca79392013-04-02 18:30:32 -07002052 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002053 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002054 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002055 sp<Client> client(mClientRef.promote());
2056
Mathias Agopian74d211a2013-04-22 16:55:35 +02002057 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002058 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2059 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002060 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002061#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002063#else
2064 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2065#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002066 " client=%p\n",
Robert Carr3dcabfa2016-03-01 18:36:58 -08002067 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 -07002068 s.crop.left, s.crop.top,
2069 s.crop.right, s.crop.bottom,
2070 s.finalCrop.left, s.finalCrop.top,
2071 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002072 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002073 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002074 s.active.transform[0][0], s.active.transform[0][1],
2075 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002076 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002077
2078 sp<const GraphicBuffer> buf0(mActiveBuffer);
2079 uint32_t w0=0, h0=0, s0=0, f0=0;
2080 if (buf0 != 0) {
2081 w0 = buf0->getWidth();
2082 h0 = buf0->getHeight();
2083 s0 = buf0->getStride();
2084 f0 = buf0->format;
2085 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002086 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002087 " "
2088 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2089 " queued-frames=%d, mRefreshPending=%d\n",
2090 mFormat, w0, h0, s0,f0,
2091 mQueuedFrames, mRefreshPending);
2092
Mathias Agopian13127d82013-03-05 17:47:11 -08002093 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002094 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002095 }
2096}
2097
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002098#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002099void Layer::miniDumpHeader(String8& result) {
2100 result.append("----------------------------------------");
2101 result.append("---------------------------------------\n");
2102 result.append(" Layer name\n");
2103 result.append(" Z | ");
2104 result.append(" Comp Type | ");
2105 result.append(" Disp Frame (LTRB) | ");
2106 result.append(" Source Crop (LTRB)\n");
2107 result.append("----------------------------------------");
2108 result.append("---------------------------------------\n");
2109}
2110
2111void Layer::miniDump(String8& result, int32_t hwcId) const {
2112 if (mHwcLayers.count(hwcId) == 0) {
2113 return;
2114 }
2115
2116 String8 name;
2117 if (mName.length() > 77) {
2118 std::string shortened;
2119 shortened.append(mName.string(), 36);
2120 shortened.append("[...]");
2121 shortened.append(mName.string() + (mName.length() - 36), 36);
2122 name = shortened.c_str();
2123 } else {
2124 name = mName;
2125 }
2126
2127 result.appendFormat(" %s\n", name.string());
2128
2129 const Layer::State& layerState(getDrawingState());
2130 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2131 result.appendFormat(" %10u | ", layerState.z);
2132 result.appendFormat("%10s | ",
2133 to_string(getCompositionType(hwcId)).c_str());
2134 const Rect& frame = hwcInfo.displayFrame;
2135 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2136 frame.right, frame.bottom);
2137 const FloatRect& crop = hwcInfo.sourceCrop;
2138 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2139 crop.right, crop.bottom);
2140
2141 result.append("- - - - - - - - - - - - - - - - - - - - ");
2142 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2143}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002144#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002145
Svetoslavd85084b2014-03-20 10:28:31 -07002146void Layer::dumpFrameStats(String8& result) const {
2147 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002148}
2149
Svetoslavd85084b2014-03-20 10:28:31 -07002150void Layer::clearFrameStats() {
2151 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002152}
2153
Jamie Gennis6547ff42013-07-16 20:12:42 -07002154void Layer::logFrameStats() {
2155 mFrameTracker.logAndResetStats(mName);
2156}
2157
Svetoslavd85084b2014-03-20 10:28:31 -07002158void Layer::getFrameStats(FrameStats* outStats) const {
2159 mFrameTracker.getStats(outStats);
2160}
2161
Pablo Ceballos40845df2016-01-25 17:41:15 -08002162void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
Brian Andersondbd0ea82016-07-22 09:38:59 -07002163 bool* outIsGlesComposition, nsecs_t* outRequestedPresentTime,
Pablo Ceballos40845df2016-01-25 17:41:15 -08002164 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2165 *outName = mName;
2166 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2167
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002168#ifdef USE_HWC2
Pablo Ceballos40845df2016-01-25 17:41:15 -08002169 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2170 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2171 HWC2::Composition::Client : true;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002172#else
2173 *outIsGlesComposition = mIsGlesComposition;
2174#endif
Brian Andersondbd0ea82016-07-22 09:38:59 -07002175 *outRequestedPresentTime = mSurfaceFlingerConsumer->getTimestamp();
Pablo Ceballos40845df2016-01-25 17:41:15 -08002176 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2177 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2178}
Dan Stozae77c7662016-05-13 11:37:28 -07002179
2180std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2181 bool forceFlush) {
2182 std::vector<OccupancyTracker::Segment> history;
2183 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2184 &history);
2185 if (result != NO_ERROR) {
2186 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2187 result);
2188 return {};
2189 }
2190 return history;
2191}
2192
Robert Carr367c5682016-06-20 11:55:28 -07002193bool Layer::getTransformToDisplayInverse() const {
2194 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2195}
2196
Mathias Agopian13127d82013-03-05 17:47:11 -08002197// ---------------------------------------------------------------------------
2198
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002199}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002200
2201#if defined(__gl_h_)
2202#error "don't include gl/gl.h in this file"
2203#endif
2204
2205#if defined(__gl2_h_)
2206#error "don't include gl2/gl2.h in this file"
2207#endif