blob: beefc5066b7503634debcba456ddcbce1e7aa4ee [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
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060040#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070042#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070045#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080047#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070072#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080074#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Mathias Agopiana4912602012-07-12 14:25:33 -070077#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070078#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070079#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include "Effects/Daltonizer.h"
82
Mathias Agopian875d8e12013-06-07 15:35:48 -070083#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070085
Jiyong Park4b20c2e2017-01-14 19:45:11 +090086#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090087#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#define DISPLAY_COUNT 1
90
Mathias Agopianfee2b462013-07-03 12:34:01 -070091/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
Mathias Agopianca088332013-03-28 17:44:13 -070097EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080099namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700100
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800101
Jaesoo Lee43518572017-01-23 19:03:16 +0900102using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900103using namespace android::hardware::configstore::V1_0;
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105// ---------------------------------------------------------------------------
106
Mathias Agopian99b49842011-06-27 16:05:52 -0700107const String16 sHardwareTest("android.permission.HARDWARE_TEST");
108const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
109const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
110const String16 sDump("android.permission.DUMP");
111
112// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800113int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
114int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700115bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700116int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700117bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800118uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800119bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800120bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800121int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600122bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700125 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700127 mTransactionPending(false),
128 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700129 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700130 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700131 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800132 mHwc(nullptr),
133 mRealHwc(nullptr),
134 mVrHwc(nullptr),
135 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800136 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800137 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800140 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700142 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700143 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700144 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700145 mDebugInSwapBuffers(0),
146 mLastSwapBufferTime(0),
147 mDebugInTransaction(0),
148 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700149 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700150 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800151 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000152 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700153 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700154 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800155 mHasColorMatrix(false),
156 mHasPoweredOff(false),
157 mFrameBuckets(),
158 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700159 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800160 mNumLayers(0),
161 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800162{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800163 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800164
165 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
166 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
167
168 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
169 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
170
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800171 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
172 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700174 useContextPriority = getBool< ISurfaceFlingerConfigs,
175 &ISurfaceFlingerConfigs::useContextPriority>(false);
176
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700177 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
178 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
179
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700180 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
181 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
182
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800183 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
184 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
185
Steven Thomas050b2c82017-03-06 11:45:16 -0800186 // Vr flinger is only enabled on Daydream ready devices.
187 useVrFlinger = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::useVrFlinger>(false);
189
Fabien Sanglard1971b632017-03-10 14:50:03 -0800190 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
192
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600193 hasWideColorDisplay =
194 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
195
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800196 // debugging stuff...
197 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700198
Mathias Agopianb4b17302013-03-20 18:36:41 -0700199 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700200 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202 property_get("debug.sf.showupdates", value, "0");
203 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700204
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205 property_get("debug.sf.ddms", value, "0");
206 mDebugDDMS = atoi(value);
207 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700208 if (!startDdmConnection()) {
209 // start failed, and DDMS debugging not enabled
210 mDebugDDMS = 0;
211 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700212 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700213 ALOGI_IF(mDebugRegion, "showupdates enabled");
214 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700215
216 property_get("debug.sf.disable_backpressure", value, "0");
217 mPropagateBackpressure = !atoi(value);
218 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700219
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800220 property_get("debug.sf.enable_hwc_vds", value, "0");
221 mUseHwcVirtualDisplays = atoi(value);
222 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800223
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800224 property_get("ro.sf.disable_triple_buffer", value, "1");
225 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800226 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227}
228
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800229void SurfaceFlinger::onFirstRef()
230{
231 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800232}
233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234SurfaceFlinger::~SurfaceFlinger()
235{
Mathias Agopiana4912602012-07-12 14:25:33 -0700236 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
237 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
238 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239}
240
Dan Stozac7014012014-02-14 15:03:43 -0800241void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800242{
243 // the window manager died on us. prepare its eulogy.
244
Andy McFadden13a082e2012-08-24 10:16:42 -0700245 // restore initial conditions (default device unblank, etc)
246 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247
248 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700249 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800250}
251
Robert Carr1db73f62016-12-21 12:58:51 -0800252static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700253 status_t err = client->initCheck();
254 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800255 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256 }
Robert Carr1db73f62016-12-21 12:58:51 -0800257 return nullptr;
258}
259
260sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
261 return initClient(new Client(this));
262}
263
264sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
265 const sp<IGraphicBufferProducer>& gbp) {
266 if (authenticateSurfaceTexture(gbp) == false) {
267 return nullptr;
268 }
269 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
270 if (layer == nullptr) {
271 return nullptr;
272 }
273
274 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275}
276
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700277sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
278 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700279{
280 class DisplayToken : public BBinder {
281 sp<SurfaceFlinger> flinger;
282 virtual ~DisplayToken() {
283 // no more references, this display must be terminated
284 Mutex::Autolock _l(flinger->mStateLock);
285 flinger->mCurrentState.displays.removeItem(this);
286 flinger->setTransactionFlags(eDisplayTransactionNeeded);
287 }
288 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700289 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700290 : flinger(flinger) {
291 }
292 };
293
294 sp<BBinder> token = new DisplayToken(this);
295
296 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700297 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700298 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700300 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301 return token;
302}
303
Jesse Hall6c913be2013-08-08 12:15:49 -0700304void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
305 Mutex::Autolock _l(mStateLock);
306
307 ssize_t idx = mCurrentState.displays.indexOfKey(display);
308 if (idx < 0) {
309 ALOGW("destroyDisplay: invalid display token");
310 return;
311 }
312
313 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
314 if (!info.isVirtualDisplay()) {
315 ALOGE("destroyDisplay called for non-virtual display");
316 return;
317 }
Irvelffc9efc2016-07-27 15:16:37 -0700318 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700319 mCurrentState.displays.removeItemsAt(idx);
320 setTransactionFlags(eDisplayTransactionNeeded);
321}
322
Jesse Hall692c7232012-11-08 15:41:56 -0800323void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800324 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800325 ALOGW_IF(mBuiltinDisplays[type],
326 "Overwriting display token for display type %d", type);
327 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800328 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700329 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700331 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800332}
333
Mathias Agopiane57f2922012-08-09 16:29:12 -0700334sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700335 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700336 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
337 return NULL;
338 }
Jesse Hall692c7232012-11-08 15:41:56 -0800339 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340}
341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342void SurfaceFlinger::bootFinished()
343{
Wei Wangb254fa32017-01-31 17:43:23 -0800344 if (mStartBootAnimThread->join() != NO_ERROR) {
345 ALOGE("Join StartBootAnimThread failed!");
346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 const nsecs_t now = systemTime();
348 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000349 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700350 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700351
352 // wait patiently for the window manager death
353 const String16 name("window");
354 sp<IBinder> window(defaultServiceManager()->getService(name));
355 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700356 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700357 }
358
Steven Thomas050b2c82017-03-06 11:45:16 -0800359 if (mVrFlinger) {
360 mVrFlinger->OnBootFinished();
361 }
362
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700363 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700364 // formerly we would just kill the process, but we now ask it to exit so it
365 // can choose where to stop the animation.
366 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700367
368 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
369 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
370 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800371}
372
Mathias Agopian3f844832013-08-07 21:24:32 -0700373void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700374 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700375 RenderEngine& engine;
376 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700377 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700378 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
379 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700380 }
381 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700383 return true;
384 }
385 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700386 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387}
388
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389class DispSyncSource : public VSyncSource, private DispSync::Callback {
390public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700391 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000392 const char* name) :
393 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700394 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700395 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000396 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
397 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700398 mDispSync(dispSync),
399 mCallbackMutex(),
400 mCallback(),
401 mVsyncMutex(),
402 mPhaseOffset(phaseOffset),
403 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700404
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700405 virtual ~DispSyncSource() {}
406
407 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700408 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000410 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700411 static_cast<DispSync::Callback*>(this));
412 if (err != NO_ERROR) {
413 ALOGE("error registering vsync callback: %s (%d)",
414 strerror(-err), err);
415 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700416 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700417 } else {
418 status_t err = mDispSync->removeEventListener(
419 static_cast<DispSync::Callback*>(this));
420 if (err != NO_ERROR) {
421 ALOGE("error unregistering vsync callback: %s (%d)",
422 strerror(-err), err);
423 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700424 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700425 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700426 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427 }
428
429 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 mCallback = callback;
432 }
433
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 virtual void setPhaseOffset(nsecs_t phaseOffset) {
435 Mutex::Autolock lock(mVsyncMutex);
436
437 // Normalize phaseOffset to [0, period)
438 auto period = mDispSync->getPeriod();
439 phaseOffset %= period;
440 if (phaseOffset < 0) {
441 // If we're here, then phaseOffset is in (-period, 0). After this
442 // operation, it will be in (0, period)
443 phaseOffset += period;
444 }
445 mPhaseOffset = phaseOffset;
446
447 // If we're not enabled, we don't need to mess with the listeners
448 if (!mEnabled) {
449 return;
450 }
451
452 // Remove the listener with the old offset
453 status_t err = mDispSync->removeEventListener(
454 static_cast<DispSync::Callback*>(this));
455 if (err != NO_ERROR) {
456 ALOGE("error unregistering vsync callback: %s (%d)",
457 strerror(-err), err);
458 }
459
460 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000461 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462 static_cast<DispSync::Callback*>(this));
463 if (err != NO_ERROR) {
464 ALOGE("error registering vsync callback: %s (%d)",
465 strerror(-err), err);
466 }
467 }
468
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700469private:
470 virtual void onDispSyncEvent(nsecs_t when) {
471 sp<VSyncSource::Callback> callback;
472 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700473 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474 callback = mCallback;
475
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700476 if (mTraceVsync) {
477 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700478 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700479 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700480 }
481
482 if (callback != NULL) {
483 callback->onVSyncEvent(when);
484 }
485 }
486
Tim Murray4a4e4a22016-04-19 16:29:23 +0000487 const char* const mName;
488
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700489 int mValue;
490
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700491 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700492 const String8 mVsyncOnLabel;
493 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700494
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700495 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700496
497 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700498 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499
500 Mutex mVsyncMutex; // Protects the following
501 nsecs_t mPhaseOffset;
502 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503};
504
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700505class InjectVSyncSource : public VSyncSource {
506public:
507 InjectVSyncSource() {}
508
509 virtual ~InjectVSyncSource() {}
510
511 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
512 std::lock_guard<std::mutex> lock(mCallbackMutex);
513 mCallback = callback;
514 }
515
516 virtual void onInjectSyncEvent(nsecs_t when) {
517 std::lock_guard<std::mutex> lock(mCallbackMutex);
518 mCallback->onVSyncEvent(when);
519 }
520
521 virtual void setVSyncEnabled(bool) {}
522 virtual void setPhaseOffset(nsecs_t) {}
523
524private:
525 std::mutex mCallbackMutex; // Protects the following
526 sp<VSyncSource::Callback> mCallback;
527};
528
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700529void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700530 ALOGI( "SurfaceFlinger's main thread ready to run. "
531 "Initializing graphics H/W...");
532
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900533 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
534
Dan Stoza9e56aa02015-11-02 13:00:03 -0800535 { // Autolock scope
536 Mutex::Autolock _l(mStateLock);
537
538 // initialize EGL for the default display
539 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
540 eglInitialize(mEGLDisplay, NULL, NULL);
541
542 // start the EventThread
543 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
544 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700545 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800546 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
547 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700548 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800549 mEventQueue.setEventThread(mSFEventThread);
550
Tim Murray22752852017-05-04 13:38:49 -0700551 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700552 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700553 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700554 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
555 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
556 }
Tim Murray22752852017-05-04 13:38:49 -0700557 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
558 ALOGE("Couldn't set SCHED_FIFO for EventThread");
559 }
Tim Murray41a38532016-06-22 12:42:10 -0700560
Dan Stoza9e56aa02015-11-02 13:00:03 -0800561 // Get a RenderEngine for the given display / config (can't fail)
562 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700563 HAL_PIXEL_FORMAT_RGBA_8888,
564 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 }
566
567 // Drop the state lock while we initialize the hardware composer. We drop
568 // the lock because on creation, it will call back into SurfaceFlinger to
569 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800570 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
571 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800572 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800573 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800574 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
575
Jesse Hall692c7232012-11-08 15:41:56 -0800576 Mutex::Autolock _l(mStateLock);
577
Ian Elliott5c34de22017-04-10 14:42:30 -0600578 // Inform native graphics APIs whether the present timestamp is supported:
579 if (getHwComposer().hasCapability(
580 HWC2::Capability::PresentFenceIsNotReliable)) {
581 property_set(kTimestampProperty, "0");
582 } else {
583 property_set(kTimestampProperty, "1");
584 }
585
Steven Thomas050b2c82017-03-06 11:45:16 -0800586 if (useVrFlinger) {
587 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700588 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800589 mVrFlingerRequestsDisplay = requestDisplay;
590 signalTransaction();
591 };
592 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
593 vrFlingerRequestDisplayCallback);
594 if (!mVrFlinger) {
595 ALOGE("Failed to start vrflinger");
596 }
597 }
598
Mathias Agopian875d8e12013-06-07 15:35:48 -0700599 // retrieve the EGL context that was selected/created
600 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700601
Mathias Agopianda27af92012-09-13 18:17:13 -0700602 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
603 "couldn't create EGLContext");
604
Dan Stoza9e56aa02015-11-02 13:00:03 -0800605 // make the GLContext current so that we can create textures when creating
606 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700607 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700608
Jamie Gennisd1700752013-10-14 12:22:52 -0700609 mEventControlThread = new EventControlThread(this);
610 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
611
Mathias Agopian92a979a2012-08-02 18:32:23 -0700612 // initialize our drawing state
613 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700614
Andy McFadden13a082e2012-08-24 10:16:42 -0700615 // set initial conditions (e.g. unblank default device)
616 initializeDisplays();
617
Dan Stoza4e637772016-07-28 13:31:51 -0700618 mRenderEngine->primeCache();
619
Wei Wangb254fa32017-01-31 17:43:23 -0800620 mStartBootAnimThread = new StartBootAnimThread();
621 if (mStartBootAnimThread->Start() != NO_ERROR) {
622 ALOGE("Run StartBootAnimThread failed!");
623 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800624
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700626}
627
Mathias Agopiana67e4182012-06-19 17:26:12 -0700628void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800629 // Start boot animation service by setting a property mailbox
630 // if property setting thread is already running, Start() will be just a NOP
631 mStartBootAnimThread->Start();
632 // Wait until property was set
633 if (mStartBootAnimThread->join() != NO_ERROR) {
634 ALOGE("Join StartBootAnimThread failed!");
635 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700636}
637
Mathias Agopian875d8e12013-06-07 15:35:48 -0700638size_t SurfaceFlinger::getMaxTextureSize() const {
639 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700640}
641
Mathias Agopian875d8e12013-06-07 15:35:48 -0700642size_t SurfaceFlinger::getMaxViewportDims() const {
643 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700644}
645
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800646// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800647
Jamie Gennis582270d2011-08-17 18:19:00 -0700648bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800649 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800650 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800651 return authenticateSurfaceTextureLocked(bufferProducer);
652}
653
654bool SurfaceFlinger::authenticateSurfaceTextureLocked(
655 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800656 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700657 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800658}
659
Brian Anderson6b376712017-04-04 10:51:39 -0700660status_t SurfaceFlinger::getSupportedFrameTimestamps(
661 std::vector<FrameEvent>* outSupported) const {
662 *outSupported = {
663 FrameEvent::REQUESTED_PRESENT,
664 FrameEvent::ACQUIRE,
665 FrameEvent::LATCH,
666 FrameEvent::FIRST_REFRESH_START,
667 FrameEvent::LAST_REFRESH_START,
668 FrameEvent::GPU_COMPOSITION_DONE,
669 FrameEvent::DEQUEUE_READY,
670 FrameEvent::RELEASE,
671 };
672 if (!getHwComposer().hasCapability(
673 HWC2::Capability::PresentFenceIsNotReliable)) {
674 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
675 }
676 return NO_ERROR;
677}
678
Dan Stoza7f7da322014-05-02 15:26:25 -0700679status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
680 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700681 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700682 return BAD_VALUE;
683 }
684
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500685 if (!display.get())
686 return NAME_NOT_FOUND;
687
Jesse Hall692c7232012-11-08 15:41:56 -0800688 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700689 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800690 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700691 type = i;
692 break;
693 }
694 }
695
696 if (type < 0) {
697 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700698 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700699
Mathias Agopian8b736f12012-08-13 17:54:26 -0700700 // TODO: Not sure if display density should handled by SF any longer
701 class Density {
702 static int getDensityFromProperty(char const* propName) {
703 char property[PROPERTY_VALUE_MAX];
704 int density = 0;
705 if (property_get(propName, property, NULL) > 0) {
706 density = atoi(property);
707 }
708 return density;
709 }
710 public:
711 static int getEmuDensity() {
712 return getDensityFromProperty("qemu.sf.lcd_density"); }
713 static int getBuildDensity() {
714 return getDensityFromProperty("ro.sf.lcd_density"); }
715 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700716
Dan Stoza7f7da322014-05-02 15:26:25 -0700717 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700718
Dan Stoza9e56aa02015-11-02 13:00:03 -0800719 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700720 DisplayInfo info = DisplayInfo();
721
Dan Stoza9e56aa02015-11-02 13:00:03 -0800722 float xdpi = hwConfig->getDpiX();
723 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700724
725 if (type == DisplayDevice::DISPLAY_PRIMARY) {
726 // The density of the device is provided by a build property
727 float density = Density::getBuildDensity() / 160.0f;
728 if (density == 0) {
729 // the build doesn't provide a density -- this is wrong!
730 // use xdpi instead
731 ALOGE("ro.sf.lcd_density must be defined as a build property");
732 density = xdpi / 160.0f;
733 }
734 if (Density::getEmuDensity()) {
735 // if "qemu.sf.lcd_density" is specified, it overrides everything
736 xdpi = ydpi = density = Density::getEmuDensity();
737 density /= 160.0f;
738 }
739 info.density = density;
740
741 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000742 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
743 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700744 } else {
745 // TODO: where should this value come from?
746 static const int TV_DENSITY = 213;
747 info.density = TV_DENSITY / 160.0f;
748 info.orientation = 0;
749 }
750
Dan Stoza9e56aa02015-11-02 13:00:03 -0800751 info.w = hwConfig->getWidth();
752 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700753 info.xdpi = xdpi;
754 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900756 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800757
Andy McFadden91b2ca82014-06-13 14:04:23 -0700758 // This is how far in advance a buffer must be queued for
759 // presentation at a given time. If you want a buffer to appear
760 // on the screen at time N, you must submit the buffer before
761 // (N - presentationDeadline).
762 //
763 // Normally it's one full refresh period (to give SF a chance to
764 // latch the buffer), but this can be reduced by configuring a
765 // DispSync offset. Any additional delays introduced by the hardware
766 // composer or panel must be accounted for here.
767 //
768 // We add an additional 1ms to allow for processing time and
769 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800770 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800771 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700772
773 // All non-virtual displays are currently considered secure.
774 info.secure = true;
775
Michael Wright28f24d02016-07-12 13:30:53 -0700776 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700777 }
778
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 return NO_ERROR;
780}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700781
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800782status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700783 DisplayStatInfo* stats) {
784 if (stats == NULL) {
785 return BAD_VALUE;
786 }
787
788 // FIXME for now we always return stats for the primary display
789 memset(stats, 0, sizeof(*stats));
790 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
791 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
792 return NO_ERROR;
793}
794
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700795int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800796 if (display == NULL) {
797 ALOGE("%s : display is NULL", __func__);
798 return BAD_VALUE;
799 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700800
801 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700802 if (device != NULL) {
803 return device->getActiveConfig();
804 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700805
Dan Stoza24a42e92015-03-09 10:04:11 -0700806 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700807}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700808
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700809void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
810 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
811 this);
812 int32_t type = hw->getDisplayType();
813 int currentMode = hw->getActiveConfig();
814
815 if (mode == currentMode) {
816 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
817 return;
818 }
819
820 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
821 ALOGW("Trying to set config for virtual display");
822 return;
823 }
824
825 hw->setActiveConfig(mode);
826 getHwComposer().setActiveConfig(type, mode);
827}
828
829status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
830 class MessageSetActiveConfig: public MessageBase {
831 SurfaceFlinger& mFlinger;
832 sp<IBinder> mDisplay;
833 int mMode;
834 public:
835 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
836 int mode) :
837 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
838 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700839 Vector<DisplayInfo> configs;
840 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700841 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700842 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700843 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700844 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700845 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700846 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
847 if (hw == NULL) {
848 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700849 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700850 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
851 ALOGW("Attempt to set active config = %d for virtual display",
852 mMode);
853 } else {
854 mFlinger.setActiveConfigInternal(hw, mMode);
855 }
856 return true;
857 }
858 };
859 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
860 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700861 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700862}
Michael Wright28f24d02016-07-12 13:30:53 -0700863status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
864 Vector<android_color_mode_t>* outColorModes) {
865 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
866 return BAD_VALUE;
867 }
868
869 if (!display.get()) {
870 return NAME_NOT_FOUND;
871 }
872
873 int32_t type = NAME_NOT_FOUND;
874 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
875 if (display == mBuiltinDisplays[i]) {
876 type = i;
877 break;
878 }
879 }
880
881 if (type < 0) {
882 return type;
883 }
884
885 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
886 outColorModes->clear();
887 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
888
889 return NO_ERROR;
890}
891
892android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700893 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700894 if (device != nullptr) {
895 return device->getActiveColorMode();
896 }
897 return static_cast<android_color_mode_t>(BAD_VALUE);
898}
899
900void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
901 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700902 int32_t type = hw->getDisplayType();
903 android_color_mode_t currentMode = hw->getActiveColorMode();
904
905 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700906 return;
907 }
908
909 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
910 ALOGW("Trying to set config for virtual display");
911 return;
912 }
913
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600914 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
915 hw->getDisplayType());
916
Michael Wright28f24d02016-07-12 13:30:53 -0700917 hw->setActiveColorMode(mode);
918 getHwComposer().setActiveColorMode(type, mode);
919}
920
921
922status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
923 android_color_mode_t colorMode) {
924 class MessageSetActiveColorMode: public MessageBase {
925 SurfaceFlinger& mFlinger;
926 sp<IBinder> mDisplay;
927 android_color_mode_t mMode;
928 public:
929 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
930 android_color_mode_t mode) :
931 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
932 virtual bool handler() {
933 Vector<android_color_mode_t> modes;
934 mFlinger.getDisplayColorModes(mDisplay, &modes);
935 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
936 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600937 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
938 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700939 return true;
940 }
941 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
942 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600943 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
944 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700945 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600946 ALOGW("Attempt to set active color mode %s %d for virtual display",
947 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700948 } else {
949 mFlinger.setActiveColorModeInternal(hw, mMode);
950 }
951 return true;
952 }
953 };
954 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
955 postMessageSync(msg);
956 return NO_ERROR;
957}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700958
Svetoslavd85084b2014-03-20 10:28:31 -0700959status_t SurfaceFlinger::clearAnimationFrameStats() {
960 Mutex::Autolock _l(mStateLock);
961 mAnimFrameTracker.clearStats();
962 return NO_ERROR;
963}
964
965status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
966 Mutex::Autolock _l(mStateLock);
967 mAnimFrameTracker.getStats(outStats);
968 return NO_ERROR;
969}
970
Dan Stozac4f471e2016-03-24 09:31:08 -0700971status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
972 HdrCapabilities* outCapabilities) const {
973 Mutex::Autolock _l(mStateLock);
974
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700975 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700976 if (displayDevice == nullptr) {
977 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
978 return BAD_VALUE;
979 }
980
981 std::unique_ptr<HdrCapabilities> capabilities =
982 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
983 if (capabilities) {
984 std::swap(*outCapabilities, *capabilities);
985 } else {
986 return BAD_VALUE;
987 }
988
989 return NO_ERROR;
990}
991
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700992status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
993 if (enable == mInjectVSyncs) {
994 return NO_ERROR;
995 }
996
997 if (enable) {
998 mInjectVSyncs = enable;
999 ALOGV("VSync Injections enabled");
1000 if (mVSyncInjector.get() == nullptr) {
1001 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001002 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001003 }
1004 mEventQueue.setEventThread(mInjectorEventThread);
1005 } else {
1006 mInjectVSyncs = enable;
1007 ALOGV("VSync Injections disabled");
1008 mEventQueue.setEventThread(mSFEventThread);
1009 mVSyncInjector.clear();
1010 }
1011 return NO_ERROR;
1012}
1013
1014status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1015 if (!mInjectVSyncs) {
1016 ALOGE("VSync Injections not enabled");
1017 return BAD_VALUE;
1018 }
1019 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1020 ALOGV("Injecting VSync inside SurfaceFlinger");
1021 mVSyncInjector->onInjectSyncEvent(when);
1022 }
1023 return NO_ERROR;
1024}
1025
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001026// ----------------------------------------------------------------------------
1027
1028sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001029 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001030}
1031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001032// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001033
1034void SurfaceFlinger::waitForEvent() {
1035 mEventQueue.waitMessage();
1036}
1037
1038void SurfaceFlinger::signalTransaction() {
1039 mEventQueue.invalidate();
1040}
1041
1042void SurfaceFlinger::signalLayerUpdate() {
1043 mEventQueue.invalidate();
1044}
1045
1046void SurfaceFlinger::signalRefresh() {
1047 mEventQueue.refresh();
1048}
1049
1050status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001051 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001052 return mEventQueue.postMessage(msg, reltime);
1053}
1054
1055status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001056 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001057 status_t res = mEventQueue.postMessage(msg, reltime);
1058 if (res == NO_ERROR) {
1059 msg->wait();
1060 }
1061 return res;
1062}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001063
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001064void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001065 do {
1066 waitForEvent();
1067 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001068}
1069
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001070void SurfaceFlinger::enableHardwareVsync() {
1071 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001072 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001074 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1075 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001076 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001077 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078}
1079
Jesse Hall948fe0c2013-10-14 12:56:09 -07001080void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001081 Mutex::Autolock _l(mHWVsyncLock);
1082
Jesse Hall948fe0c2013-10-14 12:56:09 -07001083 if (makeAvailable) {
1084 mHWVsyncAvailable = true;
1085 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001086 // Hardware vsync is not currently available, so abort the resync
1087 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001088 return;
1089 }
1090
Dan Stoza9e56aa02015-11-02 13:00:03 -08001091 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1092 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001093
1094 mPrimaryDispSync.reset();
1095 mPrimaryDispSync.setPeriod(period);
1096
1097 if (!mPrimaryHWVsyncEnabled) {
1098 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001099 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1100 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001101 mPrimaryHWVsyncEnabled = true;
1102 }
1103}
1104
Jesse Hall948fe0c2013-10-14 12:56:09 -07001105void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106 Mutex::Autolock _l(mHWVsyncLock);
1107 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001108 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1109 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001110 mPrimaryDispSync.endResync();
1111 mPrimaryHWVsyncEnabled = false;
1112 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001113 if (makeUnavailable) {
1114 mHWVsyncAvailable = false;
1115 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116}
1117
Tim Murray4a4e4a22016-04-19 16:29:23 +00001118void SurfaceFlinger::resyncWithRateLimit() {
1119 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001120
1121 // No explicit locking is needed here since EventThread holds a lock while calling this method
1122 static nsecs_t sLastResyncAttempted = 0;
1123 const nsecs_t now = systemTime();
1124 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001125 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001126 }
Dan Stoza57164302017-05-08 14:03:54 -07001127 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001128}
1129
Steven Thomas3cfac282017-02-06 12:29:30 -08001130void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1131 nsecs_t timestamp) {
1132 Mutex::Autolock lock(mStateLock);
1133 // Ignore any vsyncs from the non-active hardware composer.
1134 if (composer != mHwc) {
1135 return;
1136 }
1137
Jamie Gennisd1700752013-10-14 12:22:52 -07001138 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001139
Jamie Gennisd1700752013-10-14 12:22:52 -07001140 { // Scope for the lock
1141 Mutex::Autolock _l(mHWVsyncLock);
1142 if (type == 0 && mPrimaryHWVsyncEnabled) {
1143 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001144 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001145 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001146
1147 if (needsHwVsync) {
1148 enableHardwareVsync();
1149 } else {
1150 disableHardwareVsync(false);
1151 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001152}
1153
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001154void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001155 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001156 *compositorTiming = mCompositorTiming;
1157}
1158
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001159void SurfaceFlinger::createDefaultDisplayDevice() {
1160 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1161 wp<IBinder> token = mBuiltinDisplays[type];
1162
1163 // All non-virtual displays are currently considered secure.
1164 const bool isSecure = true;
1165
1166 sp<IGraphicBufferProducer> producer;
1167 sp<IGraphicBufferConsumer> consumer;
1168 BufferQueue::createBufferQueue(&producer, &consumer);
1169
1170 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1171
1172 bool hasWideColorModes = false;
1173 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1174 for (android_color_mode_t colorMode : modes) {
1175 switch (colorMode) {
1176 case HAL_COLOR_MODE_DISPLAY_P3:
1177 case HAL_COLOR_MODE_ADOBE_RGB:
1178 case HAL_COLOR_MODE_DCI_P3:
1179 hasWideColorModes = true;
1180 break;
1181 default:
1182 break;
1183 }
1184 }
1185 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1186 token, fbs, producer, mRenderEngine->getEGLConfig(),
1187 hasWideColorModes && hasWideColorDisplay);
1188 mDisplays.add(token, hw);
1189 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1190 if (hasWideColorModes && hasWideColorDisplay) {
1191 defaultColorMode = HAL_COLOR_MODE_SRGB;
1192 }
1193 setActiveColorModeInternal(hw, defaultColorMode);
1194}
1195
1196void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001197 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001198
1199 if (composer->isUsingVrComposer()) {
1200 // We handle initializing the primary display device for the VR
1201 // window manager hwc explicitly at the time of transition.
1202 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1203 ALOGE("External displays are not supported by the vr hardware composer.");
1204 }
1205 return;
1206 }
1207
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1209 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001210 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1211 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001212 } else {
1213 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001214 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001215 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001216 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001217 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001218 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1219 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001220 }
1221 setTransactionFlags(eDisplayTransactionNeeded);
1222
Andy McFadden9e9689c2012-10-10 18:17:51 -07001223 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001224 }
Mathias Agopian86303202012-07-24 22:46:10 -07001225}
1226
Steven Thomas3cfac282017-02-06 12:29:30 -08001227void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1228 Mutex::Autolock lock(mStateLock);
1229 if (composer == mHwc) {
1230 repaintEverything();
1231 } else {
1232 // This isn't from our current hardware composer. If it's a callback
1233 // from the real composer, forward the refresh request to vr
1234 // flinger. Otherwise ignore it.
1235 if (!composer->isUsingVrComposer()) {
1236 mVrFlinger->OnHardwareComposerRefresh();
1237 }
1238 }
1239}
1240
Dan Stoza9e56aa02015-11-02 13:00:03 -08001241void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001242 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001243 getHwComposer().setVsyncEnabled(disp,
1244 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001245}
1246
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001247void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1248 for (size_t i = 0; i < layers.size(); ++i) {
1249 layers[i]->clearHwcLayers();
1250 }
1251}
1252
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001253// Note: it is assumed the caller holds |mStateLock| when this is called
1254void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001255 disableHardwareVsync(true);
1256 clearHwcLayers(mDrawingState.layersSortedByZ);
1257 clearHwcLayers(mCurrentState.layersSortedByZ);
1258 // Clear the drawing state so that the logic inside of
1259 // handleTransactionLocked will fire. It will determine the delta between
1260 // mCurrentState and mDrawingState and re-apply all changes when we make the
1261 // transition.
1262 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001263 // Release virtual display hwcId during vr mode transition.
1264 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1265 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1266 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1267 displayDevice->disconnect(getHwComposer());
1268 }
1269 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001270 mDisplays.clear();
1271}
1272
Steven Thomas050b2c82017-03-06 11:45:16 -08001273void SurfaceFlinger::updateVrFlinger() {
1274 if (!mVrFlinger)
1275 return;
1276 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1277 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001278 return;
1279 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001280
Steven Thomas050b2c82017-03-06 11:45:16 -08001281 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001282 // Construct new HWComposer without holding any locks.
1283 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284
1285 // Set up the event handlers. This step is neccessary to initialize the internal state of
1286 // the hardware composer object properly. Our callbacks are designed such that if they are
1287 // triggered between now and the point where the display is properly re-initialized, they
1288 // will not have any effect, so this is safe to do here, before the lock is aquired.
1289 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001290 ALOGV("Vr HWC created");
1291 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001292
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001293 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001294
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001295 if (vrFlingerRequestsDisplay) {
1296 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001297
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001298 mHwc = mVrHwc;
1299 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001300
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301 } else {
1302 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001303
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304 resetHwcLocked();
1305
1306 mHwc = mRealHwc;
1307 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001309
1310 mVisibleRegionsDirty = true;
1311 invalidateHwcGeometry();
1312
1313 // Explicitly re-initialize the primary display. This is because some other
1314 // parts of this class rely on the primary display always being available.
1315 createDefaultDisplayDevice();
1316
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001317 // Reset the timing values to account for the period of the swapped in HWC
1318 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1319 const nsecs_t period = activeConfig->getVsyncPeriod();
1320 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1321 setCompositorTimingSnapped(0, period, 0);
1322
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001323 android_atomic_or(1, &mRepaintEverything);
1324 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001325}
1326
Mathias Agopian4fec8732012-06-29 14:12:52 -07001327void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001328 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001329 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001330 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001331 bool frameMissed = !mHadClientComposition &&
1332 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001333 (mPreviousPresentFence->getSignalTime() ==
1334 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001335 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001336 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001337 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001338 signalLayerUpdate();
1339 break;
1340 }
1341
Steven Thomas050b2c82017-03-06 11:45:16 -08001342 // Now that we're going to make it to the handleMessageTransaction()
1343 // call below it's safe to call updateVrFlinger(), which will
1344 // potentially trigger a display handoff.
1345 updateVrFlinger();
1346
Dan Stoza6b9454d2014-11-07 16:00:59 -08001347 bool refreshNeeded = handleMessageTransaction();
1348 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001349 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001350 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001351 // Signal a refresh if a transaction modified the window state,
1352 // a new buffer was latched, or if HWC has requested a full
1353 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001354 signalRefresh();
1355 }
1356 break;
1357 }
1358 case MessageQueue::REFRESH: {
1359 handleMessageRefresh();
1360 break;
1361 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001362 }
1363}
1364
Dan Stoza6b9454d2014-11-07 16:00:59 -08001365bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001366 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001367 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001368 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001369 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001370 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001371 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001372}
1373
Dan Stoza6b9454d2014-11-07 16:00:59 -08001374bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001375 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001376 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001377}
1378
1379void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001380 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001381
Pablo Ceballos40845df2016-01-25 17:41:15 -08001382 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001383
Brian Andersond6927fb2016-07-23 23:37:30 -07001384 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001385 rebuildLayerStacks();
1386 setUpHWComposer();
1387 doDebugFlashRegions();
1388 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001389 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001390
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001391 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001392
1393 mHadClientComposition = false;
1394 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1395 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1396 mHadClientComposition = mHadClientComposition ||
1397 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1398 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001399
Dan Stoza9e56aa02015-11-02 13:00:03 -08001400 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001401}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001402
Mathias Agopiancd60f992012-08-16 16:28:27 -07001403void SurfaceFlinger::doDebugFlashRegions()
1404{
1405 // is debugging enabled
1406 if (CC_LIKELY(!mDebugRegion))
1407 return;
1408
1409 const bool repaintEverything = mRepaintEverything;
1410 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1411 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001412 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001413 // transform the dirty region into this screen's coordinate space
1414 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1415 if (!dirtyRegion.isEmpty()) {
1416 // redraw the whole screen
1417 doComposeSurfaces(hw, Region(hw->bounds()));
1418
1419 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001420 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001421 RenderEngine& engine(getRenderEngine());
1422 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1423
Mathias Agopianda27af92012-09-13 18:17:13 -07001424 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001425 }
1426 }
1427 }
1428
1429 postFramebuffer();
1430
1431 if (mDebugRegion > 1) {
1432 usleep(mDebugRegion * 1000);
1433 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001434
Dan Stoza9e56aa02015-11-02 13:00:03 -08001435 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001436 auto& displayDevice = mDisplays[displayId];
1437 if (!displayDevice->isDisplayOn()) {
1438 continue;
1439 }
1440
1441 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001442 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1443 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001444 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445}
1446
Brian Andersond6927fb2016-07-23 23:37:30 -07001447void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001448{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001449 ATRACE_CALL();
1450 ALOGV("preComposition");
1451
Mathias Agopiancd60f992012-08-16 16:28:27 -07001452 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001453 mDrawingState.traverseInZOrder([&](Layer* layer) {
1454 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001455 needExtraInvalidate = true;
1456 }
Robert Carr2047fae2016-11-28 14:09:09 -08001457 });
1458
Mathias Agopiancd60f992012-08-16 16:28:27 -07001459 if (needExtraInvalidate) {
1460 signalLayerUpdate();
1461 }
1462}
1463
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001464void SurfaceFlinger::updateCompositorTiming(
1465 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1466 std::shared_ptr<FenceTime>& presentFenceTime) {
1467 // Update queue of past composite+present times and determine the
1468 // most recently known composite to present latency.
1469 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1470 nsecs_t compositeToPresentLatency = -1;
1471 while (!mCompositePresentTimes.empty()) {
1472 CompositePresentTime& cpt = mCompositePresentTimes.front();
1473 // Cached values should have been updated before calling this method,
1474 // which helps avoid duplicate syscalls.
1475 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1476 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1477 break;
1478 }
1479 compositeToPresentLatency = displayTime - cpt.composite;
1480 mCompositePresentTimes.pop();
1481 }
1482
1483 // Don't let mCompositePresentTimes grow unbounded, just in case.
1484 while (mCompositePresentTimes.size() > 16) {
1485 mCompositePresentTimes.pop();
1486 }
1487
Brian Andersond0010582017-03-07 13:20:31 -08001488 setCompositorTimingSnapped(
1489 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1490}
1491
1492void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1493 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001494 // Integer division and modulo round toward 0 not -inf, so we need to
1495 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001496 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001497 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1498 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1499
Brian Andersond0010582017-03-07 13:20:31 -08001500 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1501 if (idealLatency <= 0) {
1502 idealLatency = vsyncInterval;
1503 }
1504
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505 // Snap the latency to a value that removes scheduling jitter from the
1506 // composition and present times, which often have >1ms of jitter.
1507 // Reducing jitter is important if an app attempts to extrapolate
1508 // something (such as user input) to an accurate diasplay time.
1509 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1510 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001511 nsecs_t bias = vsyncInterval / 2;
1512 int64_t extraVsyncs =
1513 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1514 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1515 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001516
Brian Andersond0010582017-03-07 13:20:31 -08001517 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001518 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1519 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001520 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521}
1522
1523void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001525 ATRACE_CALL();
1526 ALOGV("postComposition");
1527
Brian Anderson3546a3f2016-07-14 11:51:14 -07001528 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001529 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001530 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001531 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001532 }
1533
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001534 // |mStateLock| not needed as we are on the main thread
1535 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001536
1537 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1538 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1539 glCompositionDoneFenceTime =
1540 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1541 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1542 } else {
1543 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1544 }
1545 mGlCompositionDoneTimeline.updateSignalTimes();
1546
Brian Anderson4e606e32017-03-16 15:34:57 -07001547 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1548 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1549 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001550 mDisplayTimeline.updateSignalTimes();
1551
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001552 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1553 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1554
1555 // We use the refreshStartTime which might be sampled a little later than
1556 // when we started doing work for this frame, but that should be okay
1557 // since updateCompositorTiming has snapping logic.
1558 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001559 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001560 CompositorTiming compositorTiming;
1561 {
1562 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1563 compositorTiming = mCompositorTiming;
1564 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565
Robert Carr2047fae2016-11-28 14:09:09 -08001566 mDrawingState.traverseInZOrder([&](Layer* layer) {
1567 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001568 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001569 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001570 recordBufferingStats(layer->getName().string(),
1571 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001572 }
Robert Carr2047fae2016-11-28 14:09:09 -08001573 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001574
Brian Anderson4e606e32017-03-16 15:34:57 -07001575 if (presentFence->isValid()) {
1576 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001577 enableHardwareVsync();
1578 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001579 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001580 }
1581 }
1582
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001583 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001584 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001585 enableHardwareVsync();
1586 }
1587 }
1588
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001589 if (mAnimCompositionPending) {
1590 mAnimCompositionPending = false;
1591
Brian Anderson4e606e32017-03-16 15:34:57 -07001592 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001593 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001594 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001595 } else {
1596 // The HWC doesn't support present fences, so use the refresh
1597 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001598 nsecs_t presentTime =
1599 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001600 mAnimFrameTracker.setActualPresentTime(presentTime);
1601 }
1602 mAnimFrameTracker.advanceFrame();
1603 }
Dan Stozab90cf072015-03-05 11:05:59 -08001604
1605 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1606 return;
1607 }
1608
1609 nsecs_t currentTime = systemTime();
1610 if (mHasPoweredOff) {
1611 mHasPoweredOff = false;
1612 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001613 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001614 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001615 if (numPeriods < NUM_BUCKETS - 1) {
1616 mFrameBuckets[numPeriods] += elapsedTime;
1617 } else {
1618 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1619 }
1620 mTotalTime += elapsedTime;
1621 }
1622 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001623}
1624
1625void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001626 ATRACE_CALL();
1627 ALOGV("rebuildLayerStacks");
1628
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001630 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1631 ATRACE_CALL();
1632 mVisibleRegionsDirty = false;
1633 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001634
Jeff Sharkey76488112017-02-27 14:15:18 -07001635 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1636 Region opaqueRegion;
1637 Region dirtyRegion;
1638 Vector<sp<Layer>> layersSortedByZ;
1639 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1640 const Transform& tr(displayDevice->getTransform());
1641 const Rect bounds(displayDevice->getBounds());
1642 if (displayDevice->isDisplayOn()) {
1643 computeVisibleRegions(
1644 displayDevice->getLayerStack(), dirtyRegion,
1645 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001646
Jeff Sharkey76488112017-02-27 14:15:18 -07001647 mDrawingState.traverseInZOrder([&](Layer* layer) {
1648 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1649 Region drawRegion(tr.transform(
1650 layer->visibleNonTransparentRegion));
1651 drawRegion.andSelf(bounds);
1652 if (!drawRegion.isEmpty()) {
1653 layersSortedByZ.add(layer);
1654 } else {
1655 // Clear out the HWC layer if this layer was
1656 // previously visible, but no longer is
1657 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1658 nullptr);
1659 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001660 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001661 // WM changes displayDevice->layerStack upon sleep/awake.
1662 // Here we make sure we delete the HWC layers even if
1663 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001664 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1665 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001666 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001667 });
1668 }
1669 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1670 displayDevice->undefinedRegion.set(bounds);
1671 displayDevice->undefinedRegion.subtractSelf(
1672 tr.transform(opaqueRegion));
1673 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001674 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001675 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001676}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001677
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001678// pickColorMode translates a given dataspace into the best available color mode.
1679// Currently only support sRGB and Display-P3.
1680android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) {
1681 switch (dataSpace) {
1682 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1683 // system expects.
1684 case HAL_DATASPACE_UNKNOWN:
1685 case HAL_DATASPACE_SRGB:
1686 case HAL_DATASPACE_V0_SRGB:
1687 return HAL_COLOR_MODE_SRGB;
1688 break;
1689
1690 case HAL_DATASPACE_DISPLAY_P3:
1691 return HAL_COLOR_MODE_DISPLAY_P3;
1692 break;
1693
1694 default:
1695 // TODO (courtneygo): Do we want to assert an error here?
1696 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1697 dataSpace);
1698 return HAL_COLOR_MODE_SRGB;
1699 break;
1700 }
1701}
1702
1703android_dataspace SurfaceFlinger::bestTargetDataSpace(android_dataspace a, android_dataspace b) {
1704 // Only support sRGB and Display-P3 right now.
1705 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1706 return HAL_DATASPACE_DISPLAY_P3;
1707 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001708 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1709 return HAL_DATASPACE_DISPLAY_P3;
1710 }
1711 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1712 return HAL_DATASPACE_DISPLAY_P3;
1713 }
1714
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001715 return HAL_DATASPACE_V0_SRGB;
1716}
1717
Mathias Agopiancd60f992012-08-16 16:28:27 -07001718void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001719 ATRACE_CALL();
1720 ALOGV("setUpHWComposer");
1721
Jesse Hall028dc8f2013-08-20 16:35:32 -07001722 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001723 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1724 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1725 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1726
1727 // If nothing has changed (!dirty), don't recompose.
1728 // If something changed, but we don't currently have any visible layers,
1729 // and didn't when we last did a composition, then skip it this time.
1730 // The second rule does two things:
1731 // - When all layers are removed from a display, we'll emit one black
1732 // frame, then nothing more until we get new layers.
1733 // - When a display is created with a private layer stack, we won't
1734 // emit any black frames until a layer is added to the layer stack.
1735 bool mustRecompose = dirty && !(empty && wasEmpty);
1736
1737 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1738 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1739 mustRecompose ? "doing" : "skipping",
1740 dirty ? "+" : "-",
1741 empty ? "+" : "-",
1742 wasEmpty ? "+" : "-");
1743
Dan Stoza71433162014-02-04 16:22:36 -08001744 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001745
1746 if (mustRecompose) {
1747 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1748 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001749 }
1750
Dan Stoza9e56aa02015-11-02 13:00:03 -08001751 // build the h/w work list
1752 if (CC_UNLIKELY(mGeometryInvalid)) {
1753 mGeometryInvalid = false;
1754 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1755 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1756 const auto hwcId = displayDevice->getHwcDisplayId();
1757 if (hwcId >= 0) {
1758 const Vector<sp<Layer>>& currentLayers(
1759 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001760 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001761 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001762 if (!layer->hasHwcLayer(hwcId)) {
1763 auto hwcLayer = mHwc->createLayer(hwcId);
1764 if (hwcLayer) {
1765 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1766 } else {
1767 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001768 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001769 }
1770 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001771
Robert Carrae060832016-11-28 10:51:00 -08001772 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001773 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001774 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001775 }
1776 }
1777 }
1778 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 }
Riley Andrews03414a12014-07-01 14:22:59 -07001780
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001781
1782 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1783
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784 // Set the per-frame data
1785 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1786 auto& displayDevice = mDisplays[displayId];
1787 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001788
Dan Stoza9e56aa02015-11-02 13:00:03 -08001789 if (hwcId < 0) {
1790 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001791 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001792 if (colorMatrix != mPreviousColorMatrix) {
1793 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1794 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1795 "display %zd: %d", displayId, result);
1796 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001797 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1798 layer->setPerFrameData(displayDevice);
1799 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001800
1801 if (hasWideColorDisplay) {
1802 android_color_mode newColorMode;
1803 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1804
1805 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1806 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1807 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1808 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1809 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1810 }
1811 newColorMode = pickColorMode(newDataSpace);
1812
1813 setActiveColorModeInternal(displayDevice, newColorMode);
1814 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001815 }
1816
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001817 mPreviousColorMatrix = colorMatrix;
1818
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001820 auto& displayDevice = mDisplays[displayId];
1821 if (!displayDevice->isDisplayOn()) {
1822 continue;
1823 }
1824
1825 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1827 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001828 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001830
Mathias Agopiancd60f992012-08-16 16:28:27 -07001831void SurfaceFlinger::doComposition() {
1832 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001833 ALOGV("doComposition");
1834
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001835 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001836 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001837 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001838 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839 // transform the dirty region into this screen's coordinate space
1840 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001841
1842 // repaint the framebuffer (if needed)
1843 doDisplayComposition(hw, dirtyRegion);
1844
Mathias Agopiancd60f992012-08-16 16:28:27 -07001845 hw->dirtyRegion.clear();
1846 hw->flip(hw->swapRegion);
1847 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001848 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001849 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001850 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001851}
1852
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853void SurfaceFlinger::postFramebuffer()
1854{
Mathias Agopian841cde52012-03-01 15:44:37 -08001855 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001856 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001857
Mathias Agopiana44b0412011-10-16 18:46:35 -07001858 const nsecs_t now = systemTime();
1859 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001860
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1862 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001863 if (!displayDevice->isDisplayOn()) {
1864 continue;
1865 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 const auto hwcId = displayDevice->getHwcDisplayId();
1867 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001868 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001869 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001870 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001871 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1873 sp<Fence> releaseFence = Fence::NO_FENCE;
1874 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1875 releaseFence = displayDevice->getClientTargetAcquireFence();
1876 } else {
1877 auto hwcLayer = layer->getHwcLayer(hwcId);
1878 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001879 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 layer->onLayerDisplayed(releaseFence);
1881 }
1882 if (hwcId >= 0) {
1883 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001884 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001885 }
1886
Mathias Agopiana44b0412011-10-16 18:46:35 -07001887 mLastSwapBufferTime = systemTime() - now;
1888 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001889
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001890 // |mStateLock| not needed as we are on the main thread
1891 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001892 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1893 logFrameStats();
1894 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001895}
1896
Mathias Agopian87baae12012-07-31 12:38:26 -07001897void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001898{
Mathias Agopian841cde52012-03-01 15:44:37 -08001899 ATRACE_CALL();
1900
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001901 // here we keep a copy of the drawing state (that is the state that's
1902 // going to be overwritten by handleTransactionLocked()) outside of
1903 // mStateLock so that the side-effects of the State assignment
1904 // don't happen with mStateLock held (which can cause deadlocks).
1905 State drawingState(mDrawingState);
1906
Mathias Agopianca4d3602011-05-19 15:38:14 -07001907 Mutex::Autolock _l(mStateLock);
1908 const nsecs_t now = systemTime();
1909 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001910
Mathias Agopianca4d3602011-05-19 15:38:14 -07001911 // Here we're guaranteed that some transaction flags are set
1912 // so we can call handleTransactionLocked() unconditionally.
1913 // We call getTransactionFlags(), which will also clear the flags,
1914 // with mStateLock held to guarantee that mCurrentState won't change
1915 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001916
Mathias Agopiane57f2922012-08-09 16:29:12 -07001917 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001918 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001919
Mathias Agopianca4d3602011-05-19 15:38:14 -07001920 mLastTransactionTime = systemTime() - now;
1921 mDebugInTransaction = 0;
1922 invalidateHwcGeometry();
1923 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001924}
1925
Mathias Agopian87baae12012-07-31 12:38:26 -07001926void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001927{
Dan Stoza7dde5992015-05-22 09:51:44 -07001928 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001929 mCurrentState.traverseInZOrder([](Layer* layer) {
1930 layer->notifyAvailableFrames();
1931 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001932
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001933 /*
1934 * Traversal of the children
1935 * (perform the transaction for each of them if needed)
1936 */
1937
Mathias Agopian3559b072012-08-15 13:46:03 -07001938 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001939 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001940 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001941 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001942
1943 const uint32_t flags = layer->doTransaction(0);
1944 if (flags & Layer::eVisibleRegion)
1945 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001946 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947 }
1948
1949 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001950 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001951 */
1952
Mathias Agopiane57f2922012-08-09 16:29:12 -07001953 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001954 // here we take advantage of Vector's copy-on-write semantics to
1955 // improve performance by skipping the transaction entirely when
1956 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001957 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1958 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001959 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001960 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001961 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001962 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001963
1964 // find the displays that were removed
1965 // (ie: in drawing state but not in current state)
1966 // also handle displays that changed
1967 // (ie: displays that are in both lists)
1968 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001969 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1970 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001971 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001972 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001973 // Call makeCurrent() on the primary display so we can
1974 // be sure that nothing associated with this display
1975 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001976 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001977 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001978 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07001979 if (hw != NULL)
1980 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001981 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001982 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001983 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001984 } else {
1985 ALOGW("trying to remove the main display");
1986 }
1987 } else {
1988 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001989 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001990 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001991 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1992 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001993 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001994 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001995 // recreating the DisplayDevice, so we just remove it
1996 // from the drawing state, so that it get re-added
1997 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001998 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07001999 if (hw != NULL)
2000 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002001 mDisplays.removeItem(display);
2002 mDrawingState.displays.removeItemsAt(i);
2003 dc--; i--;
2004 // at this point we must loop to the next item
2005 continue;
2006 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002007
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002008 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002009 if (disp != NULL) {
2010 if (state.layerStack != draw[i].layerStack) {
2011 disp->setLayerStack(state.layerStack);
2012 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002013 if ((state.orientation != draw[i].orientation)
2014 || (state.viewport != draw[i].viewport)
2015 || (state.frame != draw[i].frame))
2016 {
2017 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002018 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002019 }
Michael Lentine47e45402014-07-18 15:34:25 -07002020 if (state.width != draw[i].width || state.height != draw[i].height) {
2021 disp->setDisplaySize(state.width, state.height);
2022 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002023 }
2024 }
2025 }
2026
2027 // find displays that were added
2028 // (ie: in current state but not in drawing state)
2029 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002030 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002031 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002032
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002033 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002034 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002035 sp<IGraphicBufferProducer> bqProducer;
2036 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002037 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002038
Dan Stoza9e56aa02015-11-02 13:00:03 -08002039 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002040 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002041 // Virtual displays without a surface are dormant:
2042 // they have external state (layer stack, projection,
2043 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002044 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002045
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002046 // Allow VR composer to use virtual displays.
2047 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002048 int width = 0;
2049 int status = state.surface->query(
2050 NATIVE_WINDOW_WIDTH, &width);
2051 ALOGE_IF(status != NO_ERROR,
2052 "Unable to query width (%d)", status);
2053 int height = 0;
2054 status = state.surface->query(
2055 NATIVE_WINDOW_HEIGHT, &height);
2056 ALOGE_IF(status != NO_ERROR,
2057 "Unable to query height (%d)", status);
2058 int intFormat = 0;
2059 status = state.surface->query(
2060 NATIVE_WINDOW_FORMAT, &intFormat);
2061 ALOGE_IF(status != NO_ERROR,
2062 "Unable to query format (%d)", status);
2063 auto format = static_cast<android_pixel_format_t>(
2064 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002065
Dan Stoza8cf150a2016-08-02 10:27:31 -07002066 mHwc->allocateVirtualDisplay(width, height, &format,
2067 &hwcId);
2068 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002069
Dan Stoza5cf424b2016-05-20 14:02:39 -07002070 // TODO: Plumb requested format back up to consumer
2071
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 sp<VirtualDisplaySurface> vds =
2073 new VirtualDisplaySurface(*mHwc,
2074 hwcId, state.surface, bqProducer,
2075 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002076
2077 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002078 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002079 }
2080 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002081 ALOGE_IF(state.surface!=NULL,
2082 "adding a supported display, but rendering "
2083 "surface is provided (%p), ignoring it",
2084 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002085
2086 hwcId = state.type;
2087 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2088 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002089 }
2090
2091 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002092 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002093 sp<DisplayDevice> hw =
2094 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2095 dispSurface, producer,
2096 mRenderEngine->getEGLConfig(),
2097 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002098 hw->setLayerStack(state.layerStack);
2099 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002100 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002101 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002102 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002103 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002104 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002105 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002106 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002107 }
2108 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002110 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002111
Mathias Agopian84300952012-11-21 16:02:13 -08002112 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2113 // The transform hint might have changed for some layers
2114 // (either because a display has changed, or because a layer
2115 // as changed).
2116 //
2117 // Walk through all the layers in currentLayers,
2118 // and update their transform hint.
2119 //
2120 // If a layer is visible only on a single display, then that
2121 // display is used to calculate the hint, otherwise we use the
2122 // default display.
2123 //
2124 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2125 // the hint is set before we acquire a buffer from the surface texture.
2126 //
2127 // NOTE: layer transactions have taken place already, so we use their
2128 // drawing state. However, SurfaceFlinger's own transaction has not
2129 // happened yet, so we must use the current state layer list
2130 // (soon to become the drawing state list).
2131 //
2132 sp<const DisplayDevice> disp;
2133 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002134 bool first = true;
2135 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002136 // NOTE: we rely on the fact that layers are sorted by
2137 // layerStack first (so we don't have to traverse the list
2138 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002139 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002140 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002141 currentlayerStack = layerStack;
2142 // figure out if this layerstack is mirrored
2143 // (more than one display) if so, pick the default display,
2144 // if not, pick the only display it's on.
2145 disp.clear();
2146 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2147 sp<const DisplayDevice> hw(mDisplays[dpy]);
2148 if (hw->getLayerStack() == currentlayerStack) {
2149 if (disp == NULL) {
2150 disp = hw;
2151 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002152 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002153 break;
2154 }
2155 }
2156 }
2157 }
Chet Haase91d25932013-04-11 15:24:55 -07002158 if (disp == NULL) {
2159 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2160 // redraw after transform hint changes. See bug 8508397.
2161
2162 // could be null when this layer is using a layerStack
2163 // that is not visible on any display. Also can occur at
2164 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002165 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002166 }
Chet Haase91d25932013-04-11 15:24:55 -07002167 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002168
2169 first = false;
2170 });
Mathias Agopian84300952012-11-21 16:02:13 -08002171 }
2172
2173
Mathias Agopian3559b072012-08-15 13:46:03 -07002174 /*
2175 * Perform our own transaction if needed
2176 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002177
2178 if (mLayersAdded) {
2179 mLayersAdded = false;
2180 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002181 mVisibleRegionsDirty = true;
2182 }
2183
2184 // some layers might have been removed, so
2185 // we need to update the regions they're exposing.
2186 if (mLayersRemoved) {
2187 mLayersRemoved = false;
2188 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002189 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002190 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002191 // this layer is not visible anymore
2192 // TODO: we could traverse the tree from front to back and
2193 // compute the actual visible region
2194 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002195 Region visibleReg;
2196 visibleReg.set(layer->computeScreenBounds());
2197 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002198 }
Robert Carr2047fae2016-11-28 14:09:09 -08002199 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002200 }
2201
2202 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002203
2204 updateCursorAsync();
2205}
2206
2207void SurfaceFlinger::updateCursorAsync()
2208{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002209 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2210 auto& displayDevice = mDisplays[displayId];
2211 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002212 continue;
2213 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002214
2215 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2216 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002217 }
2218 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002219}
2220
2221void SurfaceFlinger::commitTransaction()
2222{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002223 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002224 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002225 for (const auto& l : mLayersPendingRemoval) {
2226 recordBufferingStats(l->getName().string(),
2227 l->getOccupancyHistory(true));
2228 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002229 }
2230 mLayersPendingRemoval.clear();
2231 }
2232
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002233 // If this transaction is part of a window animation then the next frame
2234 // we composite should be considered an animation as well.
2235 mAnimCompositionPending = mAnimTransactionPending;
2236
Mathias Agopian4fec8732012-06-29 14:12:52 -07002237 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002238 mDrawingState.traverseInZOrder([](Layer* layer) {
2239 layer->commitChildList();
2240 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002241 mTransactionPending = false;
2242 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002243 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244}
2245
Robert Carr2047fae2016-11-28 14:09:09 -08002246void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002247 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248{
Mathias Agopian841cde52012-03-01 15:44:37 -08002249 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002250 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002251
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252 Region aboveOpaqueLayers;
2253 Region aboveCoveredLayers;
2254 Region dirty;
2255
Mathias Agopian87baae12012-07-31 12:38:26 -07002256 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002257
Robert Carr2047fae2016-11-28 14:09:09 -08002258 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002259 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002260 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002261
Jesse Hall01e29052013-02-19 16:13:35 -08002262 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002263 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002264 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002265
Mathias Agopianab028732010-03-16 16:41:46 -07002266 /*
2267 * opaqueRegion: area of a surface that is fully opaque.
2268 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002270
2271 /*
2272 * visibleRegion: area of a surface that is visible on screen
2273 * and not fully transparent. This is essentially the layer's
2274 * footprint minus the opaque regions above it.
2275 * Areas covered by a translucent surface are considered visible.
2276 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002277 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002278
2279 /*
2280 * coveredRegion: area of a surface that is covered by all
2281 * visible regions above it (which includes the translucent areas).
2282 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002284
Jesse Halla8026d22012-09-25 13:25:04 -07002285 /*
2286 * transparentRegion: area of a surface that is hinted to be completely
2287 * transparent. This is only used to tell when the layer has no visible
2288 * non-transparent regions and can be removed from the layer list. It
2289 * does not affect the visibleRegion of this layer or any layers
2290 * beneath it. The hint may not be correct if apps don't respect the
2291 * SurfaceView restrictions (which, sadly, some don't).
2292 */
2293 Region transparentRegion;
2294
Mathias Agopianab028732010-03-16 16:41:46 -07002295
2296 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002297 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002298 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002299 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002302 if (!visibleRegion.isEmpty()) {
2303 // Remove the transparent area from the visible region
2304 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002305 if (tr.preserveRects()) {
2306 // transform the transparent region
2307 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002308 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002309 // transformation too complex, can't do the
2310 // transparent region optimization.
2311 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002312 }
Mathias Agopianab028732010-03-16 16:41:46 -07002313 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314
Mathias Agopianab028732010-03-16 16:41:46 -07002315 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002316 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002317 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002318 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2319 // the opaque region is the layer's footprint
2320 opaqueRegion = visibleRegion;
2321 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002322 }
2323 }
2324
Mathias Agopianab028732010-03-16 16:41:46 -07002325 // Clip the covered region to the visible region
2326 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2327
2328 // Update aboveCoveredLayers for next (lower) layer
2329 aboveCoveredLayers.orSelf(visibleRegion);
2330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331 // subtract the opaque region covered by the layers above us
2332 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333
2334 // compute this layer's dirty region
2335 if (layer->contentDirty) {
2336 // we need to invalidate the whole region
2337 dirty = visibleRegion;
2338 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002339 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340 layer->contentDirty = false;
2341 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002342 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002343 * the exposed region consists of two components:
2344 * 1) what's VISIBLE now and was COVERED before
2345 * 2) what's EXPOSED now less what was EXPOSED before
2346 *
2347 * note that (1) is conservative, we start with the whole
2348 * visible region but only keep what used to be covered by
2349 * something -- which mean it may have been exposed.
2350 *
2351 * (2) handles areas that were not covered by anything but got
2352 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002353 */
Mathias Agopianab028732010-03-16 16:41:46 -07002354 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002355 const Region oldVisibleRegion = layer->visibleRegion;
2356 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002357 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2358 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 }
2360 dirty.subtractSelf(aboveOpaqueLayers);
2361
2362 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002363 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364
Mathias Agopianab028732010-03-16 16:41:46 -07002365 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002367
Jesse Halla8026d22012-09-25 13:25:04 -07002368 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 layer->setVisibleRegion(visibleRegion);
2370 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002371 layer->setVisibleNonTransparentRegion(
2372 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002373 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374
Mathias Agopian87baae12012-07-31 12:38:26 -07002375 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376}
2377
Mathias Agopian87baae12012-07-31 12:38:26 -07002378void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2379 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002380 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002381 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2382 if (hw->getLayerStack() == layerStack) {
2383 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002384 }
2385 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002386}
2387
Dan Stoza6b9454d2014-11-07 16:00:59 -08002388bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002390 ALOGV("handlePageFlip");
2391
Brian Andersond6927fb2016-07-23 23:37:30 -07002392 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002393
Mathias Agopian4fec8732012-06-29 14:12:52 -07002394 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002395 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002396 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002397
2398 // Store the set of layers that need updates. This set must not change as
2399 // buffers are being latched, as this could result in a deadlock.
2400 // Example: Two producers share the same command stream and:
2401 // 1.) Layer 0 is latched
2402 // 2.) Layer 0 gets a new frame
2403 // 2.) Layer 1 gets a new frame
2404 // 3.) Layer 1 is latched.
2405 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2406 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002407 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002408 if (layer->hasQueuedFrame()) {
2409 frameQueued = true;
2410 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002411 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002412 } else {
2413 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002414 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002415 } else {
2416 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002417 }
Robert Carr2047fae2016-11-28 14:09:09 -08002418 });
2419
Dan Stoza9e56aa02015-11-02 13:00:03 -08002420 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002421 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002422 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002423 invalidateLayerStack(layer->getLayerStack(), dirty);
Mike Stroyan0cd76192017-04-20 12:10:48 -06002424 if (!dirty.isEmpty()) {
2425 newDataLatched = true;
2426 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002428
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002429 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002430
2431 // If we will need to wake up at some time in the future to deal with a
2432 // queued frame that shouldn't be displayed during this vsync period, wake
2433 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002434 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002435 signalLayerUpdate();
2436 }
2437
2438 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002439 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440}
2441
Mathias Agopianad456f92011-01-13 17:53:01 -08002442void SurfaceFlinger::invalidateHwcGeometry()
2443{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002444 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002445}
2446
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002447
Fabien Sanglard830b8472016-11-30 16:35:58 -08002448void SurfaceFlinger::doDisplayComposition(
2449 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002450 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451{
Dan Stoza71433162014-02-04 16:22:36 -08002452 // We only need to actually compose the display if:
2453 // 1) It is being handled by hardware composer, which may need this to
2454 // keep its virtual display state machine in sync, or
2455 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002456 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002457 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002459 return;
2460 }
2461
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 ALOGV("doDisplayComposition");
2463
Mathias Agopian87baae12012-07-31 12:38:26 -07002464 Region dirtyRegion(inDirtyRegion);
2465
Mathias Agopianb8a55602009-06-26 19:06:36 -07002466 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002467 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468
Fabien Sanglard830b8472016-11-30 16:35:58 -08002469 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002470 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002471 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2472 // takes a rectangle, we must make sure to update that whole
2473 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002474 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002475 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002476 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002477 // We need to redraw the rectangle that will be updated
2478 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002479 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002480 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002481 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002482 } else {
2483 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002484 dirtyRegion.set(displayDevice->bounds());
2485 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486 }
2487 }
2488
Fabien Sanglard830b8472016-11-30 16:35:58 -08002489 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002490
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002491 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002492 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002493
2494 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002495 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496}
2497
Dan Stoza9e56aa02015-11-02 13:00:03 -08002498bool SurfaceFlinger::doComposeSurfaces(
2499 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002500{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002502
Dan Stoza9e56aa02015-11-02 13:00:03 -08002503 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002504
2505 mat4 oldColorMatrix;
2506 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2507 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2508 if (applyColorMatrix) {
2509 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2510 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2511 }
2512
Dan Stoza9e56aa02015-11-02 13:00:03 -08002513 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2514 if (hasClientComposition) {
2515 ALOGV("hasClientComposition");
2516
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002517#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002518 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002519 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002520#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002521 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002522 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002523 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002524 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002525
2526 // |mStateLock| not needed as we are on the main thread
2527 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002528 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2529 }
2530 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002531 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002532
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002533 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2535 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002536 // when using overlays, we assume a fully transparent framebuffer
2537 // NOTE: we could reduce how much we need to clear, for instance
2538 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002539 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002540 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002541 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002542 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002543 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002544 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002545
2546 // we remove the scissor part
2547 // we're left with the letterbox region
2548 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002550
2551 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002552 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002553
2554 // but limit it to the dirty region
2555 region.andSelf(dirty);
2556
Mathias Agopianb9494d52012-04-18 02:28:45 -07002557 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002558 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002559 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002561 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002562 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002563
Dan Stoza9e56aa02015-11-02 13:00:03 -08002564 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002565 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002566 // scissor on the main display. It should never be needed
2567 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002568 const Rect& bounds(displayDevice->getBounds());
2569 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002570 if (scissor != bounds) {
2571 // scissor doesn't match the screen's dimensions, so we
2572 // need to clear everything outside of it and enable
2573 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002574
Mathias Agopianf45c5102012-10-24 16:29:17 -07002575 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002576 const uint32_t height = displayDevice->getHeight();
2577 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002578 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002579 }
2580 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002581 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002582
Mathias Agopian85d751c2012-08-29 16:59:24 -07002583 /*
2584 * and then, render the layers targeted at the framebuffer
2585 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002586
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("Rendering client layers");
2588 const Transform& displayTransform = displayDevice->getTransform();
2589 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002590 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002591 bool firstLayer = true;
2592 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2593 const Region clip(dirty.intersect(
2594 displayTransform.transform(layer->visibleRegion)));
2595 ALOGV("Layer: %s", layer->getName().string());
2596 ALOGV(" Composition type: %s",
2597 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002598 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 switch (layer->getCompositionType(hwcId)) {
2600 case HWC2::Composition::Cursor:
2601 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002602 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002604 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2606 layer->isOpaque(state) && (state.alpha == 1.0f)
2607 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002608 // never clear the very first layer since we're
2609 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002610 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002611 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002612 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002613 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002614 case HWC2::Composition::Client: {
2615 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002616 break;
2617 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002618 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002619 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002620 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 } else {
2622 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002623 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002625 }
2626 } else {
2627 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002629 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002631 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002633 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002634 }
2635 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002636
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002637 if (applyColorMatrix) {
2638 getRenderEngine().setupColorTransform(oldColorMatrix);
2639 }
2640
Mathias Agopianf45c5102012-10-24 16:29:17 -07002641 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002642 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002643 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644}
2645
Fabien Sanglard830b8472016-11-30 16:35:58 -08002646void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2647 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002648 RenderEngine& engine(getRenderEngine());
2649 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650}
2651
Dan Stoza7d89d062015-04-30 13:29:25 -07002652status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002653 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002654 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002655 const sp<Layer>& lbc,
2656 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002657{
Dan Stoza7d89d062015-04-30 13:29:25 -07002658 // add this layer to the current state list
2659 {
2660 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002661 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002662 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2663 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002664 return NO_MEMORY;
2665 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002666 if (parent == nullptr) {
2667 mCurrentState.layersSortedByZ.add(lbc);
2668 } else {
2669 parent->addChild(lbc);
2670 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002671 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002672 mLayersAdded = true;
2673 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002674 }
2675
Mathias Agopian96f08192010-06-02 23:28:45 -07002676 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002677 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002678
Dan Stoza7d89d062015-04-30 13:29:25 -07002679 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002680}
2681
Robert Carr9524cb32017-02-13 11:32:32 -08002682status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002683 Mutex::Autolock _l(mStateLock);
2684
Robert Carr1f0a16a2016-10-24 16:27:39 -07002685 const auto& p = layer->getParent();
2686 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2687 mCurrentState.layersSortedByZ.remove(layer);
2688
Robert Carr136e2f62017-02-08 17:54:29 -08002689 // As a matter of normal operation, the LayerCleaner will produce a second
2690 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2691 // so we will succeed in promoting it, but it's already been removed
2692 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2693 // otherwise something has gone wrong and we are leaking the layer.
2694 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002695 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2696 layer->getName().string(),
2697 (p != nullptr) ? p->getName().string() : "no-parent");
2698 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002699 } else if (index < 0) {
2700 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002701 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002702
2703 mLayersPendingRemoval.add(layer);
2704 mLayersRemoved = true;
2705 mNumLayers--;
2706 setTransactionFlags(eTransactionNeeded);
2707 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708}
2709
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002710uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002711 return android_atomic_release_load(&mTransactionFlags);
2712}
2713
Mathias Agopian3f844832013-08-07 21:24:32 -07002714uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2716}
2717
Mathias Agopian3f844832013-08-07 21:24:32 -07002718uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2720 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002721 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002722 }
2723 return old;
2724}
2725
Mathias Agopian8b33f032012-07-24 20:43:54 -07002726void SurfaceFlinger::setTransactionState(
2727 const Vector<ComposerState>& state,
2728 const Vector<DisplayState>& displays,
2729 uint32_t flags)
2730{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002731 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002732 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002733 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002734
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002735 if (flags & eAnimation) {
2736 // For window updates that are part of an animation we must wait for
2737 // previous animation "frames" to be handled.
2738 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002739 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002740 if (CC_UNLIKELY(err != NO_ERROR)) {
2741 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002742 // caller after a few seconds.
2743 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2744 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002745 mAnimTransactionPending = false;
2746 break;
2747 }
2748 }
2749 }
2750
Mathias Agopiane57f2922012-08-09 16:29:12 -07002751 size_t count = displays.size();
2752 for (size_t i=0 ; i<count ; i++) {
2753 const DisplayState& s(displays[i]);
2754 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002755 }
2756
Mathias Agopiane57f2922012-08-09 16:29:12 -07002757 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002758 for (size_t i=0 ; i<count ; i++) {
2759 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002760 // Here we need to check that the interface we're given is indeed
2761 // one of our own. A malicious client could give us a NULL
2762 // IInterface, or one of its own or even one of our own but a
2763 // different type. All these situations would cause us to crash.
2764 //
2765 // NOTE: it would be better to use RTTI as we could directly check
2766 // that we have a Client*. however, RTTI is disabled in Android.
2767 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002768 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002769 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002770 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002771 sp<Client> client( static_cast<Client *>(s.client.get()) );
2772 transactionFlags |= setClientStateLocked(client, s.state);
2773 }
2774 }
2775 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002776 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002777
Robert Carr2a7dbb42016-05-24 11:41:28 -07002778 // If a synchronous transaction is explicitly requested without any changes,
2779 // force a transaction anyway. This can be used as a flush mechanism for
2780 // previous async transactions.
2781 if (transactionFlags == 0 && (flags & eSynchronous)) {
2782 transactionFlags = eTransactionNeeded;
2783 }
2784
Mathias Agopian386aa982011-11-07 21:58:03 -08002785 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002786 if (mInterceptor.isEnabled()) {
2787 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2788 }
Irvel468051e2016-06-13 16:44:44 -07002789
Mathias Agopian386aa982011-11-07 21:58:03 -08002790 // this triggers the transaction
2791 setTransactionFlags(transactionFlags);
2792
2793 // if this is a synchronous transaction, wait for it to take effect
2794 // before returning.
2795 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002796 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002797 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002798 if (flags & eAnimation) {
2799 mAnimTransactionPending = true;
2800 }
2801 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002802 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2803 if (CC_UNLIKELY(err != NO_ERROR)) {
2804 // just in case something goes wrong in SF, return to the
2805 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002806 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2807 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002808 break;
2809 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002810 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 }
2812}
2813
Mathias Agopiane57f2922012-08-09 16:29:12 -07002814uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2815{
Jesse Hall9a143922012-10-04 16:29:19 -07002816 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2817 if (dpyIdx < 0)
2818 return 0;
2819
Mathias Agopiane57f2922012-08-09 16:29:12 -07002820 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002821 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002822 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002823 const uint32_t what = s.what;
2824 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002825 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002826 disp.surface = s.surface;
2827 flags |= eDisplayTransactionNeeded;
2828 }
2829 }
2830 if (what & DisplayState::eLayerStackChanged) {
2831 if (disp.layerStack != s.layerStack) {
2832 disp.layerStack = s.layerStack;
2833 flags |= eDisplayTransactionNeeded;
2834 }
2835 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002836 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002837 if (disp.orientation != s.orientation) {
2838 disp.orientation = s.orientation;
2839 flags |= eDisplayTransactionNeeded;
2840 }
2841 if (disp.frame != s.frame) {
2842 disp.frame = s.frame;
2843 flags |= eDisplayTransactionNeeded;
2844 }
2845 if (disp.viewport != s.viewport) {
2846 disp.viewport = s.viewport;
2847 flags |= eDisplayTransactionNeeded;
2848 }
2849 }
Michael Lentine47e45402014-07-18 15:34:25 -07002850 if (what & DisplayState::eDisplaySizeChanged) {
2851 if (disp.width != s.width) {
2852 disp.width = s.width;
2853 flags |= eDisplayTransactionNeeded;
2854 }
2855 if (disp.height != s.height) {
2856 disp.height = s.height;
2857 flags |= eDisplayTransactionNeeded;
2858 }
2859 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002860 }
2861 return flags;
2862}
2863
2864uint32_t SurfaceFlinger::setClientStateLocked(
2865 const sp<Client>& client,
2866 const layer_state_t& s)
2867{
2868 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002869 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002870 if (layer != 0) {
2871 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002872 bool geometryAppliesWithResize =
2873 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002874 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002875 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002876 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002877 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878 }
2879 if (what & layer_state_t::eLayerChanged) {
2880 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002881 const auto& p = layer->getParent();
2882 if (p == nullptr) {
2883 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2884 if (layer->setLayer(s.z) && idx >= 0) {
2885 mCurrentState.layersSortedByZ.removeAt(idx);
2886 mCurrentState.layersSortedByZ.add(layer);
2887 // we need traversal (state changed)
2888 // AND transaction (list changed)
2889 flags |= eTransactionNeeded|eTraversalNeeded;
2890 }
2891 } else {
2892 if (p->setChildLayer(layer, s.z)) {
2893 flags |= eTransactionNeeded|eTraversalNeeded;
2894 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002895 }
2896 }
Robert Carrdb66e622017-04-10 16:55:57 -07002897 if (what & layer_state_t::eRelativeLayerChanged) {
2898 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2899 flags |= eTransactionNeeded|eTraversalNeeded;
2900 }
2901 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002902 if (what & layer_state_t::eSizeChanged) {
2903 if (layer->setSize(s.w, s.h)) {
2904 flags |= eTraversalNeeded;
2905 }
2906 }
2907 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002908 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002909 flags |= eTraversalNeeded;
2910 }
2911 if (what & layer_state_t::eMatrixChanged) {
2912 if (layer->setMatrix(s.matrix))
2913 flags |= eTraversalNeeded;
2914 }
2915 if (what & layer_state_t::eTransparentRegionChanged) {
2916 if (layer->setTransparentRegionHint(s.transparentRegion))
2917 flags |= eTraversalNeeded;
2918 }
Dan Stoza23116082015-06-18 14:58:39 -07002919 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920 if (layer->setFlags(s.flags, s.mask))
2921 flags |= eTraversalNeeded;
2922 }
2923 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002924 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002925 flags |= eTraversalNeeded;
2926 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002927 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002928 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002929 flags |= eTraversalNeeded;
2930 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002931 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002932 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002933 // We only allow setting layer stacks for top level layers,
2934 // everything else inherits layer stack from its parent.
2935 if (layer->hasParent()) {
2936 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2937 layer->getName().string());
2938 } else if (idx < 0) {
2939 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2940 "that also does not appear in the top level layer list. Something"
2941 " has gone wrong.", layer->getName().string());
2942 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002943 mCurrentState.layersSortedByZ.removeAt(idx);
2944 mCurrentState.layersSortedByZ.add(layer);
2945 // we need traversal (state changed)
2946 // AND transaction (list changed)
2947 flags |= eTransactionNeeded|eTraversalNeeded;
2948 }
2949 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002950 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002951 if (s.barrierHandle != nullptr) {
2952 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2953 } else if (s.barrierGbp != nullptr) {
2954 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2955 if (authenticateSurfaceTextureLocked(gbp)) {
2956 const auto& otherLayer =
2957 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
2958 layer->deferTransactionUntil(otherLayer, s.frameNumber);
2959 } else {
2960 ALOGE("Attempt to defer transaction to to an"
2961 " unrecognized GraphicBufferProducer");
2962 }
2963 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002964 // We don't trigger a traversal here because if no other state is
2965 // changed, we don't want this to cause any more work
2966 }
Robert Carr1db73f62016-12-21 12:58:51 -08002967 if (what & layer_state_t::eReparentChildren) {
2968 if (layer->reparentChildren(s.reparentHandle)) {
2969 flags |= eTransactionNeeded|eTraversalNeeded;
2970 }
2971 }
Robert Carr9524cb32017-02-13 11:32:32 -08002972 if (what & layer_state_t::eDetachChildren) {
2973 layer->detachChildren();
2974 }
Robert Carrc3574f72016-03-24 12:19:32 -07002975 if (what & layer_state_t::eOverrideScalingModeChanged) {
2976 layer->setOverrideScalingMode(s.overrideScalingMode);
2977 // We don't trigger a traversal here because if no other state is
2978 // changed, we don't want this to cause any more work
2979 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 }
2981 return flags;
2982}
2983
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002984status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002985 const String8& name,
2986 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002987 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002988 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2989 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002991 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002992 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002993 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002994 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002995 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002996
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002997 status_t result = NO_ERROR;
2998
2999 sp<Layer> layer;
3000
Cody Northropbc755282017-03-31 12:00:08 -06003001 String8 uniqueName = getUniqueLayerName(name);
3002
Mathias Agopian3165cc22012-08-08 19:42:09 -07003003 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3004 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003005 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003006 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003007 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003008 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003009 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003010 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003011 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003012 handle, gbp, &layer);
3013 break;
3014 default:
3015 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016 break;
3017 }
3018
Dan Stoza7d89d062015-04-30 13:29:25 -07003019 if (result != NO_ERROR) {
3020 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003022
Albert Chaulk479c60c2017-01-27 14:21:34 -05003023 layer->setInfo(windowType, ownerUid);
3024
Robert Carr1f0a16a2016-10-24 16:27:39 -07003025 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003026 if (result != NO_ERROR) {
3027 return result;
3028 }
Irvelffc9efc2016-07-27 15:16:37 -07003029 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003030
3031 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003032 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003033}
3034
Cody Northropbc755282017-03-31 12:00:08 -06003035String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3036{
3037 bool matchFound = true;
3038 uint32_t dupeCounter = 0;
3039
3040 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3041 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3042
3043 // Loop over layers until we're sure there is no matching name
3044 while (matchFound) {
3045 matchFound = false;
3046 mDrawingState.traverseInZOrder([&](Layer* layer) {
3047 if (layer->getName() == uniqueName) {
3048 matchFound = true;
3049 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3050 }
3051 });
3052 }
3053
3054 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3055
3056 return uniqueName;
3057}
3058
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003059status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3060 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3061 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062{
3063 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003064 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 case PIXEL_FORMAT_TRANSPARENT:
3066 case PIXEL_FORMAT_TRANSLUCENT:
3067 format = PIXEL_FORMAT_RGBA_8888;
3068 break;
3069 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003070 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 break;
3072 }
3073
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003074 *outLayer = new Layer(this, client, name, w, h, flags);
3075 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3076 if (err == NO_ERROR) {
3077 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003078 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003079 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003080
3081 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3082 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083}
3084
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003085status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3086 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3087 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003089 *outLayer = new LayerDim(this, client, name, w, h, flags);
3090 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003091 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003092 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003093}
3094
Mathias Agopianac9fa422013-02-11 16:40:36 -08003095status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096{
Robert Carr9524cb32017-02-13 11:32:32 -08003097 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003098 status_t err = NO_ERROR;
3099 sp<Layer> l(client->getLayerUser(handle));
3100 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003101 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003102 err = removeLayer(l);
3103 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3104 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003105 }
3106 return err;
3107}
3108
Mathias Agopian13127d82013-03-05 17:47:11 -08003109status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003110{
Mathias Agopian67106042013-03-14 19:18:13 -07003111 // called by ~LayerCleaner() when all references to the IBinder (handle)
3112 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003113 sp<Layer> l = layer.promote();
3114 if (l == nullptr) {
3115 // The layer has already been removed, carry on
3116 return NO_ERROR;
3117 } if (l->getParent() != nullptr) {
3118 // If we have a parent, then we can continue to live as long as it does.
3119 return NO_ERROR;
3120 }
3121 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122}
3123
Mathias Agopianb60314a2012-04-10 22:09:54 -07003124// ---------------------------------------------------------------------------
3125
Andy McFadden13a082e2012-08-24 10:16:42 -07003126void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003127 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003128 Vector<ComposerState> state;
3129 Vector<DisplayState> displays;
3130 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003131 d.what = DisplayState::eDisplayProjectionChanged |
3132 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003133 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003134 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003135 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003136 d.frame.makeInvalid();
3137 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003138 d.width = 0;
3139 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003140 displays.add(d);
3141 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003142 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003143
Dan Stoza9e56aa02015-11-02 13:00:03 -08003144 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3145 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003146 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003147
Brian Andersond0010582017-03-07 13:20:31 -08003148 // Use phase of 0 since phase is not known.
3149 // Use latency of 0, which will snap to the ideal latency.
3150 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003151}
3152
3153void SurfaceFlinger::initializeDisplays() {
3154 class MessageScreenInitialized : public MessageBase {
3155 SurfaceFlinger* flinger;
3156 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003157 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003158 virtual bool handler() {
3159 flinger->onInitializeDisplays();
3160 return true;
3161 }
3162 };
3163 sp<MessageBase> msg = new MessageScreenInitialized(this);
3164 postMessageAsync(msg); // we may be called from main thread, use async message
3165}
3166
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003167void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3168 int mode) {
3169 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3170 this);
3171 int32_t type = hw->getDisplayType();
3172 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003173
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003174 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003175 return;
3176 }
3177
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003178 hw->setPowerMode(mode);
3179 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3180 ALOGW("Trying to set power mode for virtual display");
3181 return;
3182 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003183
Irvelffc9efc2016-07-27 15:16:37 -07003184 if (mInterceptor.isEnabled()) {
3185 Mutex::Autolock _l(mStateLock);
3186 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3187 if (idx < 0) {
3188 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3189 return;
3190 }
3191 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3192 }
3193
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003194 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003195 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003196 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003197 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3198 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003199 // FIXME: eventthread only knows about the main display right now
3200 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003201 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003202 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003204 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003205 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003206 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003207
3208 struct sched_param param = {0};
3209 param.sched_priority = 1;
3210 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3211 ALOGW("Couldn't set SCHED_FIFO on display on");
3212 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003213 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003214 // Turn off the display
3215 struct sched_param param = {0};
3216 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3217 ALOGW("Couldn't set SCHED_OTHER on display off");
3218 }
3219
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003220 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003221 disableHardwareVsync(true); // also cancels any in-progress resync
3222
Mathias Agopiancde87a32012-09-13 14:09:01 -07003223 // FIXME: eventthread only knows about the main display right now
3224 mEventThread->onScreenReleased();
3225 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003226
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003227 getHwComposer().setPowerMode(type, mode);
3228 mVisibleRegionsDirty = true;
3229 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003230 } else if (mode == HWC_POWER_MODE_DOZE ||
3231 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003232 // Update display while dozing
3233 getHwComposer().setPowerMode(type, mode);
3234 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3235 // FIXME: eventthread only knows about the main display right now
3236 mEventThread->onScreenAcquired();
3237 resyncToHardwareVsync(true);
3238 }
3239 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3240 // Leave display going to doze
3241 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3242 disableHardwareVsync(true); // also cancels any in-progress resync
3243 // FIXME: eventthread only knows about the main display right now
3244 mEventThread->onScreenReleased();
3245 }
3246 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003247 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003248 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003249 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003250 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003251}
3252
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003253void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3254 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003255 SurfaceFlinger& mFlinger;
3256 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003257 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003258 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003259 MessageSetPowerMode(SurfaceFlinger& flinger,
3260 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3261 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003262 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003263 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003264 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003265 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003266 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003267 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003268 ALOGW("Attempt to set power mode = %d for virtual display",
3269 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003270 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003271 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003272 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003273 return true;
3274 }
3275 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003276 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003277 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003278}
3279
3280// ---------------------------------------------------------------------------
3281
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3283{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003285
Mathias Agopianbd115332013-04-18 16:41:04 -07003286 IPCThreadState* ipc = IPCThreadState::self();
3287 const int pid = ipc->getCallingPid();
3288 const int uid = ipc->getCallingUid();
3289 if ((uid != AID_SHELL) &&
3290 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003291 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003292 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003293 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003294 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003295 // (this would indicate SF is stuck, but we want to be able to
3296 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003297 status_t err = mStateLock.timedLock(s2ns(1));
3298 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003299 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003300 result.appendFormat(
3301 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3302 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003303 }
3304
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003305 bool dumpAll = true;
3306 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003307 size_t numArgs = args.size();
3308 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003309 if ((index < numArgs) &&
3310 (args[index] == String16("--list"))) {
3311 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003312 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003313 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003314 }
3315
3316 if ((index < numArgs) &&
3317 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003318 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003319 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003320 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003321 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003322
3323 if ((index < numArgs) &&
3324 (args[index] == String16("--latency-clear"))) {
3325 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003326 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003327 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003328 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003329
3330 if ((index < numArgs) &&
3331 (args[index] == String16("--dispsync"))) {
3332 index++;
3333 mPrimaryDispSync.dump(result);
3334 dumpAll = false;
3335 }
Dan Stozab90cf072015-03-05 11:05:59 -08003336
3337 if ((index < numArgs) &&
3338 (args[index] == String16("--static-screen"))) {
3339 index++;
3340 dumpStaticScreenStats(result);
3341 dumpAll = false;
3342 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003343
3344 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003345 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003346 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003347 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003348 dumpAll = false;
3349 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003350
3351 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3352 index++;
3353 dumpWideColorInfo(result);
3354 dumpAll = false;
3355 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003357
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003358 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003359 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003360 }
3361
Mathias Agopian9795c422009-08-26 16:36:26 -07003362 if (locked) {
3363 mStateLock.unlock();
3364 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365 }
3366 write(fd, result.string(), result.size());
3367 return NO_ERROR;
3368}
3369
Dan Stozac7014012014-02-14 15:03:43 -08003370void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3371 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003372{
Robert Carr2047fae2016-11-28 14:09:09 -08003373 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003374 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003375 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003376}
3377
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003378void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003379 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003380{
3381 String8 name;
3382 if (index < args.size()) {
3383 name = String8(args[index]);
3384 index++;
3385 }
3386
Dan Stoza9e56aa02015-11-02 13:00:03 -08003387 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3388 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003389 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003390
3391 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003392 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003393 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003394 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003395 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003396 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003397 }
Robert Carr2047fae2016-11-28 14:09:09 -08003398 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003399 }
3400}
3401
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003402void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003403 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003404{
3405 String8 name;
3406 if (index < args.size()) {
3407 name = String8(args[index]);
3408 index++;
3409 }
3410
Robert Carr2047fae2016-11-28 14:09:09 -08003411 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003412 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003413 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003414 }
Robert Carr2047fae2016-11-28 14:09:09 -08003415 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003416
Svetoslavd85084b2014-03-20 10:28:31 -07003417 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003418}
3419
Jamie Gennis6547ff42013-07-16 20:12:42 -07003420// This should only be called from the main thread. Otherwise it would need
3421// the lock and should use mCurrentState rather than mDrawingState.
3422void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003423 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003424 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003425 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003426
3427 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3428}
3429
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003430void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003431{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003432 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003433 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3434
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003435 if (isLayerTripleBufferingDisabled())
3436 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003437
3438 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003439 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003440 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003441 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003442 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3443 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003444 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003445}
3446
Dan Stozab90cf072015-03-05 11:05:59 -08003447void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3448{
3449 result.appendFormat("Static screen stats:\n");
3450 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3451 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3452 float percent = 100.0f *
3453 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3454 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3455 b + 1, bucketTimeSec, percent);
3456 }
3457 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3458 float percent = 100.0f *
3459 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3460 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3461 NUM_BUCKETS - 1, bucketTimeSec, percent);
3462}
3463
Dan Stozae77c7662016-05-13 11:37:28 -07003464void SurfaceFlinger::recordBufferingStats(const char* layerName,
3465 std::vector<OccupancyTracker::Segment>&& history) {
3466 Mutex::Autolock lock(mBufferingStatsMutex);
3467 auto& stats = mBufferingStats[layerName];
3468 for (const auto& segment : history) {
3469 if (!segment.usedThirdBuffer) {
3470 stats.twoBufferTime += segment.totalTime;
3471 }
3472 if (segment.occupancyAverage < 1.0f) {
3473 stats.doubleBufferedTime += segment.totalTime;
3474 } else if (segment.occupancyAverage < 2.0f) {
3475 stats.tripleBufferedTime += segment.totalTime;
3476 }
3477 ++stats.numSegments;
3478 stats.totalTime += segment.totalTime;
3479 }
3480}
3481
Brian Andersond6927fb2016-07-23 23:37:30 -07003482void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3483 result.appendFormat("Layer frame timestamps:\n");
3484
3485 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3486 const size_t count = currentLayers.size();
3487 for (size_t i=0 ; i<count ; i++) {
3488 currentLayers[i]->dumpFrameEvents(result);
3489 }
3490}
3491
Dan Stozae77c7662016-05-13 11:37:28 -07003492void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3493 result.append("Buffering stats:\n");
3494 result.append(" [Layer name] <Active time> <Two buffer> "
3495 "<Double buffered> <Triple buffered>\n");
3496 Mutex::Autolock lock(mBufferingStatsMutex);
3497 typedef std::tuple<std::string, float, float, float> BufferTuple;
3498 std::map<float, BufferTuple, std::greater<float>> sorted;
3499 for (const auto& statsPair : mBufferingStats) {
3500 const char* name = statsPair.first.c_str();
3501 const BufferingStats& stats = statsPair.second;
3502 if (stats.numSegments == 0) {
3503 continue;
3504 }
3505 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3506 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3507 stats.totalTime;
3508 float doubleBufferRatio = static_cast<float>(
3509 stats.doubleBufferedTime) / stats.totalTime;
3510 float tripleBufferRatio = static_cast<float>(
3511 stats.tripleBufferedTime) / stats.totalTime;
3512 sorted.insert({activeTime, {name, twoBufferRatio,
3513 doubleBufferRatio, tripleBufferRatio}});
3514 }
3515 for (const auto& sortedPair : sorted) {
3516 float activeTime = sortedPair.first;
3517 const BufferTuple& values = sortedPair.second;
3518 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3519 std::get<0>(values).c_str(), activeTime,
3520 std::get<1>(values), std::get<2>(values),
3521 std::get<3>(values));
3522 }
3523 result.append("\n");
3524}
3525
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003526void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3527 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3528
3529 // TODO: print out if wide-color mode is active or not
3530
3531 for (size_t d = 0; d < mDisplays.size(); d++) {
3532 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3533 int32_t hwcId = displayDevice->getHwcDisplayId();
3534 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3535 continue;
3536 }
3537
3538 result.appendFormat("Display %d color modes:\n", hwcId);
3539 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3540 for (auto&& mode : modes) {
3541 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3542 }
3543
3544 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3545 result.appendFormat(" Current color mode: %s (%d)\n",
3546 decodeColorMode(currentMode).c_str(), currentMode);
3547 }
3548 result.append("\n");
3549}
3550
Mathias Agopian74d211a2013-04-22 16:55:35 +02003551void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3552 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003553{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003554 bool colorize = false;
3555 if (index < args.size()
3556 && (args[index] == String16("--color"))) {
3557 colorize = true;
3558 index++;
3559 }
3560
3561 Colorizer colorizer(colorize);
3562
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003563 // figure out if we're stuck somewhere
3564 const nsecs_t now = systemTime();
3565 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3566 const nsecs_t inTransaction(mDebugInTransaction);
3567 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3568 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3569
3570 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003571 * Dump library configuration.
3572 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003573
3574 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003575 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003576 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003577 appendSfConfigString(result);
3578 appendUiConfigString(result);
3579 appendGuiConfigString(result);
3580 result.append("\n");
3581
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003582 result.append("\nWide-Color information:\n");
3583 dumpWideColorInfo(result);
3584
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003585 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003586 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003587 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003588 result.append(SyncFeatures::getInstance().toString());
3589 result.append("\n");
3590
Dan Stoza9e56aa02015-11-02 13:00:03 -08003591 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3592
Andy McFadden41d67d72014-04-25 16:58:34 -07003593 colorizer.bold(result);
3594 result.append("DispSync configuration: ");
3595 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003596 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003597 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003598 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003599 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003600 result.append("\n");
3601
Dan Stozab90cf072015-03-05 11:05:59 -08003602 // Dump static screen stats
3603 result.append("\n");
3604 dumpStaticScreenStats(result);
3605 result.append("\n");
3606
Dan Stozae77c7662016-05-13 11:37:28 -07003607 dumpBufferingStats(result);
3608
Andy McFadden4803b742012-09-24 19:07:20 -07003609 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003610 * Dump the visible layer list
3611 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003612 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003613 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003614 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003615 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003616 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003617 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003618
3619 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003620 * Dump Display state
3621 */
3622
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003623 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003624 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003625 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003626 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3627 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003628 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003629 }
3630
3631 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003632 * Dump SurfaceFlinger global state
3633 */
3634
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003635 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003636 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003637 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003638
Mathias Agopian888c8222012-08-04 21:10:38 -07003639 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003640 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003641
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003642 colorizer.bold(result);
3643 result.appendFormat("EGL implementation : %s\n",
3644 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3645 colorizer.reset(result);
3646 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003647 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003648
Mathias Agopian875d8e12013-06-07 15:35:48 -07003649 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003650
Mathias Agopian42977342012-08-05 00:40:46 -07003651 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003652 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3653 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003654 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003655 " last eglSwapBuffers() time: %f us\n"
3656 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003657 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003658 " refresh-rate : %f fps\n"
3659 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003660 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003661 " gpu_to_cpu_unsupported : %d\n"
3662 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003663 mLastSwapBufferTime/1000.0,
3664 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003665 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003666 1e9 / activeConfig->getVsyncPeriod(),
3667 activeConfig->getDpiX(),
3668 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003669 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003670
Mathias Agopian74d211a2013-04-22 16:55:35 +02003671 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003672 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003673
Mathias Agopian74d211a2013-04-22 16:55:35 +02003674 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003675 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003676
3677 /*
3678 * VSYNC state
3679 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003680 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003681 result.append("\n");
3682
3683 /*
3684 * HWC layer minidump
3685 */
3686 for (size_t d = 0; d < mDisplays.size(); d++) {
3687 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3688 int32_t hwcId = displayDevice->getHwcDisplayId();
3689 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3690 continue;
3691 }
3692
3693 result.appendFormat("Display %d HWC layers:\n", hwcId);
3694 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003695 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003696 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003697 });
Dan Stozae22aec72016-08-01 13:20:59 -07003698 result.append("\n");
3699 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003700
3701 /*
3702 * Dump HWComposer state
3703 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003704 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003705 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003706 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003707 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003708 result.appendFormat(" h/w composer %s\n",
3709 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003710 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003711
3712 /*
3713 * Dump gralloc state
3714 */
3715 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3716 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003717}
3718
Mathias Agopian13127d82013-03-05 17:47:11 -08003719const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003720SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003721 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003722 wp<IBinder> dpy;
3723 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3724 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3725 dpy = mDisplays.keyAt(i);
3726 break;
3727 }
3728 }
3729 if (dpy == NULL) {
3730 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3731 // Just use the primary display so we have something to return
3732 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3733 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003734 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003735}
3736
Keun young Park63f165f2012-08-31 10:53:36 -07003737bool SurfaceFlinger::startDdmConnection()
3738{
3739 void* libddmconnection_dso =
3740 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3741 if (!libddmconnection_dso) {
3742 return false;
3743 }
3744 void (*DdmConnection_start)(const char* name);
3745 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003746 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003747 if (!DdmConnection_start) {
3748 dlclose(libddmconnection_dso);
3749 return false;
3750 }
3751 (*DdmConnection_start)(getServiceName());
3752 return true;
3753}
3754
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003755status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756 switch (code) {
3757 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003758 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003760 case CLEAR_ANIMATION_FRAME_STATS:
3761 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003762 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003763 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003764 {
3765 // codes that require permission check
3766 IPCThreadState* ipc = IPCThreadState::self();
3767 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003768 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003769 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003770 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003771 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003772 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003774 break;
3775 }
Robert Carr1db73f62016-12-21 12:58:51 -08003776 /*
3777 * Calling setTransactionState is safe, because you need to have been
3778 * granted a reference to Client* and Handle* to do anything with it.
3779 *
3780 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3781 */
3782 case SET_TRANSACTION_STATE:
3783 case CREATE_SCOPED_CONNECTION:
3784 {
3785 return OK;
3786 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003787 case CAPTURE_SCREEN:
3788 {
3789 // codes that require permission check
3790 IPCThreadState* ipc = IPCThreadState::self();
3791 const int pid = ipc->getCallingPid();
3792 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003793 if ((uid != AID_GRAPHICS) &&
3794 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003795 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003796 return PERMISSION_DENIED;
3797 }
3798 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003799 }
3800 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003801 return OK;
3802}
3803
3804status_t SurfaceFlinger::onTransact(
3805 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3806{
3807 status_t credentialCheck = CheckTransactCodeCredentials(code);
3808 if (credentialCheck != OK) {
3809 return credentialCheck;
3810 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003811
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003812 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3813 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003814 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003815 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003816 IPCThreadState* ipc = IPCThreadState::self();
3817 const int pid = ipc->getCallingPid();
3818 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003819 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003820 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 return PERMISSION_DENIED;
3822 }
3823 int n;
3824 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003825 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003826 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 return NO_ERROR;
3828 case 1002: // SHOW_UPDATES
3829 n = data.readInt32();
3830 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003831 invalidateHwcGeometry();
3832 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003833 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003834 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003835 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003836 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003837 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003838 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003839 setTransactionFlags(
3840 eTransactionNeeded|
3841 eDisplayTransactionNeeded|
3842 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003843 return NO_ERROR;
3844 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003845 case 1006:{ // send empty update
3846 signalRefresh();
3847 return NO_ERROR;
3848 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003849 case 1008: // toggle use of hw composer
3850 n = data.readInt32();
3851 mDebugDisableHWC = n ? 1 : 0;
3852 invalidateHwcGeometry();
3853 repaintEverything();
3854 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003855 case 1009: // toggle use of transform hint
3856 n = data.readInt32();
3857 mDebugDisableTransformHint = n ? 1 : 0;
3858 invalidateHwcGeometry();
3859 repaintEverything();
3860 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003861 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003862 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003863 reply->writeInt32(0);
3864 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003865 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003866 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 return NO_ERROR;
3868 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003869 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003870 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003871 return NO_ERROR;
3872 }
3873 case 1014: {
3874 // daltonize
3875 n = data.readInt32();
3876 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003877 case 1:
3878 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3879 break;
3880 case 2:
3881 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3882 break;
3883 case 3:
3884 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3885 break;
3886 default:
3887 mDaltonizer.setType(ColorBlindnessType::None);
3888 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003889 }
3890 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003891 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003892 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003893 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003894 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003895 invalidateHwcGeometry();
3896 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003897 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003898 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003899 case 1015: {
3900 // apply a color matrix
3901 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003902 if (n) {
Romain Guy88d37dd2017-05-26 17:57:05 -07003903 // color matrix is sent as a row-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003904 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003905 for (size_t j = 0; j < 4; j++) {
3906 mColorMatrix[i][j] = data.readFloat();
3907 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003908 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003909 } else {
3910 mColorMatrix = mat4();
3911 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003912
3913 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3914 // the division by w in the fragment shader
3915 float4 lastRow(transpose(mColorMatrix)[3]);
3916 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3917 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3918 }
3919
Alan Viverette9c5a3332013-09-12 20:04:35 -07003920 invalidateHwcGeometry();
3921 repaintEverything();
3922 return NO_ERROR;
3923 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003924 // This is an experimental interface
3925 // Needs to be shifted to proper binder interface when we productize
3926 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003927 n = data.readInt32();
3928 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003929 return NO_ERROR;
3930 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003931 case 1017: {
3932 n = data.readInt32();
3933 mForceFullDamage = static_cast<bool>(n);
3934 return NO_ERROR;
3935 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003936 case 1018: { // Modify Choreographer's phase offset
3937 n = data.readInt32();
3938 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3939 return NO_ERROR;
3940 }
3941 case 1019: { // Modify SurfaceFlinger's phase offset
3942 n = data.readInt32();
3943 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3944 return NO_ERROR;
3945 }
Irvel468051e2016-06-13 16:44:44 -07003946 case 1020: { // Layer updates interceptor
3947 n = data.readInt32();
3948 if (n) {
3949 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003950 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003951 }
3952 else{
3953 ALOGV("Interceptor disabled");
3954 mInterceptor.disable();
3955 }
3956 return NO_ERROR;
3957 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003958 case 1021: { // Disable HWC virtual displays
3959 n = data.readInt32();
3960 mUseHwcVirtualDisplays = !n;
3961 return NO_ERROR;
3962 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 }
3964 }
3965 return err;
3966}
3967
Mathias Agopian53331da2011-08-22 21:44:41 -07003968void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003969 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003970 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003971}
3972
Mathias Agopian59119e62010-10-11 12:37:43 -07003973// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003974// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003975// ---------------------------------------------------------------------------
3976
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003977/* The code below is here to handle b/8734824
3978 *
3979 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003980 * from the surfaceflinger thread to the calling binder thread, where they
3981 * are executed. This allows the calling thread in the calling process to be
3982 * reused and not depend on having "enough" binder threads to handle the
3983 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003984 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003985class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003986 /* Parts of GraphicProducerWrapper are run on two different threads,
3987 * communicating by sending messages via Looper but also by shared member
3988 * data. Coherence maintenance is subtle and in places implicit (ugh).
3989 *
3990 * Don't rely on Looper's sendMessage/handleMessage providing
3991 * release/acquire semantics for any data not actually in the Message.
3992 * Data going from surfaceflinger to binder threads needs to be
3993 * synchronized explicitly.
3994 *
3995 * Barrier open/wait do provide release/acquire semantics. This provides
3996 * implicit synchronization for data coming back from binder to
3997 * surfaceflinger threads.
3998 */
3999
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004000 sp<IGraphicBufferProducer> impl;
4001 sp<Looper> looper;
4002 status_t result;
4003 bool exitPending;
4004 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07004005 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004006 uint32_t code;
4007 Parcel const* data;
4008 Parcel* reply;
4009
4010 enum {
4011 MSG_API_CALL,
4012 MSG_EXIT
4013 };
4014
4015 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004016 * Called on surfaceflinger thread. This is called by our "fake"
4017 * BpGraphicBufferProducer. We package the data and reply Parcel and
4018 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004019 */
4020 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08004021 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004022 this->code = code;
4023 this->data = &data;
4024 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004025 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07004026 // if we've exited, we run the message synchronously right here.
4027 // note (JH): as far as I can tell from looking at the code, this
4028 // never actually happens. if it does, i'm not sure if it happens
4029 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004030 handleMessage(Message(MSG_API_CALL));
4031 } else {
4032 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004033 // Prevent stores to this->{code, data, reply} from being
4034 // reordered later than the construction of Message.
4035 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004036 looper->sendMessage(this, Message(MSG_API_CALL));
4037 barrier.wait();
4038 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004039 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004040 }
4041
4042 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004043 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004044 * call the real BpGraphicBufferProducer.
4045 */
4046 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004047 int what = message.what;
4048 // Prevent reads below from happening before the read from Message
4049 atomic_thread_fence(memory_order_acquire);
4050 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004051 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004052 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004053 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004054 exitRequested = true;
4055 }
4056 }
4057
4058public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004059 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004060 : impl(impl),
4061 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004062 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004063 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004064 exitRequested(false),
4065 code(0),
4066 data(NULL),
4067 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004068 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004069
Jesse Hallb154c422014-07-13 12:47:02 -07004070 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004071 status_t waitForResponse() {
4072 do {
4073 looper->pollOnce(-1);
4074 } while (!exitRequested);
4075 return result;
4076 }
4077
Jesse Hallb154c422014-07-13 12:47:02 -07004078 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004079 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004080 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004081 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004082 // Ensure this->result is visible to the binder thread before it
4083 // handles the message.
4084 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004085 looper->sendMessage(this, Message(MSG_EXIT));
4086 }
4087};
4088
4089
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004090status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4091 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004092 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004093 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004094 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004095
4096 if (CC_UNLIKELY(display == 0))
4097 return BAD_VALUE;
4098
4099 if (CC_UNLIKELY(producer == 0))
4100 return BAD_VALUE;
4101
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004102 // if we have secure windows on this display, never allow the screen capture
4103 // unless the producer interface is local (i.e.: we can take a screenshot for
4104 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004105 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004106
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004107 // Convert to surfaceflinger's internal rotation type.
4108 Transform::orientation_flags rotationFlags;
4109 switch (rotation) {
4110 case ISurfaceComposer::eRotateNone:
4111 rotationFlags = Transform::ROT_0;
4112 break;
4113 case ISurfaceComposer::eRotate90:
4114 rotationFlags = Transform::ROT_90;
4115 break;
4116 case ISurfaceComposer::eRotate180:
4117 rotationFlags = Transform::ROT_180;
4118 break;
4119 case ISurfaceComposer::eRotate270:
4120 rotationFlags = Transform::ROT_270;
4121 break;
4122 default:
4123 rotationFlags = Transform::ROT_0;
4124 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4125 break;
4126 }
4127
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004128 class MessageCaptureScreen : public MessageBase {
4129 SurfaceFlinger* flinger;
4130 sp<IBinder> display;
4131 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004132 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004133 uint32_t reqWidth, reqHeight;
4134 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004135 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004136 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004137 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004138 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004139 public:
4140 MessageCaptureScreen(SurfaceFlinger* flinger,
4141 const sp<IBinder>& display,
4142 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004143 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004144 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004145 bool useIdentityTransform,
4146 Transform::orientation_flags rotation,
4147 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004148 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004149 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004150 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004151 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004152 rotation(rotation), result(PERMISSION_DENIED),
4153 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004154 {
4155 }
4156 status_t getResult() const {
4157 return result;
4158 }
4159 virtual bool handler() {
4160 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004161 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004162 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004163 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004164 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004165 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004166 return true;
4167 }
4168 };
4169
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004170 // this creates a "fake" BBinder which will serve as a "fake" remote
4171 // binder to receive the marshaled calls and forward them to the
4172 // real remote (a BpGraphicBufferProducer)
4173 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4174
4175 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4176 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004177 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004178 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004179 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004180 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004181
4182 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004183 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004184 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004185 }
4186 return res;
4187}
4188
Mathias Agopian180f10d2013-04-10 22:55:41 -07004189
4190void SurfaceFlinger::renderScreenImplLocked(
4191 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004192 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004193 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004194 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004195{
4196 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004197 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004198
4199 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004200 const int32_t hw_w = hw->getWidth();
4201 const int32_t hw_h = hw->getHeight();
4202 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004203 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004204
Dan Stozac1879002014-05-22 15:59:05 -07004205 // if a default or invalid sourceCrop is passed in, set reasonable values
4206 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4207 !sourceCrop.isValid()) {
4208 sourceCrop.setLeftTop(Point(0, 0));
4209 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4210 }
4211
4212 // ensure that sourceCrop is inside screen
4213 if (sourceCrop.left < 0) {
4214 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4215 }
Dan Stozabe31f442014-06-11 11:20:54 -07004216 if (sourceCrop.right > hw_w) {
4217 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004218 }
4219 if (sourceCrop.top < 0) {
4220 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4221 }
Dan Stozabe31f442014-06-11 11:20:54 -07004222 if (sourceCrop.bottom > hw_h) {
4223 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004224 }
4225
Romain Guy88d37dd2017-05-26 17:57:05 -07004226#ifdef USE_HWC2
4227 engine.setWideColor(hw->getWideColorSupport());
4228 engine.setColorMode(hw->getActiveColorMode());
4229#endif
4230
Mathias Agopian180f10d2013-04-10 22:55:41 -07004231 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004232 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004233
4234 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004235 engine.setViewportAndProjection(
4236 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004237 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004238
4239 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004240 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004241
Robert Carr1f0a16a2016-10-24 16:27:39 -07004242 // We loop through the first level of layers without traversing,
4243 // as we need to interpret min/max layer Z in the top level Z space.
4244 for (const auto& layer : mDrawingState.layersSortedByZ) {
4245 if (layer->getLayerStack() != hw->getLayerStack()) {
4246 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004247 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004248 const Layer::State& state(layer->getDrawingState());
4249 if (state.z < minLayerZ || state.z > maxLayerZ) {
4250 continue;
4251 }
Dan Stoza412903f2017-04-27 13:42:17 -07004252 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004253 if (!layer->isVisible()) {
4254 return;
4255 }
4256 if (filtering) layer->setFiltering(true);
4257 layer->draw(hw, useIdentityTransform);
4258 if (filtering) layer->setFiltering(false);
4259 });
4260 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004261
Mathias Agopian931bda12013-08-28 18:11:46 -07004262 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004263}
4264
4265
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004266status_t SurfaceFlinger::captureScreenImplLocked(
4267 const sp<const DisplayDevice>& hw,
4268 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004269 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004270 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004271 bool useIdentityTransform, Transform::orientation_flags rotation,
4272 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004273{
4274 ATRACE_CALL();
4275
Mathias Agopian180f10d2013-04-10 22:55:41 -07004276 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004277 uint32_t hw_w = hw->getWidth();
4278 uint32_t hw_h = hw->getHeight();
4279
4280 if (rotation & Transform::ROT_90) {
4281 std::swap(hw_w, hw_h);
4282 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004283
Mathias Agopian180f10d2013-04-10 22:55:41 -07004284 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4285 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4286 reqWidth, reqHeight, hw_w, hw_h);
4287 return BAD_VALUE;
4288 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004289
Mathias Agopian180f10d2013-04-10 22:55:41 -07004290 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4291 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4292
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004293 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004294 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004295 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004296 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4297 (state.z < minLayerZ || state.z > maxLayerZ)) {
4298 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004299 }
Dan Stoza412903f2017-04-27 13:42:17 -07004300 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004301 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4302 layer->isSecure());
4303 });
4304 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004305
4306 if (!isLocalScreenshot && secureLayerIsVisible) {
4307 ALOGW("FB is protected: PERMISSION_DENIED");
4308 return PERMISSION_DENIED;
4309 }
4310
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004311 // create a surface (because we're a producer, and we need to
4312 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004313 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004314
4315 // Put the screenshot Surface into async mode so that
4316 // Layer::headFenceHasSignaled will always return true and we'll latch the
4317 // first buffer regardless of whether or not its acquire fence has
4318 // signaled. This is needed to avoid a race condition in the rotation
4319 // animation. See b/30209608
4320 sur->setAsyncMode(true);
4321
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004322 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004323
Michael Lentine5a16a622015-05-21 13:48:24 -07004324 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4325 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004326 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4327 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004328
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004329 int err = 0;
4330 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004331 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004332 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4333 err |= native_window_set_usage(window, usage);
Romain Guy88d37dd2017-05-26 17:57:05 -07004334 err |= native_window_set_buffers_data_space(window, hw->getWideColorSupport()
4335 ? HAL_DATASPACE_DISPLAY_P3 : HAL_DATASPACE_V0_SRGB);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004336
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004337 if (err == NO_ERROR) {
4338 ANativeWindowBuffer* buffer;
4339 /* TODO: Once we have the sync framework everywhere this can use
4340 * server-side waits on the fence that dequeueBuffer returns.
4341 */
4342 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4343 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004344 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004345 // create an EGLImage from the buffer so we can later
4346 // turn it into a texture
4347 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4348 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4349 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004350 // this binds the given EGLImage as a framebuffer for the
4351 // duration of this scope.
4352 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4353 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004354 // this will in fact render into our dequeued buffer
4355 // via an FBO, which means we didn't have to create
4356 // an EGLSurface and therefore we're not
4357 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004358 renderScreenImplLocked(
4359 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4360 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004361
Riley Andrews86639902014-08-15 12:27:24 -07004362 // Attempt to create a sync khr object that can produce a sync point. If that
4363 // isn't available, create a non-dupable sync object in the fallback path and
4364 // wait on it directly.
4365 EGLSyncKHR sync;
4366 if (!DEBUG_SCREENSHOTS) {
4367 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004368 // native fence fd will not be populated until flush() is done.
4369 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004370 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004371 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004372 }
Riley Andrews86639902014-08-15 12:27:24 -07004373 if (sync != EGL_NO_SYNC_KHR) {
4374 // get the sync fd
4375 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4376 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4377 ALOGW("captureScreen: failed to dup sync khr object");
4378 syncFd = -1;
4379 }
4380 eglDestroySyncKHR(mEGLDisplay, sync);
4381 } else {
4382 // fallback path
4383 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4384 if (sync != EGL_NO_SYNC_KHR) {
4385 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4386 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4387 EGLint eglErr = eglGetError();
4388 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4389 ALOGW("captureScreen: fence wait timed out");
4390 } else {
4391 ALOGW_IF(eglErr != EGL_SUCCESS,
4392 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4393 }
4394 eglDestroySyncKHR(mEGLDisplay, sync);
4395 } else {
4396 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4397 }
4398 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004399 if (DEBUG_SCREENSHOTS) {
4400 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4401 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4402 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4403 hw, minLayerZ, maxLayerZ);
4404 delete [] pixels;
4405 }
4406
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004407 } else {
4408 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4409 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004410 window->cancelBuffer(window, buffer, syncFd);
4411 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004412 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004413 // destroy our image
4414 eglDestroyImageKHR(mEGLDisplay, image);
4415 } else {
4416 result = BAD_VALUE;
4417 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004418 if (buffer) {
4419 // queueBuffer takes ownership of syncFd
4420 result = window->queueBuffer(window, buffer, syncFd);
4421 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004422 }
4423 } else {
4424 result = BAD_VALUE;
4425 }
4426 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4427 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004428
Mathias Agopian74c40c02010-09-29 13:02:36 -07004429 return result;
4430}
4431
Mathias Agopiand5556842013-09-19 17:08:37 -07004432void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004433 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004434 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004435 for (size_t y=0 ; y<h ; y++) {
4436 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4437 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004438 if (p[x] != 0xFF000000) return;
4439 }
4440 }
4441 ALOGE("*** we just took a black screenshot ***\n"
4442 "requested minz=%d, maxz=%d, layerStack=%d",
4443 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004444
Robert Carr2047fae2016-11-28 14:09:09 -08004445 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004446 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004447 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004448 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4449 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004450 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004451 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4452 layer->isVisible() ? '+' : '-',
4453 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004454 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004455 i++;
4456 });
4457 }
4458 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004459 }
4460}
4461
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004462// ---------------------------------------------------------------------------
4463
Dan Stoza412903f2017-04-27 13:42:17 -07004464void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4465 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004466}
4467
Dan Stoza412903f2017-04-27 13:42:17 -07004468void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4469 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004470}
4471
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004472}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004473
4474
4475#if defined(__gl_h_)
4476#error "don't include gl/gl.h in this file"
4477#endif
4478
4479#if defined(__gl2_h_)
4480#error "don't include gl2/gl2.h in this file"
4481#endif