blob: 24948c8bfa96455fff4822a2d26c1c5b121e301b [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "Layer"
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <stdlib.h>
23#include <stdint.h>
24#include <sys/types.h>
Mathias Agopian13127d82013-03-05 17:47:11 -080025#include <math.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080026
Mathias Agopiana67932f2011-04-20 14:20:59 -070027#include <cutils/compiler.h>
Mathias Agopian076b1cc2009-04-10 14:24:30 -070028#include <cutils/native_handle.h>
Mathias Agopiana67932f2011-04-20 14:20:59 -070029#include <cutils/properties.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <utils/Errors.h>
32#include <utils/Log.h>
Jesse Hall399184a2014-03-03 15:42:54 -080033#include <utils/NativeHandle.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034#include <utils/StopWatch.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080035#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080036
Mathias Agopian3330b202009-10-05 17:07:12 -070037#include <ui/GraphicBuffer.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080038#include <ui/PixelFormat.h>
Mathias Agopian9cce3252010-02-09 17:46:37 -080039
Dan Stoza6b9454d2014-11-07 16:00:59 -080040#include <gui/BufferItem.h>
Mathias Agopian90ac7992012-02-25 18:48:35 -080041#include <gui/Surface.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080042
43#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020044#include "Colorizer.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070045#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080046#include "Layer.h"
Fabien Sanglard7b1563a2016-10-13 12:05:28 -070047#include "LayerRejecter.h"
Dan Stozab9b08832014-03-13 11:55:57 -070048#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080049#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080050
Mathias Agopian1b031492012-06-20 17:51:20 -070051#include "DisplayHardware/HWComposer.h"
52
Mathias Agopian875d8e12013-06-07 15:35:48 -070053#include "RenderEngine/RenderEngine.h"
54
Dan Stozac5da2712016-07-20 15:38:12 -070055#include <mutex>
56
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080057#define DEBUG_RESIZE 0
58
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059namespace android {
60
61// ---------------------------------------------------------------------------
62
Mathias Agopian13127d82013-03-05 17:47:11 -080063int32_t Layer::sSequence = 1;
64
Mathias Agopian4d9b8222013-03-12 17:11:48 -070065Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
66 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
Mathias Agopian13127d82013-03-05 17:47:11 -080067 : contentDirty(false),
68 sequence(uint32_t(android_atomic_inc(&sSequence))),
69 mFlinger(flinger),
Mathias Agopiana67932f2011-04-20 14:20:59 -070070 mTextureName(-1U),
Mathias Agopian13127d82013-03-05 17:47:11 -080071 mPremultipliedAlpha(true),
72 mName("unnamed"),
Mathias Agopian13127d82013-03-05 17:47:11 -080073 mFormat(PIXEL_FORMAT_NONE),
Mathias Agopian13127d82013-03-05 17:47:11 -080074 mTransactionFlags(0),
Dan Stoza7dde5992015-05-22 09:51:44 -070075 mPendingStateMutex(),
76 mPendingStates(),
Mathias Agopiana67932f2011-04-20 14:20:59 -070077 mQueuedFrames(0),
Jesse Hall399184a2014-03-03 15:42:54 -080078 mSidebandStreamChanged(false),
Mathias Agopiana67932f2011-04-20 14:20:59 -070079 mCurrentTransform(0),
Mathias Agopian933389f2011-07-18 16:15:08 -070080 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
Robert Carrc3574f72016-03-24 12:19:32 -070081 mOverrideScalingMode(-1),
Mathias Agopiana67932f2011-04-20 14:20:59 -070082 mCurrentOpacity(true),
Brian Andersond6927fb2016-07-23 23:37:30 -070083 mBufferLatched(false),
Dan Stozacac35382016-01-27 12:21:06 -080084 mCurrentFrameNumber(0),
Brian Andersond6927fb2016-07-23 23:37:30 -070085 mPreviousFrameNumber(-1U),
Mathias Agopian4d143ee2012-02-23 20:05:39 -080086 mRefreshPending(false),
Mathias Agopian82d7ab62012-01-19 18:34:40 -080087 mFrameLatencyNeeded(false),
Mathias Agopian13127d82013-03-05 17:47:11 -080088 mFiltering(false),
89 mNeedsFiltering(false),
Mathias Agopian5cdc8992013-08-13 20:51:23 -070090 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
Fabien Sanglard9d96de42016-10-11 00:15:18 +000091#ifndef USE_HWC2
92 mIsGlesComposition(false),
93#endif
Mathias Agopian13127d82013-03-05 17:47:11 -080094 mProtectedByApp(false),
95 mHasSurface(false),
Riley Andrews03414a12014-07-01 14:22:59 -070096 mClientRef(client),
Dan Stozaa4650a52015-05-12 12:56:16 -070097 mPotentialCursor(false),
98 mQueueItemLock(),
99 mQueueItemCondition(),
100 mQueueItems(),
Dan Stoza65476f32015-05-14 09:27:25 -0700101 mLastFrameNumberReceived(0),
Pablo Ceballos04839ab2015-11-13 13:39:23 -0800102 mUpdateTexImageFailed(false),
Robert Carr82364e32016-05-15 11:27:47 -0700103 mAutoRefresh(false),
104 mFreezePositionUpdates(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000106#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800107 ALOGV("Creating Layer %s", name.string());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000108#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800109
Mathias Agopiana67932f2011-04-20 14:20:59 -0700110 mCurrentCrop.makeInvalid();
Mathias Agopian3f844832013-08-07 21:24:32 -0700111 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
Mathias Agopian49457ac2013-08-14 18:20:17 -0700112 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700113
114 uint32_t layerFlags = 0;
115 if (flags & ISurfaceComposerClient::eHidden)
Andy McFadden4125a4f2014-01-29 17:17:11 -0800116 layerFlags |= layer_state_t::eLayerHidden;
117 if (flags & ISurfaceComposerClient::eOpaque)
118 layerFlags |= layer_state_t::eLayerOpaque;
Dan Stoza23116082015-06-18 14:58:39 -0700119 if (flags & ISurfaceComposerClient::eSecure)
120 layerFlags |= layer_state_t::eLayerSecure;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700121
122 if (flags & ISurfaceComposerClient::eNonPremultiplied)
123 mPremultipliedAlpha = false;
124
125 mName = name;
126
127 mCurrentState.active.w = w;
128 mCurrentState.active.h = h;
Robert Carr3dcabfa2016-03-01 18:36:58 -0800129 mCurrentState.active.transform.set(0, 0);
Robert Carrb5d3d262016-03-25 15:08:13 -0700130 mCurrentState.crop.makeInvalid();
131 mCurrentState.finalCrop.makeInvalid();
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700132 mCurrentState.z = 0;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000133#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800134 mCurrentState.alpha = 1.0f;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000135#else
136 mCurrentState.alpha = 0xFF;
137#endif
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700138 mCurrentState.layerStack = 0;
139 mCurrentState.flags = layerFlags;
140 mCurrentState.sequence = 0;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700141 mCurrentState.requested = mCurrentState.active;
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700142 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700143
144 // drawing state & current state are identical
145 mDrawingState = mCurrentState;
Jamie Gennis6547ff42013-07-16 20:12:42 -0700146
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000147#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800148 const auto& hwc = flinger->getHwComposer();
149 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
150 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000151#else
152 nsecs_t displayPeriod =
153 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
154#endif
Jamie Gennis6547ff42013-07-16 20:12:42 -0700155 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
Jamie Gennise8696a42012-01-15 18:54:57 -0800156}
157
Mathias Agopian3f844832013-08-07 21:24:32 -0700158void Layer::onFirstRef() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800159 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
Dan Stozab3d0bdf2014-04-07 16:33:59 -0700160 sp<IGraphicBufferProducer> producer;
161 sp<IGraphicBufferConsumer> consumer;
Irvel468051e2016-06-13 16:44:44 -0700162 BufferQueue::createBufferQueue(&producer, &consumer, nullptr, true);
Dan Stozab9b08832014-03-13 11:55:57 -0700163 mProducer = new MonitoredProducer(producer, mFlinger);
Irvel468051e2016-06-13 16:44:44 -0700164 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800165 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Jesse Hall399184a2014-03-03 15:42:54 -0800166 mSurfaceFlingerConsumer->setContentsChangedListener(this);
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700167 mSurfaceFlingerConsumer->setName(mName);
Daniel Lamb2675792012-02-23 14:35:13 -0800168
Dan Stozac9d97202016-03-03 08:20:27 -0800169#ifndef TARGET_DISABLE_TRIPLE_BUFFERING
Pablo Ceballos19e3e062015-08-19 16:16:06 -0700170 mProducer->setMaxDequeuedBufferCount(2);
Mathias Agopian303d5382012-02-05 01:49:16 -0800171#endif
Andy McFadden69052052012-09-14 16:10:11 -0700172
Mathias Agopian84300952012-11-21 16:02:13 -0800173 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
174 updateTransformHint(hw);
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700175}
176
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700177Layer::~Layer() {
Pablo Ceballos8ea4e7b2016-03-03 15:20:02 -0800178 sp<Client> c(mClientRef.promote());
179 if (c != 0) {
180 c->detachLayer(this);
181 }
182
Dan Stozacac35382016-01-27 12:21:06 -0800183 for (auto& point : mRemoteSyncPoints) {
184 point->setTransactionApplied();
185 }
Dan Stozac8145172016-04-28 16:29:06 -0700186 for (auto& point : mLocalSyncPoints) {
187 point->setFrameAvailable();
188 }
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700189 mFlinger->deleteTextureAsync(mTextureName);
Jamie Gennis6547ff42013-07-16 20:12:42 -0700190 mFrameTracker.logAndResetStats(mName);
Mathias Agopian96f08192010-06-02 23:28:45 -0700191}
192
Mathias Agopian13127d82013-03-05 17:47:11 -0800193// ---------------------------------------------------------------------------
194// callbacks
195// ---------------------------------------------------------------------------
196
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000197#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800198void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
199 if (mHwcLayers.empty()) {
200 return;
201 }
202 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
203}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000204#else
205void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
206 HWComposer::HWCLayerInterface* layer) {
207 if (layer) {
208 layer->onDisplayed();
209 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
210 }
211}
212#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800213
Dan Stoza6b9454d2014-11-07 16:00:59 -0800214void Layer::onFrameAvailable(const BufferItem& item) {
215 // Add this buffer from our internal queue tracker
216 { // Autolock scope
217 Mutex::Autolock lock(mQueueItemLock);
Irvel468051e2016-06-13 16:44:44 -0700218 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
219 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
Dan Stozaa4650a52015-05-12 12:56:16 -0700220 // Reset the frame number tracker when we receive the first buffer after
221 // a frame number reset
222 if (item.mFrameNumber == 1) {
223 mLastFrameNumberReceived = 0;
224 }
225
226 // Ensure that callbacks are handled in order
227 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
228 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
229 ms2ns(500));
230 if (result != NO_ERROR) {
231 ALOGE("[%s] Timed out waiting on callback", mName.string());
232 }
233 }
234
Dan Stoza6b9454d2014-11-07 16:00:59 -0800235 mQueueItems.push_back(item);
Dan Stozaecc50402015-04-28 14:42:06 -0700236 android_atomic_inc(&mQueuedFrames);
Dan Stozaa4650a52015-05-12 12:56:16 -0700237
238 // Wake up any pending callbacks
239 mLastFrameNumberReceived = item.mFrameNumber;
240 mQueueItemCondition.broadcast();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800241 }
242
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243 mFlinger->signalLayerUpdate();
Mathias Agopian579b3f82010-06-08 19:54:15 -0700244}
245
Dan Stoza6b9454d2014-11-07 16:00:59 -0800246void Layer::onFrameReplaced(const BufferItem& item) {
Dan Stoza7dde5992015-05-22 09:51:44 -0700247 { // Autolock scope
248 Mutex::Autolock lock(mQueueItemLock);
Dan Stozaa4650a52015-05-12 12:56:16 -0700249
Dan Stoza7dde5992015-05-22 09:51:44 -0700250 // Ensure that callbacks are handled in order
251 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
252 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
253 ms2ns(500));
254 if (result != NO_ERROR) {
255 ALOGE("[%s] Timed out waiting on callback", mName.string());
256 }
Dan Stozaa4650a52015-05-12 12:56:16 -0700257 }
Dan Stoza7dde5992015-05-22 09:51:44 -0700258
259 if (mQueueItems.empty()) {
260 ALOGE("Can't replace a frame on an empty queue");
261 return;
262 }
Pablo Ceballos4d85da42016-04-19 20:11:56 -0700263 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
Dan Stoza7dde5992015-05-22 09:51:44 -0700264
265 // Wake up any pending callbacks
266 mLastFrameNumberReceived = item.mFrameNumber;
267 mQueueItemCondition.broadcast();
Dan Stozaa4650a52015-05-12 12:56:16 -0700268 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800269}
270
Jesse Hall399184a2014-03-03 15:42:54 -0800271void Layer::onSidebandStreamChanged() {
272 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
273 // mSidebandStreamChanged was false
274 mFlinger->signalLayerUpdate();
275 }
276}
277
Mathias Agopian67106042013-03-14 19:18:13 -0700278// called with SurfaceFlinger::mStateLock from the drawing thread after
279// the layer has been remove from the current state list (and just before
280// it's removed from the drawing state list)
Mathias Agopian13127d82013-03-05 17:47:11 -0800281void Layer::onRemoved() {
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800282 mSurfaceFlingerConsumer->abandon();
Mathias Agopian48d819a2009-09-10 19:41:18 -0700283}
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700284
Mathias Agopian13127d82013-03-05 17:47:11 -0800285// ---------------------------------------------------------------------------
286// set-up
287// ---------------------------------------------------------------------------
288
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700289const String8& Layer::getName() const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800290 return mName;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800291}
292
Mathias Agopianf9d93272009-06-19 17:00:27 -0700293status_t Layer::setBuffers( uint32_t w, uint32_t h,
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800294 PixelFormat format, uint32_t flags)
295{
Mathias Agopianca99fb82010-04-14 16:43:44 -0700296 uint32_t const maxSurfaceDims = min(
Mathias Agopiana4912602012-07-12 14:25:33 -0700297 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
Mathias Agopianca99fb82010-04-14 16:43:44 -0700298
299 // never allow a surface larger than what our underlying GL implementation
300 // can handle.
301 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
Mathias Agopianff615cc2012-02-24 14:58:36 -0800302 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700303 return BAD_VALUE;
304 }
305
Mathias Agopiancbb288b2009-09-07 16:32:45 -0700306 mFormat = format;
Mathias Agopianeff062c2010-08-25 14:59:15 -0700307
Riley Andrews03414a12014-07-01 14:22:59 -0700308 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
Mathias Agopian3165cc22012-08-08 19:42:09 -0700309 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
Mathias Agopiana67932f2011-04-20 14:20:59 -0700310 mCurrentOpacity = getOpacityForFormat(format);
311
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800312 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
313 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
314 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
Mathias Agopianca99fb82010-04-14 16:43:44 -0700315
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800316 return NO_ERROR;
317}
318
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700319sp<IBinder> Layer::getHandle() {
Mathias Agopian13127d82013-03-05 17:47:11 -0800320 Mutex::Autolock _l(mLock);
321
322 LOG_ALWAYS_FATAL_IF(mHasSurface,
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700323 "Layer::getHandle() has already been called");
Mathias Agopian13127d82013-03-05 17:47:11 -0800324
325 mHasSurface = true;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700326
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700327 return new Handle(mFlinger, this);
Mathias Agopian13127d82013-03-05 17:47:11 -0800328}
329
Dan Stozab9b08832014-03-13 11:55:57 -0700330sp<IGraphicBufferProducer> Layer::getProducer() const {
331 return mProducer;
Mathias Agopian4d9b8222013-03-12 17:11:48 -0700332}
333
Mathias Agopian13127d82013-03-05 17:47:11 -0800334// ---------------------------------------------------------------------------
335// h/w composer set-up
336// ---------------------------------------------------------------------------
337
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800338Rect Layer::getContentCrop() const {
339 // this is the crop rectangle that applies to the buffer
340 // itself (as opposed to the window)
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700341 Rect crop;
342 if (!mCurrentCrop.isEmpty()) {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800343 // if the buffer crop is defined, we use that
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700344 crop = mCurrentCrop;
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800345 } else if (mActiveBuffer != NULL) {
346 // otherwise we use the whole buffer
347 crop = mActiveBuffer->getBounds();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700348 } else {
Mathias Agopiana8bca8d2013-02-27 22:03:19 -0800349 // if we don't have a buffer yet, we use an empty/invalid crop
Mathias Agopian4fec8732012-06-29 14:12:52 -0700350 crop.makeInvalid();
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700351 }
Jamie Gennisf15a83f2012-05-10 20:43:55 -0700352 return crop;
353}
354
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700355static Rect reduce(const Rect& win, const Region& exclude) {
356 if (CC_LIKELY(exclude.isEmpty())) {
357 return win;
358 }
359 if (exclude.isRect()) {
360 return win.reduce(exclude.getBounds());
361 }
362 return Region(win).subtract(exclude).getBounds();
363}
364
Mathias Agopian13127d82013-03-05 17:47:11 -0800365Rect Layer::computeBounds() const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700366 const Layer::State& s(getDrawingState());
Michael Lentine6c925ed2014-09-26 17:55:01 -0700367 return computeBounds(s.activeTransparentRegion);
368}
369
370Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
371 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800372 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700373
374 if (!s.crop.isEmpty()) {
375 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -0800376 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -0700377 // subtract the transparent region and snap to the bounds
Michael Lentine6c925ed2014-09-26 17:55:01 -0700378 return reduce(win, activeTransparentRegion);
Mathias Agopian13127d82013-03-05 17:47:11 -0800379}
380
Dan Stoza71bded52016-10-19 11:10:33 -0700381gfx::FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
Mathias Agopian13127d82013-03-05 17:47:11 -0800382 // the content crop is the area of the content that gets scaled to the
383 // layer's size.
Dan Stoza71bded52016-10-19 11:10:33 -0700384 gfx::FloatRect crop = getContentCrop().toFloatRect();
Mathias Agopian13127d82013-03-05 17:47:11 -0800385
Robert Carrb5d3d262016-03-25 15:08:13 -0700386 // the crop is the area of the window that gets cropped, but not
Mathias Agopian13127d82013-03-05 17:47:11 -0800387 // scaled in any ways.
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700388 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -0800389
390 // apply the projection's clipping to the window crop in
391 // layerstack space, and convert-back to layer space.
Mathias Agopian6b442672013-07-09 21:24:52 -0700392 // if there are no window scaling involved, this operation will map to full
393 // pixels in the buffer.
394 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
395 // a viewport clipping and a window transform. we should use floating point to fix this.
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700396
397 Rect activeCrop(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700398 if (!s.crop.isEmpty()) {
399 activeCrop = s.crop;
Mathias Agopian0e8f1442013-08-20 21:41:07 -0700400 }
401
Robert Carr3dcabfa2016-03-01 18:36:58 -0800402 activeCrop = s.active.transform.transform(activeCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000403 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
404 activeCrop.clear();
405 }
Robert Carrb5d3d262016-03-25 15:08:13 -0700406 if (!s.finalCrop.isEmpty()) {
407 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000408 activeCrop.clear();
409 }
410 }
Robert Carr3dcabfa2016-03-01 18:36:58 -0800411 activeCrop = s.active.transform.inverse().transform(activeCrop);
Mathias Agopian13127d82013-03-05 17:47:11 -0800412
Michael Lentine28ea2172014-11-19 18:32:37 -0800413 // This needs to be here as transform.transform(Rect) computes the
414 // transformed rect and then takes the bounding box of the result before
415 // returning. This means
416 // transform.inverse().transform(transform.transform(Rect)) != Rect
417 // in which case we need to make sure the final rect is clipped to the
418 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000419 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
420 activeCrop.clear();
421 }
Mathias Agopian13127d82013-03-05 17:47:11 -0800422
Mathias Agopianf3e85d42013-05-10 18:01:12 -0700423 // subtract the transparent region and snap to the bounds
424 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
425
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000426 // Transform the window crop to match the buffer coordinate system,
427 // which means using the inverse of the current transform set on the
428 // SurfaceFlingerConsumer.
429 uint32_t invTransform = mCurrentTransform;
430 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
431 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700432 * the code below applies the primary display's inverse transform to the
433 * buffer
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000434 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700435 uint32_t invTransformOrient =
436 DisplayDevice::getPrimaryDisplayOrientationTransform();
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000437 // calculate the inverse transform
438 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
439 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
440 NATIVE_WINDOW_TRANSFORM_FLIP_H;
Mathias Agopian13127d82013-03-05 17:47:11 -0800441 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000442 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700443 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
444 .getOrientation();
Mathias Agopian13127d82013-03-05 17:47:11 -0800445 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000446
447 int winWidth = s.active.w;
448 int winHeight = s.active.h;
449 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
450 // If the activeCrop has been rotate the ends are rotated but not
451 // the space itself so when transforming ends back we can't rely on
452 // a modification of the axes of rotation. To account for this we
453 // need to reorient the inverse rotation in terms of the current
454 // axes of rotation.
455 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
456 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
457 if (is_h_flipped == is_v_flipped) {
458 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
459 NATIVE_WINDOW_TRANSFORM_FLIP_H;
460 }
461 winWidth = s.active.h;
462 winHeight = s.active.w;
463 }
464 const Rect winCrop = activeCrop.transform(
465 invTransform, s.active.w, s.active.h);
466
467 // below, crop is intersected with winCrop expressed in crop's coordinate space
468 float xScale = crop.getWidth() / float(winWidth);
469 float yScale = crop.getHeight() / float(winHeight);
470
471 float insetL = winCrop.left * xScale;
472 float insetT = winCrop.top * yScale;
473 float insetR = (winWidth - winCrop.right ) * xScale;
474 float insetB = (winHeight - winCrop.bottom) * yScale;
475
476 crop.left += insetL;
477 crop.top += insetT;
478 crop.right -= insetR;
479 crop.bottom -= insetB;
480
Mathias Agopian13127d82013-03-05 17:47:11 -0800481 return crop;
482}
483
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000484#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800485void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000486#else
487void Layer::setGeometry(
488 const sp<const DisplayDevice>& hw,
489 HWComposer::HWCLayerInterface& layer)
490#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700491{
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000492#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800493 const auto hwcId = displayDevice->getHwcDisplayId();
494 auto& hwcInfo = mHwcLayers[hwcId];
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000495#else
496 layer.setDefaultState();
497#endif
Mathias Agopiana537c0f2011-08-02 15:51:37 -0700498
Mathias Agopian3e8b8532012-05-13 20:42:01 -0700499 // enable this layer
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000500#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800501 hwcInfo.forceClientComposition = false;
502
503 if (isSecure() && !displayDevice->isSecure()) {
504 hwcInfo.forceClientComposition = true;
505 }
506
507 auto& hwcLayer = hwcInfo.layer;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000508#else
509 layer.setSkip(false);
510
511 if (isSecure() && !hw->isSecure()) {
512 layer.setSkip(true);
513 }
514#endif
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700515
Mathias Agopian13127d82013-03-05 17:47:11 -0800516 // this gives us only the "orientation" component of the transform
Mathias Agopian1eae0ee2013-06-05 16:59:15 -0700517 const State& s(getDrawingState());
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000518#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800519 if (!isOpaque(s) || s.alpha != 1.0f) {
520 auto blendMode = mPremultipliedAlpha ?
521 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
522 auto error = hwcLayer->setBlendMode(blendMode);
523 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
524 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
525 to_string(error).c_str(), static_cast<int32_t>(error));
526 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000527#else
528 if (!isOpaque(s) || s.alpha != 0xFF) {
529 layer.setBlending(mPremultipliedAlpha ?
530 HWC_BLENDING_PREMULT :
531 HWC_BLENDING_COVERAGE);
532 }
533#endif
Mathias Agopian13127d82013-03-05 17:47:11 -0800534
535 // apply the layer's transform, followed by the display's global transform
536 // here we're guaranteed that the layer's transform preserves rects
Michael Lentine6c925ed2014-09-26 17:55:01 -0700537 Region activeTransparentRegion(s.activeTransparentRegion);
Robert Carrb5d3d262016-03-25 15:08:13 -0700538 if (!s.crop.isEmpty()) {
539 Rect activeCrop(s.crop);
Robert Carr3dcabfa2016-03-01 18:36:58 -0800540 activeCrop = s.active.transform.transform(activeCrop);
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000541#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000542 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000543#else
544 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
545#endif
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000546 activeCrop.clear();
547 }
Pablo Ceballos51450032016-08-03 10:20:45 -0700548 activeCrop = s.active.transform.inverse().transform(activeCrop, true);
Michael Lentine28ea2172014-11-19 18:32:37 -0800549 // This needs to be here as transform.transform(Rect) computes the
550 // transformed rect and then takes the bounding box of the result before
551 // returning. This means
552 // transform.inverse().transform(transform.transform(Rect)) != Rect
553 // in which case we need to make sure the final rect is clipped to the
554 // display bounds.
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000555 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
556 activeCrop.clear();
557 }
Michael Lentine6c925ed2014-09-26 17:55:01 -0700558 // mark regions outside the crop as transparent
559 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
560 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
561 s.active.w, s.active.h));
562 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
563 activeCrop.left, activeCrop.bottom));
564 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
565 s.active.w, activeCrop.bottom));
566 }
Robert Carr3dcabfa2016-03-01 18:36:58 -0800567 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
Robert Carrb5d3d262016-03-25 15:08:13 -0700568 if (!s.finalCrop.isEmpty()) {
569 if(!frame.intersect(s.finalCrop, &frame)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000570 frame.clear();
571 }
572 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000573#ifdef USE_HWC2
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000574 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
575 frame.clear();
576 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800577 const Transform& tr(displayDevice->getTransform());
578 Rect transformedFrame = tr.transform(frame);
579 auto error = hwcLayer->setDisplayFrame(transformedFrame);
Dan Stozae22aec72016-08-01 13:20:59 -0700580 if (error != HWC2::Error::None) {
581 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
582 mName.string(), transformedFrame.left, transformedFrame.top,
583 transformedFrame.right, transformedFrame.bottom,
584 to_string(error).c_str(), static_cast<int32_t>(error));
585 } else {
586 hwcInfo.displayFrame = transformedFrame;
587 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588
Dan Stoza71bded52016-10-19 11:10:33 -0700589 gfx::FloatRect sourceCrop = computeCrop(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 error = hwcLayer->setSourceCrop(sourceCrop);
Dan Stozae22aec72016-08-01 13:20:59 -0700591 if (error != HWC2::Error::None) {
592 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
593 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
594 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
595 static_cast<int32_t>(error));
596 } else {
597 hwcInfo.sourceCrop = sourceCrop;
598 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800599
600 error = hwcLayer->setPlaneAlpha(s.alpha);
601 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
602 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
603 static_cast<int32_t>(error));
604
605 error = hwcLayer->setZOrder(s.z);
606 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
607 mName.string(), s.z, to_string(error).c_str(),
608 static_cast<int32_t>(error));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000609#else
610 if (!frame.intersect(hw->getViewport(), &frame)) {
611 frame.clear();
612 }
613 const Transform& tr(hw->getTransform());
614 layer.setFrame(tr.transform(frame));
615 layer.setCrop(computeCrop(hw));
616 layer.setPlaneAlpha(s.alpha);
617#endif
Mathias Agopian9f8386e2013-01-29 18:56:42 -0800618
Mathias Agopian29a367b2011-07-12 14:51:45 -0700619 /*
620 * Transformations are applied in this order:
621 * 1) buffer orientation/flip/mirror
622 * 2) state transformation (window manager)
623 * 3) layer orientation (screen orientation)
624 * (NOTE: the matrices are multiplied in reverse order)
625 */
626
627 const Transform bufferOrientation(mCurrentTransform);
Robert Carr3dcabfa2016-03-01 18:36:58 -0800628 Transform transform(tr * s.active.transform * bufferOrientation);
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700629
630 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
631 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700632 * the code below applies the primary display's inverse transform to the
633 * buffer
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700634 */
Pablo Ceballos021623b2016-04-15 17:31:51 -0700635 uint32_t invTransform =
636 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700637 // calculate the inverse transform
638 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
639 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
640 NATIVE_WINDOW_TRANSFORM_FLIP_H;
641 }
642 // and apply to the current transform
Pablo Ceballos0f5131f2016-05-17 13:34:45 -0700643 transform = Transform(invTransform) * transform;
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700644 }
Mathias Agopian29a367b2011-07-12 14:51:45 -0700645
646 // this gives us only the "orientation" component of the transform
Mathias Agopian13127d82013-03-05 17:47:11 -0800647 const uint32_t orientation = transform.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000648#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649 if (orientation & Transform::ROT_INVALID) {
650 // we can only handle simple transformation
651 hwcInfo.forceClientComposition = true;
652 } else {
653 auto transform = static_cast<HWC2::Transform>(orientation);
654 auto error = hwcLayer->setTransform(transform);
655 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
656 "%s (%d)", mName.string(), to_string(transform).c_str(),
657 to_string(error).c_str(), static_cast<int32_t>(error));
658 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000659#else
660 if (orientation & Transform::ROT_INVALID) {
661 // we can only handle simple transformation
662 layer.setSkip(true);
663 } else {
664 layer.setTransform(orientation);
665 }
666#endif
Mathias Agopiana350ff92010-08-10 17:14:02 -0700667}
668
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000669#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800670void Layer::forceClientComposition(int32_t hwcId) {
671 if (mHwcLayers.count(hwcId) == 0) {
672 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
673 return;
674 }
675
676 mHwcLayers[hwcId].forceClientComposition = true;
677}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000678#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -0800679
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000680#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
682 // Apply this display's projection's viewport to the visible region
683 // before giving it to the HWC HAL.
684 const Transform& tr = displayDevice->getTransform();
685 const auto& viewport = displayDevice->getViewport();
686 Region visible = tr.transform(visibleRegion.intersect(viewport));
687 auto hwcId = displayDevice->getHwcDisplayId();
688 auto& hwcLayer = mHwcLayers[hwcId].layer;
689 auto error = hwcLayer->setVisibleRegion(visible);
690 if (error != HWC2::Error::None) {
691 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
692 to_string(error).c_str(), static_cast<int32_t>(error));
693 visible.dump(LOG_TAG);
694 }
695
696 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
697 if (error != HWC2::Error::None) {
698 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
699 to_string(error).c_str(), static_cast<int32_t>(error));
700 surfaceDamageRegion.dump(LOG_TAG);
701 }
702
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700703 // Sideband layers
Dan Stoza9e56aa02015-11-02 13:00:03 -0800704 if (mSidebandStream.get()) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700705 setCompositionType(hwcId, HWC2::Composition::Sideband);
706 ALOGV("[%s] Requesting Sideband composition", mName.string());
707 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708 if (error != HWC2::Error::None) {
709 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
710 mName.string(), mSidebandStream->handle(),
711 to_string(error).c_str(), static_cast<int32_t>(error));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800712 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700713 return;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800714 }
715
Dan Stoza0a21df72016-07-20 12:52:38 -0700716 // Client layers
717 if (mHwcLayers[hwcId].forceClientComposition ||
718 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700719 ALOGV("[%s] Requesting Client composition", mName.string());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800720 setCompositionType(hwcId, HWC2::Composition::Client);
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700721 return;
722 }
723
Dan Stoza0a21df72016-07-20 12:52:38 -0700724 // SolidColor layers
725 if (mActiveBuffer == nullptr) {
726 setCompositionType(hwcId, HWC2::Composition::SolidColor);
Dan Stozac6c89542016-07-27 10:16:52 -0700727
728 // For now, we only support black for DimLayer
Dan Stoza0a21df72016-07-20 12:52:38 -0700729 error = hwcLayer->setColor({0, 0, 0, 255});
730 if (error != HWC2::Error::None) {
731 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
732 to_string(error).c_str(), static_cast<int32_t>(error));
733 }
Dan Stozac6c89542016-07-27 10:16:52 -0700734
735 // Clear out the transform, because it doesn't make sense absent a
736 // source buffer
737 error = hwcLayer->setTransform(HWC2::Transform::None);
738 if (error != HWC2::Error::None) {
739 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
740 to_string(error).c_str(), static_cast<int32_t>(error));
741 }
742
Dan Stoza0a21df72016-07-20 12:52:38 -0700743 return;
744 }
745
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700746 // Device or Cursor layers
747 if (mPotentialCursor) {
748 ALOGV("[%s] Requesting Cursor composition", mName.string());
749 setCompositionType(hwcId, HWC2::Composition::Cursor);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 } else {
751 ALOGV("[%s] Requesting Device composition", mName.string());
752 setCompositionType(hwcId, HWC2::Composition::Device);
753 }
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700754
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -0700755 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
756 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
757 if (error != HWC2::Error::None) {
758 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
759 mCurrentState.dataSpace, to_string(error).c_str(),
760 static_cast<int32_t>(error));
761 }
762
Dan Stoza0f67b3f2016-05-17 10:48:38 -0700763 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
764 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
765 if (error != HWC2::Error::None) {
766 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
767 mActiveBuffer->handle, to_string(error).c_str(),
768 static_cast<int32_t>(error));
769 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000771#else
772void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
773 HWComposer::HWCLayerInterface& layer) {
774 // we have to set the visible region on every frame because
775 // we currently free it during onLayerDisplayed(), which is called
776 // after HWComposer::commit() -- every frame.
777 // Apply this display's projection's viewport to the visible region
778 // before giving it to the HWC HAL.
779 const Transform& tr = hw->getTransform();
780 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
781 layer.setVisibleRegionScreen(visible);
782 layer.setSurfaceDamage(surfaceDamageRegion);
783 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
Dan Stozaee44edd2015-03-23 15:50:23 -0700784
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000785 if (mSidebandStream.get()) {
786 layer.setSidebandStream(mSidebandStream);
787 } else {
788 // NOTE: buffer can be NULL if the client never drew into this
789 // layer yet, or if we ran out of memory
790 layer.setBuffer(mActiveBuffer);
791 }
792}
793#endif
794
795#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -0800796void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
797 auto hwcId = displayDevice->getHwcDisplayId();
798 if (mHwcLayers.count(hwcId) == 0 ||
799 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
800 return;
801 }
802
803 // This gives us only the "orientation" component of the transform
804 const State& s(getCurrentState());
805
806 // Apply the layer's transform, followed by the display's global transform
807 // Here we're guaranteed that the layer's transform preserves rects
808 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -0700809 if (!s.crop.isEmpty()) {
810 win.intersect(s.crop, &win);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800811 }
812 // Subtract the transparent region and snap to the bounds
813 Rect bounds = reduce(win, s.activeTransparentRegion);
Dan Stozabaf416d2016-03-10 11:57:08 -0800814 Rect frame(s.active.transform.transform(bounds));
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 frame.intersect(displayDevice->getViewport(), &frame);
Robert Carrb5d3d262016-03-25 15:08:13 -0700816 if (!s.finalCrop.isEmpty()) {
817 frame.intersect(s.finalCrop, &frame);
Pablo Ceballosacbe6782016-03-04 17:54:21 +0000818 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 auto& displayTransform(displayDevice->getTransform());
820 auto position = displayTransform.transform(frame);
821
822 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
823 position.top);
824 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
825 "to (%d, %d): %s (%d)", mName.string(), position.left,
826 position.top, to_string(error).c_str(),
827 static_cast<int32_t>(error));
828}
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000829#else
830void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
831 HWComposer::HWCLayerInterface& layer) {
832 int fenceFd = -1;
833
834 // TODO: there is a possible optimization here: we only need to set the
835 // acquire fence the first time a new buffer is acquired on EACH display.
836
837 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
838 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
839 if (fence->isValid()) {
840 fenceFd = fence->dup();
841 if (fenceFd == -1) {
842 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
843 }
844 }
845 }
846 layer.setAcquireFenceFd(fenceFd);
847}
848
849Rect Layer::getPosition(
850 const sp<const DisplayDevice>& hw)
851{
852 // this gives us only the "orientation" component of the transform
853 const State& s(getCurrentState());
854
855 // apply the layer's transform, followed by the display's global transform
856 // here we're guaranteed that the layer's transform preserves rects
857 Rect win(s.active.w, s.active.h);
858 if (!s.crop.isEmpty()) {
859 win.intersect(s.crop, &win);
860 }
861 // subtract the transparent region and snap to the bounds
862 Rect bounds = reduce(win, s.activeTransparentRegion);
863 Rect frame(s.active.transform.transform(bounds));
864 frame.intersect(hw->getViewport(), &frame);
865 if (!s.finalCrop.isEmpty()) {
866 frame.intersect(s.finalCrop, &frame);
867 }
868 const Transform& tr(hw->getTransform());
869 return Rect(tr.transform(frame));
870}
871#endif
Riley Andrews03414a12014-07-01 14:22:59 -0700872
Mathias Agopian13127d82013-03-05 17:47:11 -0800873// ---------------------------------------------------------------------------
874// drawing...
875// ---------------------------------------------------------------------------
876
877void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
Dan Stozac7014012014-02-14 15:03:43 -0800878 onDraw(hw, clip, false);
Mathias Agopian13127d82013-03-05 17:47:11 -0800879}
880
Dan Stozac7014012014-02-14 15:03:43 -0800881void Layer::draw(const sp<const DisplayDevice>& hw,
882 bool useIdentityTransform) const {
883 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -0800884}
885
Dan Stozac7014012014-02-14 15:03:43 -0800886void Layer::draw(const sp<const DisplayDevice>& hw) const {
887 onDraw(hw, Region(hw->bounds()), false);
888}
889
890void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
891 bool useIdentityTransform) const
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800892{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800893 ATRACE_CALL();
894
Mathias Agopiana67932f2011-04-20 14:20:59 -0700895 if (CC_UNLIKELY(mActiveBuffer == 0)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800896 // the texture has not been created yet, this Layer has
Mathias Agopian179169e2010-05-06 20:21:45 -0700897 // in fact never been drawn into. This happens frequently with
898 // SurfaceView because the WindowManager can't know when the client
899 // has drawn the first time.
900
901 // If there is nothing under us, we paint the screen in black, otherwise
902 // we just skip this update.
903
904 // figure out if there is something below us
905 Region under;
Mathias Agopianf7ae69d2011-08-23 12:34:29 -0700906 const SurfaceFlinger::LayerVector& drawingLayers(
907 mFlinger->mDrawingState.layersSortedByZ);
Mathias Agopian179169e2010-05-06 20:21:45 -0700908 const size_t count = drawingLayers.size();
909 for (size_t i=0 ; i<count ; ++i) {
Mathias Agopian13127d82013-03-05 17:47:11 -0800910 const sp<Layer>& layer(drawingLayers[i]);
911 if (layer.get() == static_cast<Layer const*>(this))
Mathias Agopian179169e2010-05-06 20:21:45 -0700912 break;
Mathias Agopian42977342012-08-05 00:40:46 -0700913 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
Mathias Agopian179169e2010-05-06 20:21:45 -0700914 }
915 // if not everything below us is covered, we plug the holes!
916 Region holes(clip.subtract(under));
917 if (!holes.isEmpty()) {
Fabien Sanglard17487192016-12-07 13:03:32 -0800918 clearWithOpenGL(hw, 0, 0, 0, 1);
Mathias Agopian179169e2010-05-06 20:21:45 -0700919 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800920 return;
921 }
Mathias Agopiana67932f2011-04-20 14:20:59 -0700922
Andy McFadden97eba892012-12-11 15:21:45 -0800923 // Bind the current buffer to the GL texture, and wait for it to be
924 // ready for us to draw into.
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800925 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
926 if (err != NO_ERROR) {
Andy McFadden97eba892012-12-11 15:21:45 -0800927 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
Jesse Halldc5b4852012-06-29 15:21:18 -0700928 // Go ahead and draw the buffer anyway; no matter what we do the screen
929 // is probably going to have something visibly wrong.
930 }
931
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700932 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
933
Mathias Agopian875d8e12013-06-07 15:35:48 -0700934 RenderEngine& engine(mFlinger->getRenderEngine());
935
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700936 if (!blackOutLayer) {
Jamie Genniscbb1a952012-05-08 17:05:52 -0700937 // TODO: we could be more subtle with isFixedSize()
Mathias Agopianeba8c682012-09-19 23:14:45 -0700938 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
Jamie Genniscbb1a952012-05-08 17:05:52 -0700939
940 // Query the texture matrix given our current filtering mode.
941 float textureMatrix[16];
Andy McFaddenbf974ab2012-12-04 16:51:15 -0800942 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
943 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
Jamie Genniscbb1a952012-05-08 17:05:52 -0700944
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700945 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
946
947 /*
Pablo Ceballos021623b2016-04-15 17:31:51 -0700948 * the code below applies the primary display's inverse transform to
949 * the texture transform
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700950 */
951
952 // create a 4x4 transform matrix from the display transform flags
953 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
954 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
955 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
956
957 mat4 tr;
Pablo Ceballos021623b2016-04-15 17:31:51 -0700958 uint32_t transform =
959 DisplayDevice::getPrimaryDisplayOrientationTransform();
Mathias Agopianc1c05de2013-09-17 23:45:22 -0700960 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
961 tr = tr * rot90;
962 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
963 tr = tr * flipH;
964 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
965 tr = tr * flipV;
966
967 // calculate the inverse
968 tr = inverse(tr);
969
970 // and finally apply it to the original texture matrix
971 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
972 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
973 }
974
Jamie Genniscbb1a952012-05-08 17:05:52 -0700975 // Set things up for texturing.
Mathias Agopian49457ac2013-08-14 18:20:17 -0700976 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
977 mTexture.setFiltering(useFiltering);
978 mTexture.setMatrix(textureMatrix);
979
980 engine.setupLayerTexturing(mTexture);
Mathias Agopiana67932f2011-04-20 14:20:59 -0700981 } else {
Mathias Agopian875d8e12013-06-07 15:35:48 -0700982 engine.setupLayerBlackedOut();
Mathias Agopiana67932f2011-04-20 14:20:59 -0700983 }
Fabien Sanglard85789802016-12-07 13:08:24 -0800984 drawWithOpenGL(hw, useIdentityTransform);
Mathias Agopian875d8e12013-06-07 15:35:48 -0700985 engine.disableTexturing();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800986}
987
Mathias Agopian13127d82013-03-05 17:47:11 -0800988
Dan Stozac7014012014-02-14 15:03:43 -0800989void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard17487192016-12-07 13:03:32 -0800990 float red, float green, float blue,
Dan Stozac7014012014-02-14 15:03:43 -0800991 float alpha) const
Mathias Agopian13127d82013-03-05 17:47:11 -0800992{
Mathias Agopian19733a32013-08-28 18:13:56 -0700993 RenderEngine& engine(mFlinger->getRenderEngine());
Dan Stozac7014012014-02-14 15:03:43 -0800994 computeGeometry(hw, mMesh, false);
Mathias Agopian19733a32013-08-28 18:13:56 -0700995 engine.setupFillWithColor(red, green, blue, alpha);
996 engine.drawMesh(mMesh);
Mathias Agopian13127d82013-03-05 17:47:11 -0800997}
998
999void Layer::clearWithOpenGL(
Fabien Sanglard17487192016-12-07 13:03:32 -08001000 const sp<const DisplayDevice>& hw) const {
1001 clearWithOpenGL(hw, 0,0,0,0);
Mathias Agopian13127d82013-03-05 17:47:11 -08001002}
1003
Dan Stozac7014012014-02-14 15:03:43 -08001004void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
Fabien Sanglard85789802016-12-07 13:08:24 -08001005 bool useIdentityTransform) const {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001006 const State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08001007
Dan Stozac7014012014-02-14 15:03:43 -08001008 computeGeometry(hw, mMesh, useIdentityTransform);
Mathias Agopian13127d82013-03-05 17:47:11 -08001009
Mathias Agopian13127d82013-03-05 17:47:11 -08001010 /*
1011 * NOTE: the way we compute the texture coordinates here produces
1012 * different results than when we take the HWC path -- in the later case
1013 * the "source crop" is rounded to texel boundaries.
1014 * This can produce significantly different results when the texture
1015 * is scaled by a large amount.
1016 *
1017 * The GL code below is more logical (imho), and the difference with
1018 * HWC is due to a limitation of the HWC API to integers -- a question
Mathias Agopianc1c05de2013-09-17 23:45:22 -07001019 * is suspend is whether we should ignore this problem or revert to
Mathias Agopian13127d82013-03-05 17:47:11 -08001020 * GL composition when a buffer scaling is applied (maybe with some
1021 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1022 * like more of a hack.
1023 */
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001024 Rect win(computeBounds());
1025
Robert Carrb5d3d262016-03-25 15:08:13 -07001026 if (!s.finalCrop.isEmpty()) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001027 win = s.active.transform.transform(win);
Robert Carrb5d3d262016-03-25 15:08:13 -07001028 if (!win.intersect(s.finalCrop, &win)) {
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001029 win.clear();
1030 }
1031 win = s.active.transform.inverse().transform(win);
1032 if (!win.intersect(computeBounds(), &win)) {
1033 win.clear();
1034 }
1035 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001036
Mathias Agopian3f844832013-08-07 21:24:32 -07001037 float left = float(win.left) / float(s.active.w);
1038 float top = float(win.top) / float(s.active.h);
1039 float right = float(win.right) / float(s.active.w);
1040 float bottom = float(win.bottom) / float(s.active.h);
Mathias Agopian13127d82013-03-05 17:47:11 -08001041
Mathias Agopian875d8e12013-06-07 15:35:48 -07001042 // TODO: we probably want to generate the texture coords with the mesh
1043 // here we assume that we only have 4 vertices
Mathias Agopianff2ed702013-09-01 21:36:12 -07001044 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1045 texCoords[0] = vec2(left, 1.0f - top);
1046 texCoords[1] = vec2(left, 1.0f - bottom);
1047 texCoords[2] = vec2(right, 1.0f - bottom);
1048 texCoords[3] = vec2(right, 1.0f - top);
Mathias Agopian13127d82013-03-05 17:47:11 -08001049
Mathias Agopian875d8e12013-06-07 15:35:48 -07001050 RenderEngine& engine(mFlinger->getRenderEngine());
Andy McFadden4125a4f2014-01-29 17:17:11 -08001051 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001052 engine.drawMesh(mMesh);
Mathias Agopian875d8e12013-06-07 15:35:48 -07001053 engine.disableBlending();
Mathias Agopian13127d82013-03-05 17:47:11 -08001054}
1055
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001056#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001057void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1058 bool callIntoHwc) {
1059 if (mHwcLayers.count(hwcId) == 0) {
1060 ALOGE("setCompositionType called without a valid HWC layer");
1061 return;
1062 }
1063 auto& hwcInfo = mHwcLayers[hwcId];
1064 auto& hwcLayer = hwcInfo.layer;
1065 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1066 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1067 if (hwcInfo.compositionType != type) {
1068 ALOGV(" actually setting");
1069 hwcInfo.compositionType = type;
1070 if (callIntoHwc) {
1071 auto error = hwcLayer->setCompositionType(type);
1072 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1073 "composition type %s: %s (%d)", mName.string(),
1074 to_string(type).c_str(), to_string(error).c_str(),
1075 static_cast<int32_t>(error));
1076 }
1077 }
1078}
1079
1080HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
Dan Stozaec0f7172016-07-21 11:09:40 -07001081 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1082 // If we're querying the composition type for a display that does not
1083 // have a HWC counterpart, then it will always be Client
1084 return HWC2::Composition::Client;
1085 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001086 if (mHwcLayers.count(hwcId) == 0) {
Dan Stozaec0f7172016-07-21 11:09:40 -07001087 ALOGE("getCompositionType called with an invalid HWC layer");
Dan Stoza9e56aa02015-11-02 13:00:03 -08001088 return HWC2::Composition::Invalid;
1089 }
1090 return mHwcLayers.at(hwcId).compositionType;
1091}
1092
1093void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1094 if (mHwcLayers.count(hwcId) == 0) {
1095 ALOGE("setClearClientTarget called without a valid HWC layer");
1096 return;
1097 }
1098 mHwcLayers[hwcId].clearClientTarget = clear;
1099}
1100
1101bool Layer::getClearClientTarget(int32_t hwcId) const {
1102 if (mHwcLayers.count(hwcId) == 0) {
1103 ALOGE("getClearClientTarget called without a valid HWC layer");
1104 return false;
1105 }
1106 return mHwcLayers.at(hwcId).clearClientTarget;
1107}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001108#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001109
Ruben Brunk1681d952014-06-27 15:51:55 -07001110uint32_t Layer::getProducerStickyTransform() const {
1111 int producerStickyTransform = 0;
1112 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1113 if (ret != OK) {
1114 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1115 strerror(-ret), ret);
1116 return 0;
1117 }
1118 return static_cast<uint32_t>(producerStickyTransform);
1119}
1120
Dan Stozac5da2712016-07-20 15:38:12 -07001121bool Layer::latchUnsignaledBuffers() {
1122 static bool propertyLoaded = false;
1123 static bool latch = false;
1124 static std::mutex mutex;
1125 std::lock_guard<std::mutex> lock(mutex);
1126 if (!propertyLoaded) {
1127 char value[PROPERTY_VALUE_MAX] = {};
1128 property_get("debug.sf.latch_unsignaled", value, "0");
1129 latch = atoi(value);
1130 propertyLoaded = true;
1131 }
1132 return latch;
1133}
1134
Dan Stozacac35382016-01-27 12:21:06 -08001135uint64_t Layer::getHeadFrameNumber() const {
1136 Mutex::Autolock lock(mQueueItemLock);
1137 if (!mQueueItems.empty()) {
1138 return mQueueItems[0].mFrameNumber;
1139 } else {
1140 return mCurrentFrameNumber;
1141 }
1142}
1143
Dan Stoza1ce65812016-06-15 16:26:27 -07001144bool Layer::headFenceHasSignaled() const {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001145#ifdef USE_HWC2
Dan Stozac5da2712016-07-20 15:38:12 -07001146 if (latchUnsignaledBuffers()) {
1147 return true;
1148 }
1149
Dan Stoza1ce65812016-06-15 16:26:27 -07001150 Mutex::Autolock lock(mQueueItemLock);
1151 if (mQueueItems.empty()) {
1152 return true;
1153 }
1154 if (mQueueItems[0].mIsDroppable) {
1155 // Even though this buffer's fence may not have signaled yet, it could
1156 // be replaced by another buffer before it has a chance to, which means
1157 // that it's possible to get into a situation where a buffer is never
1158 // able to be latched. To avoid this, grab this buffer anyway.
1159 return true;
1160 }
1161 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001162#else
1163 return true;
1164#endif
Dan Stoza1ce65812016-06-15 16:26:27 -07001165}
1166
Dan Stozacac35382016-01-27 12:21:06 -08001167bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1168 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1169 // Don't bother with a SyncPoint, since we've already latched the
1170 // relevant frame
1171 return false;
Dan Stoza7dde5992015-05-22 09:51:44 -07001172 }
1173
Dan Stozacac35382016-01-27 12:21:06 -08001174 Mutex::Autolock lock(mLocalSyncPointMutex);
1175 mLocalSyncPoints.push_back(point);
1176 return true;
Dan Stoza7dde5992015-05-22 09:51:44 -07001177}
1178
Mathias Agopian13127d82013-03-05 17:47:11 -08001179void Layer::setFiltering(bool filtering) {
1180 mFiltering = filtering;
1181}
1182
1183bool Layer::getFiltering() const {
1184 return mFiltering;
1185}
1186
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001187// As documented in libhardware header, formats in the range
1188// 0x100 - 0x1FF are specific to the HAL implementation, and
1189// are known to have no alpha channel
1190// TODO: move definition for device-specific range into
1191// hardware.h, instead of using hard-coded values here.
1192#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1193
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001194bool Layer::getOpacityForFormat(uint32_t format) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001195 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1196 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001197 }
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001198 switch (format) {
1199 case HAL_PIXEL_FORMAT_RGBA_8888:
1200 case HAL_PIXEL_FORMAT_BGRA_8888:
Romain Guyff415142016-12-13 16:51:25 -08001201 case HAL_PIXEL_FORMAT_RGBA_FP16:
Mathias Agopiandd533712013-07-26 15:31:39 -07001202 return false;
Mathias Agopian5773d3f2013-07-25 19:24:31 -07001203 }
1204 // in all other case, we have no blending (also for unknown formats)
Mathias Agopiandd533712013-07-26 15:31:39 -07001205 return true;
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001206}
1207
Mathias Agopian13127d82013-03-05 17:47:11 -08001208// ----------------------------------------------------------------------------
1209// local state
1210// ----------------------------------------------------------------------------
1211
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001212static void boundPoint(vec2* point, const Rect& crop) {
1213 if (point->x < crop.left) {
1214 point->x = crop.left;
1215 }
1216 if (point->x > crop.right) {
1217 point->x = crop.right;
1218 }
1219 if (point->y < crop.top) {
1220 point->y = crop.top;
1221 }
1222 if (point->y > crop.bottom) {
1223 point->y = crop.bottom;
1224 }
1225}
1226
Dan Stozac7014012014-02-14 15:03:43 -08001227void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1228 bool useIdentityTransform) const
Mathias Agopian13127d82013-03-05 17:47:11 -08001229{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001230 const Layer::State& s(getDrawingState());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001231 const Transform tr(hw->getTransform());
Mathias Agopian13127d82013-03-05 17:47:11 -08001232 const uint32_t hw_h = hw->getHeight();
1233 Rect win(s.active.w, s.active.h);
Robert Carrb5d3d262016-03-25 15:08:13 -07001234 if (!s.crop.isEmpty()) {
1235 win.intersect(s.crop, &win);
Mathias Agopian13127d82013-03-05 17:47:11 -08001236 }
Mathias Agopian6c7f25a2013-05-09 20:37:10 -07001237 // subtract the transparent region and snap to the bounds
Mathias Agopianf3e85d42013-05-10 18:01:12 -07001238 win = reduce(win, s.activeTransparentRegion);
Mathias Agopian3f844832013-08-07 21:24:32 -07001239
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001240 vec2 lt = vec2(win.left, win.top);
1241 vec2 lb = vec2(win.left, win.bottom);
1242 vec2 rb = vec2(win.right, win.bottom);
1243 vec2 rt = vec2(win.right, win.top);
1244
1245 if (!useIdentityTransform) {
1246 lt = s.active.transform.transform(lt);
1247 lb = s.active.transform.transform(lb);
1248 rb = s.active.transform.transform(rb);
1249 rt = s.active.transform.transform(rt);
1250 }
1251
Robert Carrb5d3d262016-03-25 15:08:13 -07001252 if (!s.finalCrop.isEmpty()) {
1253 boundPoint(&lt, s.finalCrop);
1254 boundPoint(&lb, s.finalCrop);
1255 boundPoint(&rb, s.finalCrop);
1256 boundPoint(&rt, s.finalCrop);
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001257 }
1258
Mathias Agopianff2ed702013-09-01 21:36:12 -07001259 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001260 position[0] = tr.transform(lt);
1261 position[1] = tr.transform(lb);
1262 position[2] = tr.transform(rb);
1263 position[3] = tr.transform(rt);
Mathias Agopian3f844832013-08-07 21:24:32 -07001264 for (size_t i=0 ; i<4 ; i++) {
Mathias Agopian5cdc8992013-08-13 20:51:23 -07001265 position[i].y = hw_h - position[i].y;
Mathias Agopian13127d82013-03-05 17:47:11 -08001266 }
1267}
Eric Hassoldac45e6b2011-02-10 14:41:26 -08001268
Andy McFadden4125a4f2014-01-29 17:17:11 -08001269bool Layer::isOpaque(const Layer::State& s) const
Mathias Agopiana7f66922010-05-26 22:08:52 -07001270{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001271 // if we don't have a buffer yet, we're translucent regardless of the
1272 // layer's opaque flag.
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001273 if (mActiveBuffer == 0) {
Mathias Agopiana67932f2011-04-20 14:20:59 -07001274 return false;
Jamie Gennisdb5230f2011-07-28 14:54:07 -07001275 }
Mathias Agopiana67932f2011-04-20 14:20:59 -07001276
1277 // if the layer has the opaque flag, then we're always opaque,
1278 // otherwise we use the current buffer's format.
Andy McFadden4125a4f2014-01-29 17:17:11 -08001279 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
Mathias Agopiana7f66922010-05-26 22:08:52 -07001280}
1281
Dan Stoza23116082015-06-18 14:58:39 -07001282bool Layer::isSecure() const
1283{
1284 const Layer::State& s(mDrawingState);
1285 return (s.flags & layer_state_t::eLayerSecure);
1286}
1287
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001288bool Layer::isProtected() const
1289{
Mathias Agopiana67932f2011-04-20 14:20:59 -07001290 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
Jamie Gennis7a4d0df2011-03-09 17:05:02 -08001291 return (activeBuffer != 0) &&
1292 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1293}
Mathias Agopianb5b7f262010-05-07 15:58:44 -07001294
Mathias Agopian13127d82013-03-05 17:47:11 -08001295bool Layer::isFixedSize() const {
Robert Carrc3574f72016-03-24 12:19:32 -07001296 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
Mathias Agopian13127d82013-03-05 17:47:11 -08001297}
1298
1299bool Layer::isCropped() const {
1300 return !mCurrentCrop.isEmpty();
1301}
1302
1303bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1304 return mNeedsFiltering || hw->needsFiltering();
1305}
1306
1307void Layer::setVisibleRegion(const Region& visibleRegion) {
1308 // always called from main thread
1309 this->visibleRegion = visibleRegion;
1310}
1311
1312void Layer::setCoveredRegion(const Region& coveredRegion) {
1313 // always called from main thread
1314 this->coveredRegion = coveredRegion;
1315}
1316
1317void Layer::setVisibleNonTransparentRegion(const Region&
1318 setVisibleNonTransparentRegion) {
1319 // always called from main thread
1320 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1321}
1322
1323// ----------------------------------------------------------------------------
1324// transaction
1325// ----------------------------------------------------------------------------
1326
Dan Stoza7dde5992015-05-22 09:51:44 -07001327void Layer::pushPendingState() {
1328 if (!mCurrentState.modified) {
1329 return;
1330 }
1331
Dan Stoza7dde5992015-05-22 09:51:44 -07001332 // If this transaction is waiting on the receipt of a frame, generate a sync
1333 // point and send it to the remote layer.
1334 if (mCurrentState.handle != nullptr) {
Dan Stoza22851c32016-08-09 13:21:03 -07001335 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1336 sp<Handle> handle = nullptr;
1337 sp<Layer> handleLayer = nullptr;
1338 if (strongBinder != nullptr) {
1339 handle = static_cast<Handle*>(strongBinder.get());
1340 handleLayer = handle->owner.promote();
1341 }
1342 if (strongBinder == nullptr || handleLayer == nullptr) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001343 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1344 // If we can't promote the layer we are intended to wait on,
1345 // then it is expired or otherwise invalid. Allow this transaction
1346 // to be applied as per normal (no synchronization).
1347 mCurrentState.handle = nullptr;
Pablo Ceballos3bddd5b2015-11-19 14:39:14 -08001348 } else {
1349 auto syncPoint = std::make_shared<SyncPoint>(
1350 mCurrentState.frameNumber);
Dan Stozacac35382016-01-27 12:21:06 -08001351 if (handleLayer->addSyncPoint(syncPoint)) {
1352 mRemoteSyncPoints.push_back(std::move(syncPoint));
1353 } else {
1354 // We already missed the frame we're supposed to synchronize
1355 // on, so go ahead and apply the state update
1356 mCurrentState.handle = nullptr;
1357 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001358 }
1359
Dan Stoza7dde5992015-05-22 09:51:44 -07001360 // Wake us up to check if the frame has been received
1361 setTransactionFlags(eTransactionNeeded);
Dan Stozaf5702ff2016-11-02 16:27:47 -07001362 mFlinger->setTransactionFlags(eTraversalNeeded);
Dan Stoza7dde5992015-05-22 09:51:44 -07001363 }
1364 mPendingStates.push_back(mCurrentState);
1365}
1366
Pablo Ceballos05289c22016-04-14 15:49:55 -07001367void Layer::popPendingState(State* stateToCommit) {
1368 auto oldFlags = stateToCommit->flags;
1369 *stateToCommit = mPendingStates[0];
1370 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1371 (stateToCommit->flags & stateToCommit->mask);
Dan Stoza7dde5992015-05-22 09:51:44 -07001372
1373 mPendingStates.removeAt(0);
1374}
1375
Pablo Ceballos05289c22016-04-14 15:49:55 -07001376bool Layer::applyPendingStates(State* stateToCommit) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001377 bool stateUpdateAvailable = false;
1378 while (!mPendingStates.empty()) {
1379 if (mPendingStates[0].handle != nullptr) {
1380 if (mRemoteSyncPoints.empty()) {
1381 // If we don't have a sync point for this, apply it anyway. It
1382 // will be visually wrong, but it should keep us from getting
1383 // into too much trouble.
1384 ALOGE("[%s] No local sync point found", mName.string());
Pablo Ceballos05289c22016-04-14 15:49:55 -07001385 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001386 stateUpdateAvailable = true;
1387 continue;
1388 }
1389
Dan Stozacac35382016-01-27 12:21:06 -08001390 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1391 mPendingStates[0].frameNumber) {
1392 ALOGE("[%s] Unexpected sync point frame number found",
1393 mName.string());
1394
1395 // Signal our end of the sync point and then dispose of it
1396 mRemoteSyncPoints.front()->setTransactionApplied();
1397 mRemoteSyncPoints.pop_front();
1398 continue;
1399 }
1400
Dan Stoza7dde5992015-05-22 09:51:44 -07001401 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1402 // Apply the state update
Pablo Ceballos05289c22016-04-14 15:49:55 -07001403 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001404 stateUpdateAvailable = true;
1405
1406 // Signal our end of the sync point and then dispose of it
1407 mRemoteSyncPoints.front()->setTransactionApplied();
1408 mRemoteSyncPoints.pop_front();
Dan Stoza792e5292016-02-11 11:43:58 -08001409 } else {
1410 break;
Dan Stoza7dde5992015-05-22 09:51:44 -07001411 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001412 } else {
Pablo Ceballos05289c22016-04-14 15:49:55 -07001413 popPendingState(stateToCommit);
Dan Stoza7dde5992015-05-22 09:51:44 -07001414 stateUpdateAvailable = true;
1415 }
1416 }
1417
1418 // If we still have pending updates, wake SurfaceFlinger back up and point
1419 // it at this layer so we can process them
1420 if (!mPendingStates.empty()) {
1421 setTransactionFlags(eTransactionNeeded);
1422 mFlinger->setTransactionFlags(eTraversalNeeded);
1423 }
1424
1425 mCurrentState.modified = false;
1426 return stateUpdateAvailable;
1427}
1428
1429void Layer::notifyAvailableFrames() {
Dan Stozacac35382016-01-27 12:21:06 -08001430 auto headFrameNumber = getHeadFrameNumber();
Dan Stoza1ce65812016-06-15 16:26:27 -07001431 bool headFenceSignaled = headFenceHasSignaled();
Dan Stozacac35382016-01-27 12:21:06 -08001432 Mutex::Autolock lock(mLocalSyncPointMutex);
1433 for (auto& point : mLocalSyncPoints) {
Dan Stoza1ce65812016-06-15 16:26:27 -07001434 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
Dan Stozacac35382016-01-27 12:21:06 -08001435 point->setFrameAvailable();
1436 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001437 }
1438}
1439
Mathias Agopian13127d82013-03-05 17:47:11 -08001440uint32_t Layer::doTransaction(uint32_t flags) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001441 ATRACE_CALL();
1442
Dan Stoza7dde5992015-05-22 09:51:44 -07001443 pushPendingState();
Pablo Ceballos05289c22016-04-14 15:49:55 -07001444 Layer::State c = getCurrentState();
1445 if (!applyPendingStates(&c)) {
Dan Stoza7dde5992015-05-22 09:51:44 -07001446 return 0;
1447 }
1448
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001449 const Layer::State& s(getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001450
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001451 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1452 (c.requested.h != s.requested.h);
Mathias Agopiana138f892010-05-21 17:24:35 -07001453
1454 if (sizeChanged) {
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001455 // the size changed, we need to ask our client to request a new buffer
Steve Block9d453682011-12-20 16:23:08 +00001456 ALOGD_IF(DEBUG_RESIZE,
Andy McFadden69052052012-09-14 16:10:11 -07001457 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001458 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001459 " requested={ wh={%4u,%4u} }}\n"
Mathias Agopian419e1962012-05-23 14:34:07 -07001460 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
Robert Carrb5d3d262016-03-25 15:08:13 -07001461 " requested={ wh={%4u,%4u} }}\n",
Robert Carrc3574f72016-03-24 12:19:32 -07001462 this, getName().string(), mCurrentTransform,
1463 getEffectiveScalingMode(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001464 c.active.w, c.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001465 c.crop.left,
1466 c.crop.top,
1467 c.crop.right,
1468 c.crop.bottom,
1469 c.crop.getWidth(),
1470 c.crop.getHeight(),
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001471 c.requested.w, c.requested.h,
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001472 s.active.w, s.active.h,
Robert Carrb5d3d262016-03-25 15:08:13 -07001473 s.crop.left,
1474 s.crop.top,
1475 s.crop.right,
1476 s.crop.bottom,
1477 s.crop.getWidth(),
1478 s.crop.getHeight(),
1479 s.requested.w, s.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001480
Jamie Gennis2a0d5b62011-09-26 16:54:44 -07001481 // record the new size, form this point on, when the client request
1482 // a buffer, it'll get the new size.
Andy McFaddenbf974ab2012-12-04 16:51:15 -08001483 mSurfaceFlingerConsumer->setDefaultBufferSize(
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001484 c.requested.w, c.requested.h);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001485 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07001486
Robert Carr82364e32016-05-15 11:27:47 -07001487 const bool resizePending = (c.requested.w != c.active.w) ||
1488 (c.requested.h != c.active.h);
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001489 if (!isFixedSize()) {
Dan Stoza9e9b0442015-04-22 14:59:08 -07001490 if (resizePending && mSidebandStream == NULL) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001491 // don't let Layer::doTransaction update the drawing state
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001492 // if we have a pending resize, unless we are in fixed-size mode.
1493 // the drawing state will be updated only once we receive a buffer
1494 // with the correct size.
1495 //
1496 // in particular, we want to make sure the clip (which is part
1497 // of the geometry state) is latched together with the size but is
1498 // latched immediately when no resizing is involved.
Dan Stoza9e9b0442015-04-22 14:59:08 -07001499 //
1500 // If a sideband stream is attached, however, we want to skip this
1501 // optimization so that transactions aren't missed when a buffer
1502 // never arrives
Mathias Agopian0cd545f2012-06-07 14:18:55 -07001503
1504 flags |= eDontUpdateGeometryState;
1505 }
1506 }
1507
Mathias Agopian13127d82013-03-05 17:47:11 -08001508 // always set active to requested, unless we're asked not to
1509 // this is used by Layer, which special cases resizes.
1510 if (flags & eDontUpdateGeometryState) {
1511 } else {
Pablo Ceballos7d052572016-06-02 17:46:05 -07001512 Layer::State& editCurrentState(getCurrentState());
Robert Carr82364e32016-05-15 11:27:47 -07001513 if (mFreezePositionUpdates) {
1514 float tx = c.active.transform.tx();
1515 float ty = c.active.transform.ty();
1516 c.active = c.requested;
1517 c.active.transform.set(tx, ty);
1518 editCurrentState.active = c.active;
1519 } else {
1520 editCurrentState.active = editCurrentState.requested;
1521 c.active = c.requested;
1522 }
Mathias Agopian13127d82013-03-05 17:47:11 -08001523 }
1524
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001525 if (s.active != c.active) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001526 // invalidate and recompute the visible regions if needed
1527 flags |= Layer::eVisibleRegion;
1528 }
1529
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001530 if (c.sequence != s.sequence) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001531 // invalidate and recompute the visible regions if needed
1532 flags |= eVisibleRegion;
1533 this->contentDirty = true;
1534
1535 // we may use linear filtering, if the matrix scales us
Robert Carr3dcabfa2016-03-01 18:36:58 -08001536 const uint8_t type = c.active.transform.getType();
1537 mNeedsFiltering = (!c.active.transform.preserveRects() ||
Mathias Agopian13127d82013-03-05 17:47:11 -08001538 (type >= Transform::SCALE));
1539 }
1540
Dan Stozac8145172016-04-28 16:29:06 -07001541 // If the layer is hidden, signal and clear out all local sync points so
1542 // that transactions for layers depending on this layer's frames becoming
1543 // visible are not blocked
1544 if (c.flags & layer_state_t::eLayerHidden) {
1545 Mutex::Autolock lock(mLocalSyncPointMutex);
1546 for (auto& point : mLocalSyncPoints) {
1547 point->setFrameAvailable();
1548 }
1549 mLocalSyncPoints.clear();
1550 }
1551
Mathias Agopian13127d82013-03-05 17:47:11 -08001552 // Commit the transaction
Pablo Ceballos05289c22016-04-14 15:49:55 -07001553 commitTransaction(c);
Mathias Agopian13127d82013-03-05 17:47:11 -08001554 return flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001555}
1556
Pablo Ceballos05289c22016-04-14 15:49:55 -07001557void Layer::commitTransaction(const State& stateToCommit) {
1558 mDrawingState = stateToCommit;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001559}
1560
Mathias Agopian13127d82013-03-05 17:47:11 -08001561uint32_t Layer::getTransactionFlags(uint32_t flags) {
1562 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1563}
1564
1565uint32_t Layer::setTransactionFlags(uint32_t flags) {
1566 return android_atomic_or(flags, &mTransactionFlags);
1567}
1568
Robert Carr82364e32016-05-15 11:27:47 -07001569bool Layer::setPosition(float x, float y, bool immediate) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001570 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
Mathias Agopian13127d82013-03-05 17:47:11 -08001571 return false;
1572 mCurrentState.sequence++;
Robert Carr69663fb2016-03-27 19:59:19 -07001573
1574 // We update the requested and active position simultaneously because
1575 // we want to apply the position portion of the transform matrix immediately,
1576 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
Robert Carr3dcabfa2016-03-01 18:36:58 -08001577 mCurrentState.requested.transform.set(x, y);
Robert Carr82364e32016-05-15 11:27:47 -07001578 if (immediate && !mFreezePositionUpdates) {
1579 mCurrentState.active.transform.set(x, y);
1580 }
1581 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
Robert Carr69663fb2016-03-27 19:59:19 -07001582
Dan Stoza7dde5992015-05-22 09:51:44 -07001583 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001584 setTransactionFlags(eTransactionNeeded);
1585 return true;
1586}
Robert Carr82364e32016-05-15 11:27:47 -07001587
Mathias Agopian13127d82013-03-05 17:47:11 -08001588bool Layer::setLayer(uint32_t z) {
1589 if (mCurrentState.z == z)
1590 return false;
1591 mCurrentState.sequence++;
1592 mCurrentState.z = z;
Dan Stoza7dde5992015-05-22 09:51:44 -07001593 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001594 setTransactionFlags(eTransactionNeeded);
1595 return true;
1596}
1597bool Layer::setSize(uint32_t w, uint32_t h) {
1598 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1599 return false;
1600 mCurrentState.requested.w = w;
1601 mCurrentState.requested.h = h;
Dan Stoza7dde5992015-05-22 09:51:44 -07001602 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001603 setTransactionFlags(eTransactionNeeded);
1604 return true;
1605}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001606#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001607bool Layer::setAlpha(float alpha) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001608#else
1609bool Layer::setAlpha(uint8_t alpha) {
1610#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08001611 if (mCurrentState.alpha == alpha)
1612 return false;
1613 mCurrentState.sequence++;
1614 mCurrentState.alpha = alpha;
Dan Stoza7dde5992015-05-22 09:51:44 -07001615 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001616 setTransactionFlags(eTransactionNeeded);
1617 return true;
1618}
1619bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1620 mCurrentState.sequence++;
Robert Carr3dcabfa2016-03-01 18:36:58 -08001621 mCurrentState.requested.transform.set(
Mathias Agopian13127d82013-03-05 17:47:11 -08001622 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
Dan Stoza7dde5992015-05-22 09:51:44 -07001623 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001624 setTransactionFlags(eTransactionNeeded);
1625 return true;
1626}
1627bool Layer::setTransparentRegionHint(const Region& transparent) {
Mathias Agopian2ca79392013-04-02 18:30:32 -07001628 mCurrentState.requestedTransparentRegion = transparent;
Dan Stoza7dde5992015-05-22 09:51:44 -07001629 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001630 setTransactionFlags(eTransactionNeeded);
1631 return true;
1632}
1633bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1634 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1635 if (mCurrentState.flags == newFlags)
1636 return false;
1637 mCurrentState.sequence++;
1638 mCurrentState.flags = newFlags;
Dan Stoza7dde5992015-05-22 09:51:44 -07001639 mCurrentState.mask = mask;
1640 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001641 setTransactionFlags(eTransactionNeeded);
1642 return true;
1643}
Robert Carr99e27f02016-06-16 15:18:02 -07001644
1645bool Layer::setCrop(const Rect& crop, bool immediate) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001646 if (mCurrentState.crop == crop)
Mathias Agopian13127d82013-03-05 17:47:11 -08001647 return false;
1648 mCurrentState.sequence++;
Robert Carr99e27f02016-06-16 15:18:02 -07001649 mCurrentState.requestedCrop = crop;
1650 if (immediate) {
1651 mCurrentState.crop = crop;
1652 }
Dan Stoza7dde5992015-05-22 09:51:44 -07001653 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001654 setTransactionFlags(eTransactionNeeded);
1655 return true;
1656}
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001657bool Layer::setFinalCrop(const Rect& crop) {
Robert Carrb5d3d262016-03-25 15:08:13 -07001658 if (mCurrentState.finalCrop == crop)
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001659 return false;
1660 mCurrentState.sequence++;
Robert Carrb5d3d262016-03-25 15:08:13 -07001661 mCurrentState.finalCrop = crop;
Pablo Ceballosacbe6782016-03-04 17:54:21 +00001662 mCurrentState.modified = true;
1663 setTransactionFlags(eTransactionNeeded);
1664 return true;
1665}
Mathias Agopian13127d82013-03-05 17:47:11 -08001666
Robert Carrc3574f72016-03-24 12:19:32 -07001667bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1668 if (scalingMode == mOverrideScalingMode)
1669 return false;
1670 mOverrideScalingMode = scalingMode;
Robert Carr82364e32016-05-15 11:27:47 -07001671 setTransactionFlags(eTransactionNeeded);
Robert Carrc3574f72016-03-24 12:19:32 -07001672 return true;
1673}
1674
1675uint32_t Layer::getEffectiveScalingMode() const {
1676 if (mOverrideScalingMode >= 0) {
1677 return mOverrideScalingMode;
1678 }
1679 return mCurrentScalingMode;
1680}
1681
Mathias Agopian13127d82013-03-05 17:47:11 -08001682bool Layer::setLayerStack(uint32_t layerStack) {
1683 if (mCurrentState.layerStack == layerStack)
1684 return false;
1685 mCurrentState.sequence++;
1686 mCurrentState.layerStack = layerStack;
Dan Stoza7dde5992015-05-22 09:51:44 -07001687 mCurrentState.modified = true;
Mathias Agopian13127d82013-03-05 17:47:11 -08001688 setTransactionFlags(eTransactionNeeded);
1689 return true;
Mathias Agopiana67932f2011-04-20 14:20:59 -07001690}
1691
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07001692bool Layer::setDataSpace(android_dataspace dataSpace) {
1693 if (mCurrentState.dataSpace == dataSpace)
1694 return false;
1695 mCurrentState.sequence++;
1696 mCurrentState.dataSpace = dataSpace;
1697 mCurrentState.modified = true;
1698 setTransactionFlags(eTransactionNeeded);
1699 return true;
1700}
1701
Dan Stoza7dde5992015-05-22 09:51:44 -07001702void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1703 uint64_t frameNumber) {
1704 mCurrentState.handle = handle;
1705 mCurrentState.frameNumber = frameNumber;
1706 // We don't set eTransactionNeeded, because just receiving a deferral
1707 // request without any other state updates shouldn't actually induce a delay
1708 mCurrentState.modified = true;
1709 pushPendingState();
Dan Stoza792e5292016-02-11 11:43:58 -08001710 mCurrentState.handle = nullptr;
1711 mCurrentState.frameNumber = 0;
Dan Stoza7dde5992015-05-22 09:51:44 -07001712 mCurrentState.modified = false;
1713}
1714
Dan Stozaee44edd2015-03-23 15:50:23 -07001715void Layer::useSurfaceDamage() {
1716 if (mFlinger->mForceFullDamage) {
1717 surfaceDamageRegion = Region::INVALID_REGION;
1718 } else {
1719 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1720 }
1721}
1722
1723void Layer::useEmptyDamage() {
1724 surfaceDamageRegion.clear();
1725}
1726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001727// ----------------------------------------------------------------------------
1728// pageflip handling...
1729// ----------------------------------------------------------------------------
1730
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731bool Layer::shouldPresentNow(const DispSync& dispSync) const {
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001732 if (mSidebandStreamChanged || mAutoRefresh) {
Dan Stozad87defa2015-07-29 16:15:50 -07001733 return true;
1734 }
1735
Dan Stoza6b9454d2014-11-07 16:00:59 -08001736 Mutex::Autolock lock(mQueueItemLock);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001737 if (mQueueItems.empty()) {
1738 return false;
1739 }
1740 auto timestamp = mQueueItems[0].mTimestamp;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001741 nsecs_t expectedPresent =
1742 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
Dan Stoza0eb2d392015-07-06 12:56:50 -07001743
1744 // Ignore timestamps more than a second in the future
1745 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1746 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1747 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1748 expectedPresent);
1749
1750 bool isDue = timestamp < expectedPresent;
1751 return isDue || !isPlausible;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001752}
1753
Brian Andersond6927fb2016-07-23 23:37:30 -07001754bool Layer::onPreComposition(nsecs_t refreshStartTime) {
1755 if (mBufferLatched) {
1756 Mutex::Autolock lock(mFrameEventHistoryMutex);
1757 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
1758 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08001759 mRefreshPending = false;
Pablo Ceballosff95aab2016-01-13 17:09:58 -08001760 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001761}
1762
Brian Anderson3d4039d2016-09-23 16:31:30 -07001763bool Layer::onPostComposition(
1764 const std::shared_ptr<FenceTime>& glDoneFence,
1765 const std::shared_ptr<FenceTime>& presentFence,
1766 const std::shared_ptr<FenceTime>& retireFence) {
1767 mAcquireTimeline.updateSignalTimes();
1768 mReleaseTimeline.updateSignalTimes();
1769
Brian Andersond6927fb2016-07-23 23:37:30 -07001770 // mFrameLatencyNeeded is true when a new frame was latched for the
1771 // composition.
Fabien Sanglard28e98082016-12-05 10:19:46 -08001772 if (!mFrameLatencyNeeded)
1773 return false;
1774
Fabien Sanglard28e98082016-12-05 10:19:46 -08001775 // Update mFrameEventHistory.
1776 {
1777 Mutex::Autolock lock(mFrameEventHistoryMutex);
1778 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
Brian Anderson3d4039d2016-09-23 16:31:30 -07001779 glDoneFence, presentFence);
Fabien Sanglard28e98082016-12-05 10:19:46 -08001780 mFrameEventHistory.addRetire(mPreviousFrameNumber,
1781 retireFence);
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001782 }
Fabien Sanglard28e98082016-12-05 10:19:46 -08001783
1784 // Update mFrameTracker.
1785 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1786 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1787
Brian Anderson3d4039d2016-09-23 16:31:30 -07001788 std::shared_ptr<FenceTime> frameReadyFence =
1789 mSurfaceFlingerConsumer->getCurrentFenceTime();
Fabien Sanglard28e98082016-12-05 10:19:46 -08001790 if (frameReadyFence->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001791 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001792 } else {
1793 // There was no fence for this frame, so assume that it was ready
1794 // to be presented at the desired present time.
1795 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1796 }
1797
Brian Anderson3d4039d2016-09-23 16:31:30 -07001798 if (presentFence->isValid()) {
1799 mFrameTracker.setActualPresentFence(
1800 std::shared_ptr<FenceTime>(presentFence));
1801 } else if (retireFence->isValid()) {
1802 mFrameTracker.setActualPresentFence(
1803 std::shared_ptr<FenceTime>(retireFence));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001804 } else {
1805 // The HWC doesn't support present fences, so use the refresh
1806 // timestamp instead.
Brian Anderson3d4039d2016-09-23 16:31:30 -07001807 mFrameTracker.setActualPresentTime(
1808 mFlinger->getHwComposer().getRefreshTimestamp(
1809 HWC_DISPLAY_PRIMARY));
Fabien Sanglard28e98082016-12-05 10:19:46 -08001810 }
1811
1812 mFrameTracker.advanceFrame();
1813 mFrameLatencyNeeded = false;
1814 return true;
Mathias Agopiand3ee2312012-08-02 14:01:42 -07001815}
1816
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001817#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001818void Layer::releasePendingBuffer() {
1819 mSurfaceFlingerConsumer->releasePendingBuffer();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001820 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07001821 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001822 mReleaseTimeline.push(releaseFenceTime);
1823
1824 Mutex::Autolock lock(mFrameEventHistoryMutex);
1825 mFrameEventHistory.addRelease(
1826 mPreviousFrameNumber, std::move(releaseFenceTime));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001827}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001828#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08001829
Mathias Agopianda27af92012-09-13 18:17:13 -07001830bool Layer::isVisible() const {
Mathias Agopian13127d82013-03-05 17:47:11 -08001831 const Layer::State& s(mDrawingState);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001832#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1834 && (mActiveBuffer != NULL || mSidebandStream != NULL);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001835#else
1836 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1837 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1838#endif
Mathias Agopianda27af92012-09-13 18:17:13 -07001839}
1840
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001841bool Layer::allTransactionsSignaled() {
1842 auto headFrameNumber = getHeadFrameNumber();
1843 bool matchingFramesFound = false;
1844 bool allTransactionsApplied = true;
1845 Mutex::Autolock lock(mLocalSyncPointMutex);
1846
1847 for (auto& point : mLocalSyncPoints) {
1848 if (point->getFrameNumber() > headFrameNumber) {
1849 break;
1850 }
1851 matchingFramesFound = true;
1852
1853 if (!point->frameIsAvailable()) {
1854 // We haven't notified the remote layer that the frame for
1855 // this point is available yet. Notify it now, and then
1856 // abort this attempt to latch.
1857 point->setFrameAvailable();
1858 allTransactionsApplied = false;
1859 break;
1860 }
1861
1862 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
1863 }
1864 return !matchingFramesFound || allTransactionsApplied;
1865}
1866
Brian Andersond6927fb2016-07-23 23:37:30 -07001867Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001868{
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001869 ATRACE_CALL();
1870
Jesse Hall399184a2014-03-03 15:42:54 -08001871 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1872 // mSidebandStreamChanged was true
1873 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
Dan Stoza12e0a272015-05-05 14:00:52 -07001874 if (mSidebandStream != NULL) {
1875 setTransactionFlags(eTransactionNeeded);
1876 mFlinger->setTransactionFlags(eTraversalNeeded);
1877 }
Jesse Hall5bf786d2014-09-30 10:35:11 -07001878 recomputeVisibleRegions = true;
1879
1880 const State& s(getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001881 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
Jesse Hall399184a2014-03-03 15:42:54 -08001882 }
1883
Mathias Agopian4fec8732012-06-29 14:12:52 -07001884 Region outDirtyRegion;
Fabien Sanglard223eb912016-10-13 10:15:06 -07001885 if (mQueuedFrames <= 0 && !mAutoRefresh) {
1886 return outDirtyRegion;
1887 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001888
Fabien Sanglard223eb912016-10-13 10:15:06 -07001889 // if we've already called updateTexImage() without going through
1890 // a composition step, we have to skip this layer at this point
1891 // because we cannot call updateTeximage() without a corresponding
1892 // compositionComplete() call.
1893 // we'll trigger an update in onPreComposition().
1894 if (mRefreshPending) {
1895 return outDirtyRegion;
1896 }
1897
1898 // If the head buffer's acquire fence hasn't signaled yet, return and
1899 // try again later
1900 if (!headFenceHasSignaled()) {
1901 mFlinger->signalLayerUpdate();
1902 return outDirtyRegion;
1903 }
1904
1905 // Capture the old state of the layer for comparisons later
1906 const State& s(getDrawingState());
1907 const bool oldOpacity = isOpaque(s);
1908 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1909
Fabien Sanglardcd6fd542016-10-13 12:47:39 -07001910 if (!allTransactionsSignaled()) {
Fabien Sanglard223eb912016-10-13 10:15:06 -07001911 mFlinger->signalLayerUpdate();
1912 return outDirtyRegion;
1913 }
1914
1915 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1916 // of the buffer queue isn't modified when the buffer queue is returning
1917 // BufferItem's that weren't actually queued. This can happen in shared
1918 // buffer mode.
1919 bool queuedBuffer = false;
Fabien Sanglard7b1563a2016-10-13 12:05:28 -07001920 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1921 getProducerStickyTransform() != 0, mName.string(),
1922 mOverrideScalingMode, mFreezePositionUpdates);
Fabien Sanglard223eb912016-10-13 10:15:06 -07001923 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1924 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1925 mLastFrameNumberReceived);
1926 if (updateResult == BufferQueue::PRESENT_LATER) {
1927 // Producer doesn't want buffer to be displayed yet. Signal a
1928 // layer update so we check again at the next opportunity.
1929 mFlinger->signalLayerUpdate();
1930 return outDirtyRegion;
1931 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1932 // If the buffer has been rejected, remove it from the shadow queue
1933 // and return early
1934 if (queuedBuffer) {
1935 Mutex::Autolock lock(mQueueItemLock);
1936 mQueueItems.removeAt(0);
1937 android_atomic_dec(&mQueuedFrames);
1938 }
1939 return outDirtyRegion;
1940 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1941 // This can occur if something goes wrong when trying to create the
1942 // EGLImage for this buffer. If this happens, the buffer has already
1943 // been released, so we need to clean up the queue and bug out
1944 // early.
1945 if (queuedBuffer) {
1946 Mutex::Autolock lock(mQueueItemLock);
1947 mQueueItems.clear();
1948 android_atomic_and(0, &mQueuedFrames);
Mathias Agopian702634a2012-05-23 17:50:31 -07001949 }
1950
Fabien Sanglard223eb912016-10-13 10:15:06 -07001951 // Once we have hit this state, the shadow queue may no longer
1952 // correctly reflect the incoming BufferQueue's contents, so even if
1953 // updateTexImage starts working, the only safe course of action is
1954 // to continue to ignore updates.
1955 mUpdateTexImageFailed = true;
1956
1957 return outDirtyRegion;
1958 }
1959
1960 if (queuedBuffer) {
1961 // Autolock scope
1962 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1963
1964 Mutex::Autolock lock(mQueueItemLock);
1965
1966 // Remove any stale buffers that have been dropped during
1967 // updateTexImage
1968 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1969 mQueueItems.removeAt(0);
1970 android_atomic_dec(&mQueuedFrames);
1971 }
1972
1973 mQueueItems.removeAt(0);
1974 }
1975
1976
1977 // Decrement the queued-frames count. Signal another event if we
1978 // have more frames pending.
1979 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1980 || mAutoRefresh) {
1981 mFlinger->signalLayerUpdate();
1982 }
1983
Fabien Sanglard223eb912016-10-13 10:15:06 -07001984 // update the active buffer
1985 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1986 if (mActiveBuffer == NULL) {
1987 // this can only happen if the very first buffer was rejected.
1988 return outDirtyRegion;
1989 }
1990
Brian Andersond6927fb2016-07-23 23:37:30 -07001991 mBufferLatched = true;
1992 mPreviousFrameNumber = mCurrentFrameNumber;
1993 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1994
1995 {
1996 Mutex::Autolock lock(mFrameEventHistoryMutex);
1997 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
1998#ifndef USE_HWC2
Brian Anderson3d4039d2016-09-23 16:31:30 -07001999 auto releaseFenceTime = std::make_shared<FenceTime>(
Brian Andersond6927fb2016-07-23 23:37:30 -07002000 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
Brian Anderson3d4039d2016-09-23 16:31:30 -07002001 mReleaseTimeline.push(releaseFenceTime);
2002 mFrameEventHistory.addRelease(
2003 mPreviousFrameNumber, std::move(releaseFenceTime));
Brian Andersond6927fb2016-07-23 23:37:30 -07002004#endif
2005 }
2006
Fabien Sanglard223eb912016-10-13 10:15:06 -07002007 mRefreshPending = true;
2008 mFrameLatencyNeeded = true;
2009 if (oldActiveBuffer == NULL) {
2010 // the first time we receive a buffer, we need to trigger a
2011 // geometry invalidation.
2012 recomputeVisibleRegions = true;
2013 }
2014
Courtney Goeltzenleuchterbb09b432016-11-30 13:51:28 -07002015 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2016
Fabien Sanglard223eb912016-10-13 10:15:06 -07002017 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2018 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2019 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2020 if ((crop != mCurrentCrop) ||
2021 (transform != mCurrentTransform) ||
2022 (scalingMode != mCurrentScalingMode))
2023 {
2024 mCurrentCrop = crop;
2025 mCurrentTransform = transform;
2026 mCurrentScalingMode = scalingMode;
2027 recomputeVisibleRegions = true;
2028 }
2029
2030 if (oldActiveBuffer != NULL) {
2031 uint32_t bufWidth = mActiveBuffer->getWidth();
2032 uint32_t bufHeight = mActiveBuffer->getHeight();
2033 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2034 bufHeight != uint32_t(oldActiveBuffer->height)) {
Mathias Agopian702634a2012-05-23 17:50:31 -07002035 recomputeVisibleRegions = true;
2036 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002037 }
Mathias Agopian702634a2012-05-23 17:50:31 -07002038
Fabien Sanglard223eb912016-10-13 10:15:06 -07002039 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2040 if (oldOpacity != isOpaque(s)) {
2041 recomputeVisibleRegions = true;
2042 }
Dan Stozacac35382016-01-27 12:21:06 -08002043
Fabien Sanglard223eb912016-10-13 10:15:06 -07002044 // Remove any sync points corresponding to the buffer which was just
2045 // latched
2046 {
2047 Mutex::Autolock lock(mLocalSyncPointMutex);
2048 auto point = mLocalSyncPoints.begin();
2049 while (point != mLocalSyncPoints.end()) {
2050 if (!(*point)->frameIsAvailable() ||
2051 !(*point)->transactionIsApplied()) {
2052 // This sync point must have been added since we started
2053 // latching. Don't drop it yet.
2054 ++point;
2055 continue;
2056 }
2057
2058 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2059 point = mLocalSyncPoints.erase(point);
2060 } else {
2061 ++point;
Dan Stozacac35382016-01-27 12:21:06 -08002062 }
2063 }
Mathias Agopiancaa600c2009-09-16 18:27:24 -07002064 }
Fabien Sanglard223eb912016-10-13 10:15:06 -07002065
2066 // FIXME: postedRegion should be dirty & bounds
2067 Region dirtyRegion(Rect(s.active.w, s.active.h));
2068
2069 // transform the dirty region to window-manager space
2070 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2071
Mathias Agopian4fec8732012-06-29 14:12:52 -07002072 return outDirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002073}
2074
Mathias Agopiana67932f2011-04-20 14:20:59 -07002075uint32_t Layer::getEffectiveUsage(uint32_t usage) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07002076{
Mathias Agopiana67932f2011-04-20 14:20:59 -07002077 // TODO: should we do something special if mSecure is set?
2078 if (mProtectedByApp) {
2079 // need a hardware-protected path to external video sink
2080 usage |= GraphicBuffer::USAGE_PROTECTED;
Jamie Gennis54cc83e2010-11-02 11:51:32 -07002081 }
Riley Andrews03414a12014-07-01 14:22:59 -07002082 if (mPotentialCursor) {
2083 usage |= GraphicBuffer::USAGE_CURSOR;
2084 }
Jamie Gennis3599bf22011-08-10 11:48:07 -07002085 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
Mathias Agopiana67932f2011-04-20 14:20:59 -07002086 return usage;
Mathias Agopianb5b7f262010-05-07 15:58:44 -07002087}
2088
Mathias Agopian84300952012-11-21 16:02:13 -08002089void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
Mathias Agopiana4583642011-08-23 18:03:18 -07002090 uint32_t orientation = 0;
2091 if (!mFlinger->mDebugDisableTransformHint) {
Mathias Agopian84300952012-11-21 16:02:13 -08002092 // The transform hint is used to improve performance, but we can
2093 // only have a single transform hint, it cannot
Mathias Agopian4fec8732012-06-29 14:12:52 -07002094 // apply to all displays.
Mathias Agopian42977342012-08-05 00:40:46 -07002095 const Transform& planeTransform(hw->getTransform());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002096 orientation = planeTransform.getOrientation();
Mathias Agopiana4583642011-08-23 18:03:18 -07002097 if (orientation & Transform::ROT_INVALID) {
2098 orientation = 0;
2099 }
2100 }
Andy McFaddenbf974ab2012-12-04 16:51:15 -08002101 mSurfaceFlingerConsumer->setTransformHint(orientation);
Mathias Agopiana4583642011-08-23 18:03:18 -07002102}
2103
Mathias Agopian13127d82013-03-05 17:47:11 -08002104// ----------------------------------------------------------------------------
2105// debugging
2106// ----------------------------------------------------------------------------
2107
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002108void Layer::dump(String8& result, Colorizer& colorizer) const
Mathias Agopian13127d82013-03-05 17:47:11 -08002109{
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002110 const Layer::State& s(getDrawingState());
Mathias Agopian13127d82013-03-05 17:47:11 -08002111
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002112 colorizer.colorize(result, Colorizer::GREEN);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002113 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002114 "+ %s %p (%s)\n",
2115 getTypeId(), this, getName().string());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002116 colorizer.reset(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002117
Mathias Agopian2ca79392013-04-02 18:30:32 -07002118 s.activeTransparentRegion.dump(result, "transparentRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002119 visibleRegion.dump(result, "visibleRegion");
Dan Stozaee44edd2015-03-23 15:50:23 -07002120 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
Mathias Agopian13127d82013-03-05 17:47:11 -08002121 sp<Client> client(mClientRef.promote());
2122
Mathias Agopian74d211a2013-04-22 16:55:35 +02002123 result.appendFormat( " "
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002124 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2125 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
Mathias Agopian13127d82013-03-05 17:47:11 -08002126 "isOpaque=%1d, invalidate=%1d, "
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002127#ifdef USE_HWC2
Dan Stoza9e56aa02015-11-02 13:00:03 -08002128 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002129#else
2130 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2131#endif
Mathias Agopian13127d82013-03-05 17:47:11 -08002132 " client=%p\n",
Robert Carr3dcabfa2016-03-01 18:36:58 -08002133 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 -07002134 s.crop.left, s.crop.top,
2135 s.crop.right, s.crop.bottom,
2136 s.finalCrop.left, s.finalCrop.top,
2137 s.finalCrop.right, s.finalCrop.bottom,
Andy McFadden4125a4f2014-01-29 17:17:11 -08002138 isOpaque(s), contentDirty,
Mathias Agopian13127d82013-03-05 17:47:11 -08002139 s.alpha, s.flags,
Robert Carr3dcabfa2016-03-01 18:36:58 -08002140 s.active.transform[0][0], s.active.transform[0][1],
2141 s.active.transform[1][0], s.active.transform[1][1],
Mathias Agopian13127d82013-03-05 17:47:11 -08002142 client.get());
Mathias Agopian13127d82013-03-05 17:47:11 -08002143
2144 sp<const GraphicBuffer> buf0(mActiveBuffer);
2145 uint32_t w0=0, h0=0, s0=0, f0=0;
2146 if (buf0 != 0) {
2147 w0 = buf0->getWidth();
2148 h0 = buf0->getHeight();
2149 s0 = buf0->getStride();
2150 f0 = buf0->format;
2151 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02002152 result.appendFormat(
Mathias Agopian13127d82013-03-05 17:47:11 -08002153 " "
2154 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2155 " queued-frames=%d, mRefreshPending=%d\n",
2156 mFormat, w0, h0, s0,f0,
2157 mQueuedFrames, mRefreshPending);
2158
Mathias Agopian13127d82013-03-05 17:47:11 -08002159 if (mSurfaceFlingerConsumer != 0) {
Colin Cross3d1d2802016-09-26 18:10:16 -07002160 mSurfaceFlingerConsumer->dumpState(result, " ");
Mathias Agopian13127d82013-03-05 17:47:11 -08002161 }
2162}
2163
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002164#ifdef USE_HWC2
Dan Stozae22aec72016-08-01 13:20:59 -07002165void Layer::miniDumpHeader(String8& result) {
2166 result.append("----------------------------------------");
2167 result.append("---------------------------------------\n");
2168 result.append(" Layer name\n");
2169 result.append(" Z | ");
2170 result.append(" Comp Type | ");
2171 result.append(" Disp Frame (LTRB) | ");
2172 result.append(" Source Crop (LTRB)\n");
2173 result.append("----------------------------------------");
2174 result.append("---------------------------------------\n");
2175}
2176
2177void Layer::miniDump(String8& result, int32_t hwcId) const {
2178 if (mHwcLayers.count(hwcId) == 0) {
2179 return;
2180 }
2181
2182 String8 name;
2183 if (mName.length() > 77) {
2184 std::string shortened;
2185 shortened.append(mName.string(), 36);
2186 shortened.append("[...]");
2187 shortened.append(mName.string() + (mName.length() - 36), 36);
2188 name = shortened.c_str();
2189 } else {
2190 name = mName;
2191 }
2192
2193 result.appendFormat(" %s\n", name.string());
2194
2195 const Layer::State& layerState(getDrawingState());
2196 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2197 result.appendFormat(" %10u | ", layerState.z);
2198 result.appendFormat("%10s | ",
2199 to_string(getCompositionType(hwcId)).c_str());
2200 const Rect& frame = hwcInfo.displayFrame;
2201 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2202 frame.right, frame.bottom);
Dan Stoza71bded52016-10-19 11:10:33 -07002203 const gfx::FloatRect& crop = hwcInfo.sourceCrop;
Dan Stozae22aec72016-08-01 13:20:59 -07002204 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2205 crop.right, crop.bottom);
2206
2207 result.append("- - - - - - - - - - - - - - - - - - - - ");
2208 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2209}
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002210#endif
Dan Stozae22aec72016-08-01 13:20:59 -07002211
Svetoslavd85084b2014-03-20 10:28:31 -07002212void Layer::dumpFrameStats(String8& result) const {
2213 mFrameTracker.dumpStats(result);
Mathias Agopian13127d82013-03-05 17:47:11 -08002214}
2215
Svetoslavd85084b2014-03-20 10:28:31 -07002216void Layer::clearFrameStats() {
2217 mFrameTracker.clearStats();
Mathias Agopian13127d82013-03-05 17:47:11 -08002218}
2219
Jamie Gennis6547ff42013-07-16 20:12:42 -07002220void Layer::logFrameStats() {
2221 mFrameTracker.logAndResetStats(mName);
2222}
2223
Svetoslavd85084b2014-03-20 10:28:31 -07002224void Layer::getFrameStats(FrameStats* outStats) const {
2225 mFrameTracker.getStats(outStats);
2226}
2227
Brian Andersond6927fb2016-07-23 23:37:30 -07002228void Layer::dumpFrameEvents(String8& result) {
2229 result.appendFormat("- Layer %s (%s, %p)\n",
2230 getName().string(), getTypeId(), this);
2231 Mutex::Autolock lock(mFrameEventHistoryMutex);
2232 mFrameEventHistory.checkFencesForCompletion();
2233 mFrameEventHistory.dump(result);
2234}
Pablo Ceballos40845df2016-01-25 17:41:15 -08002235
Brian Anderson3890c392016-07-25 12:48:08 -07002236void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2237 FrameEventHistoryDelta *outDelta) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002238 Mutex::Autolock lock(mFrameEventHistoryMutex);
2239 if (newTimestamps) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002240 mAcquireTimeline.push(newTimestamps->acquireFence);
Brian Andersond6927fb2016-07-23 23:37:30 -07002241 mFrameEventHistory.addQueue(*newTimestamps);
2242 }
2243
Brian Anderson3890c392016-07-25 12:48:08 -07002244 if (outDelta) {
2245 mFrameEventHistory.getAndResetDelta(outDelta);
Brian Andersond6927fb2016-07-23 23:37:30 -07002246 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002247}
Dan Stozae77c7662016-05-13 11:37:28 -07002248
2249std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2250 bool forceFlush) {
2251 std::vector<OccupancyTracker::Segment> history;
2252 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2253 &history);
2254 if (result != NO_ERROR) {
2255 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2256 result);
2257 return {};
2258 }
2259 return history;
2260}
2261
Robert Carr367c5682016-06-20 11:55:28 -07002262bool Layer::getTransformToDisplayInverse() const {
2263 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2264}
2265
Mathias Agopian13127d82013-03-05 17:47:11 -08002266// ---------------------------------------------------------------------------
2267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002268}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07002269
2270#if defined(__gl_h_)
2271#error "don't include gl/gl.h in this file"
2272#endif
2273
2274#if defined(__gl2_h_)
2275#error "don't include gl2/gl2.h in this file"
2276#endif