blob: ded6607778860a17605393fb6f3fcbdc6827347c [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>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070029
30#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070033#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080034
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070035#include <binder/IPCThreadState.h>
36#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
40
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080048#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070049
50#include <ui/GraphicBufferAllocator.h>
51#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080053
Mathias Agopiancde87a32012-09-13 14:09:01 -070054#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080060
Mathias Agopian921e6ac2012-07-23 23:11:29 -070061#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070062#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080067#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070068#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070069#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070070#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080071#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070073#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080075#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopiana4912602012-07-12 14:25:33 -070078#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070079#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070080#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include "Effects/Daltonizer.h"
83
Mathias Agopian875d8e12013-06-07 15:35:48 -070084#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070086
Jiyong Park4b20c2e2017-01-14 19:45:11 +090087#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090088#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#define DISPLAY_COUNT 1
91
Mathias Agopianfee2b462013-07-03 12:34:01 -070092/*
93 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
94 * black pixels.
95 */
96#define DEBUG_SCREENSHOTS false
97
Mathias Agopianca088332013-03-28 17:44:13 -070098EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700101
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800102
Jaesoo Lee43518572017-01-23 19:03:16 +0900103using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900104using namespace android::hardware::configstore::V1_0;
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106// ---------------------------------------------------------------------------
107
Mathias Agopian99b49842011-06-27 16:05:52 -0700108const String16 sHardwareTest("android.permission.HARDWARE_TEST");
109const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
110const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
111const String16 sDump("android.permission.DUMP");
112
113// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800114int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
115int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700116bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700117int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700118bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800119uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800120bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800121bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800122int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600123bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700126 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700128 mTransactionPending(false),
129 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700130 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700131 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700132 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800133 mHwc(nullptr),
134 mRealHwc(nullptr),
135 mVrHwc(nullptr),
136 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800137 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800138 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800139 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800140 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800141 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700143 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700144 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700145 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700150 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700151 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800152 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000153 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700154 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700155 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700156 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800157 mHasPoweredOff(false),
158 mFrameBuckets(),
159 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700160 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800161 mNumLayers(0),
162 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800163{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800164 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800165
166 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
167 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
168
169 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
170 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800172 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
173 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800174
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700175 useContextPriority = getBool< ISurfaceFlingerConfigs,
176 &ISurfaceFlingerConfigs::useContextPriority>(false);
177
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700178 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
179 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
180
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700181 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
183
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800184 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
186
Steven Thomas050b2c82017-03-06 11:45:16 -0800187 // Vr flinger is only enabled on Daydream ready devices.
188 useVrFlinger = getBool< ISurfaceFlingerConfigs,
189 &ISurfaceFlingerConfigs::useVrFlinger>(false);
190
Fabien Sanglard1971b632017-03-10 14:50:03 -0800191 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
192 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
193
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600194 hasWideColorDisplay =
195 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800197 // debugging stuff...
198 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700199
Mathias Agopianb4b17302013-03-20 18:36:41 -0700200 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700201 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203 property_get("debug.sf.showupdates", value, "0");
204 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700205
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206 property_get("debug.sf.ddms", value, "0");
207 mDebugDDMS = atoi(value);
208 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700209 if (!startDdmConnection()) {
210 // start failed, and DDMS debugging not enabled
211 mDebugDDMS = 0;
212 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700213 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700214 ALOGI_IF(mDebugRegion, "showupdates enabled");
215 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700216
217 property_get("debug.sf.disable_backpressure", value, "0");
218 mPropagateBackpressure = !atoi(value);
219 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700220
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800221 property_get("debug.sf.enable_hwc_vds", value, "0");
222 mUseHwcVirtualDisplays = atoi(value);
223 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800224
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800225 property_get("ro.sf.disable_triple_buffer", value, "1");
226 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800227 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700228
229 property_get("persist.sys.sf.color_saturation", value, "1.0");
230 mSaturation = atof(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231}
232
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233void SurfaceFlinger::onFirstRef()
234{
235 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800236}
237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238SurfaceFlinger::~SurfaceFlinger()
239{
Mathias Agopiana4912602012-07-12 14:25:33 -0700240 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
241 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
242 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800243}
244
Dan Stozac7014012014-02-14 15:03:43 -0800245void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800246{
247 // the window manager died on us. prepare its eulogy.
248
Andy McFadden13a082e2012-08-24 10:16:42 -0700249 // restore initial conditions (default device unblank, etc)
250 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251
252 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700253 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800254}
255
Robert Carr1db73f62016-12-21 12:58:51 -0800256static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700257 status_t err = client->initCheck();
258 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800259 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800260 }
Robert Carr1db73f62016-12-21 12:58:51 -0800261 return nullptr;
262}
263
264sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
265 return initClient(new Client(this));
266}
267
268sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
269 const sp<IGraphicBufferProducer>& gbp) {
270 if (authenticateSurfaceTexture(gbp) == false) {
271 return nullptr;
272 }
273 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
274 if (layer == nullptr) {
275 return nullptr;
276 }
277
278 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279}
280
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700281sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
282 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700283{
284 class DisplayToken : public BBinder {
285 sp<SurfaceFlinger> flinger;
286 virtual ~DisplayToken() {
287 // no more references, this display must be terminated
288 Mutex::Autolock _l(flinger->mStateLock);
289 flinger->mCurrentState.displays.removeItem(this);
290 flinger->setTransactionFlags(eDisplayTransactionNeeded);
291 }
292 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700293 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700294 : flinger(flinger) {
295 }
296 };
297
298 sp<BBinder> token = new DisplayToken(this);
299
300 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700301 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700302 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700303 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700304 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700305 return token;
306}
307
Jesse Hall6c913be2013-08-08 12:15:49 -0700308void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
309 Mutex::Autolock _l(mStateLock);
310
311 ssize_t idx = mCurrentState.displays.indexOfKey(display);
312 if (idx < 0) {
313 ALOGW("destroyDisplay: invalid display token");
314 return;
315 }
316
317 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
318 if (!info.isVirtualDisplay()) {
319 ALOGE("destroyDisplay called for non-virtual display");
320 return;
321 }
Irvelffc9efc2016-07-27 15:16:37 -0700322 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700323 mCurrentState.displays.removeItemsAt(idx);
324 setTransactionFlags(eDisplayTransactionNeeded);
325}
326
Jesse Hall692c7232012-11-08 15:41:56 -0800327void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800328 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800329 ALOGW_IF(mBuiltinDisplays[type],
330 "Overwriting display token for display type %d", type);
331 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800332 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700333 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800334 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700335 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800336}
337
Mathias Agopiane57f2922012-08-09 16:29:12 -0700338sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700339 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700340 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
341 return NULL;
342 }
Jesse Hall692c7232012-11-08 15:41:56 -0800343 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700344}
345
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800346void SurfaceFlinger::bootFinished()
347{
Wei Wangb254fa32017-01-31 17:43:23 -0800348 if (mStartBootAnimThread->join() != NO_ERROR) {
349 ALOGE("Join StartBootAnimThread failed!");
350 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 const nsecs_t now = systemTime();
352 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000353 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700354 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700355
356 // wait patiently for the window manager death
357 const String16 name("window");
358 sp<IBinder> window(defaultServiceManager()->getService(name));
359 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700360 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700361 }
362
Steven Thomas050b2c82017-03-06 11:45:16 -0800363 if (mVrFlinger) {
364 mVrFlinger->OnBootFinished();
365 }
366
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700367 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700368 // formerly we would just kill the process, but we now ask it to exit so it
369 // can choose where to stop the animation.
370 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700371
372 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
373 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
374 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375}
376
Mathias Agopian3f844832013-08-07 21:24:32 -0700377void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700379 RenderEngine& engine;
380 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700382 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
383 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 }
385 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700386 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700387 return true;
388 }
389 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700390 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700391}
392
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700393class DispSyncSource : public VSyncSource, private DispSync::Callback {
394public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700395 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000396 const char* name) :
397 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700398 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700399 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000400 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
401 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700402 mDispSync(dispSync),
403 mCallbackMutex(),
404 mCallback(),
405 mVsyncMutex(),
406 mPhaseOffset(phaseOffset),
407 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700408
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700409 virtual ~DispSyncSource() {}
410
411 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700412 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700413 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000414 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700415 static_cast<DispSync::Callback*>(this));
416 if (err != NO_ERROR) {
417 ALOGE("error registering vsync callback: %s (%d)",
418 strerror(-err), err);
419 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700420 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421 } else {
422 status_t err = mDispSync->removeEventListener(
423 static_cast<DispSync::Callback*>(this));
424 if (err != NO_ERROR) {
425 ALOGE("error unregistering vsync callback: %s (%d)",
426 strerror(-err), err);
427 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700430 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700431 }
432
433 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700434 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700435 mCallback = callback;
436 }
437
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700438 virtual void setPhaseOffset(nsecs_t phaseOffset) {
439 Mutex::Autolock lock(mVsyncMutex);
440
441 // Normalize phaseOffset to [0, period)
442 auto period = mDispSync->getPeriod();
443 phaseOffset %= period;
444 if (phaseOffset < 0) {
445 // If we're here, then phaseOffset is in (-period, 0). After this
446 // operation, it will be in (0, period)
447 phaseOffset += period;
448 }
449 mPhaseOffset = phaseOffset;
450
451 // If we're not enabled, we don't need to mess with the listeners
452 if (!mEnabled) {
453 return;
454 }
455
456 // Remove the listener with the old offset
457 status_t err = mDispSync->removeEventListener(
458 static_cast<DispSync::Callback*>(this));
459 if (err != NO_ERROR) {
460 ALOGE("error unregistering vsync callback: %s (%d)",
461 strerror(-err), err);
462 }
463
464 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000465 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700466 static_cast<DispSync::Callback*>(this));
467 if (err != NO_ERROR) {
468 ALOGE("error registering vsync callback: %s (%d)",
469 strerror(-err), err);
470 }
471 }
472
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700473private:
474 virtual void onDispSyncEvent(nsecs_t when) {
475 sp<VSyncSource::Callback> callback;
476 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700477 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700478 callback = mCallback;
479
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700480 if (mTraceVsync) {
481 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700482 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700483 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700484 }
485
486 if (callback != NULL) {
487 callback->onVSyncEvent(when);
488 }
489 }
490
Tim Murray4a4e4a22016-04-19 16:29:23 +0000491 const char* const mName;
492
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700493 int mValue;
494
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700495 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700496 const String8 mVsyncOnLabel;
497 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700498
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500
501 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700502 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700503
504 Mutex mVsyncMutex; // Protects the following
505 nsecs_t mPhaseOffset;
506 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507};
508
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700509class InjectVSyncSource : public VSyncSource {
510public:
511 InjectVSyncSource() {}
512
513 virtual ~InjectVSyncSource() {}
514
515 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
516 std::lock_guard<std::mutex> lock(mCallbackMutex);
517 mCallback = callback;
518 }
519
520 virtual void onInjectSyncEvent(nsecs_t when) {
521 std::lock_guard<std::mutex> lock(mCallbackMutex);
522 mCallback->onVSyncEvent(when);
523 }
524
525 virtual void setVSyncEnabled(bool) {}
526 virtual void setPhaseOffset(nsecs_t) {}
527
528private:
529 std::mutex mCallbackMutex; // Protects the following
530 sp<VSyncSource::Callback> mCallback;
531};
532
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700533void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700534 ALOGI( "SurfaceFlinger's main thread ready to run. "
535 "Initializing graphics H/W...");
536
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900537 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
538
Dan Stoza9e56aa02015-11-02 13:00:03 -0800539 { // Autolock scope
540 Mutex::Autolock _l(mStateLock);
541
542 // initialize EGL for the default display
543 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
544 eglInitialize(mEGLDisplay, NULL, NULL);
545
546 // start the EventThread
547 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
548 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700549 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
551 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700552 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 mEventQueue.setEventThread(mSFEventThread);
554
Tim Murray22752852017-05-04 13:38:49 -0700555 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700556 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700557 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700558 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
559 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
560 }
Tim Murray22752852017-05-04 13:38:49 -0700561 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
562 ALOGE("Couldn't set SCHED_FIFO for EventThread");
563 }
Tim Murray41a38532016-06-22 12:42:10 -0700564
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565 // Get a RenderEngine for the given display / config (can't fail)
566 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700567 HAL_PIXEL_FORMAT_RGBA_8888,
568 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569 }
570
571 // Drop the state lock while we initialize the hardware composer. We drop
572 // the lock because on creation, it will call back into SurfaceFlinger to
573 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800574 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
575 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800576 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800577 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
579
Jesse Hall692c7232012-11-08 15:41:56 -0800580 Mutex::Autolock _l(mStateLock);
581
Ian Elliott5c34de22017-04-10 14:42:30 -0600582 // Inform native graphics APIs whether the present timestamp is supported:
583 if (getHwComposer().hasCapability(
584 HWC2::Capability::PresentFenceIsNotReliable)) {
585 property_set(kTimestampProperty, "0");
586 } else {
587 property_set(kTimestampProperty, "1");
588 }
589
Steven Thomas050b2c82017-03-06 11:45:16 -0800590 if (useVrFlinger) {
591 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700592 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800593 mVrFlingerRequestsDisplay = requestDisplay;
594 signalTransaction();
595 };
596 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
597 vrFlingerRequestDisplayCallback);
598 if (!mVrFlinger) {
599 ALOGE("Failed to start vrflinger");
600 }
601 }
602
Mathias Agopian875d8e12013-06-07 15:35:48 -0700603 // retrieve the EGL context that was selected/created
604 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700605
Mathias Agopianda27af92012-09-13 18:17:13 -0700606 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
607 "couldn't create EGLContext");
608
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609 // make the GLContext current so that we can create textures when creating
610 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700611 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700612
Jamie Gennisd1700752013-10-14 12:22:52 -0700613 mEventControlThread = new EventControlThread(this);
614 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
615
Mathias Agopian92a979a2012-08-02 18:32:23 -0700616 // initialize our drawing state
617 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700618
Andy McFadden13a082e2012-08-24 10:16:42 -0700619 // set initial conditions (e.g. unblank default device)
620 initializeDisplays();
621
Dan Stoza4e637772016-07-28 13:31:51 -0700622 mRenderEngine->primeCache();
623
Wei Wangb254fa32017-01-31 17:43:23 -0800624 mStartBootAnimThread = new StartBootAnimThread();
625 if (mStartBootAnimThread->Start() != NO_ERROR) {
626 ALOGE("Run StartBootAnimThread failed!");
627 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800628
Dan Stoza9e56aa02015-11-02 13:00:03 -0800629 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700630}
631
Mathias Agopiana67e4182012-06-19 17:26:12 -0700632void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800633 // Start boot animation service by setting a property mailbox
634 // if property setting thread is already running, Start() will be just a NOP
635 mStartBootAnimThread->Start();
636 // Wait until property was set
637 if (mStartBootAnimThread->join() != NO_ERROR) {
638 ALOGE("Join StartBootAnimThread failed!");
639 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700640}
641
Mathias Agopian875d8e12013-06-07 15:35:48 -0700642size_t SurfaceFlinger::getMaxTextureSize() const {
643 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700644}
645
Mathias Agopian875d8e12013-06-07 15:35:48 -0700646size_t SurfaceFlinger::getMaxViewportDims() const {
647 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700648}
649
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800650// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800651
Jamie Gennis582270d2011-08-17 18:19:00 -0700652bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800653 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800654 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800655 return authenticateSurfaceTextureLocked(bufferProducer);
656}
657
658bool SurfaceFlinger::authenticateSurfaceTextureLocked(
659 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800660 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700661 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800662}
663
Brian Anderson6b376712017-04-04 10:51:39 -0700664status_t SurfaceFlinger::getSupportedFrameTimestamps(
665 std::vector<FrameEvent>* outSupported) const {
666 *outSupported = {
667 FrameEvent::REQUESTED_PRESENT,
668 FrameEvent::ACQUIRE,
669 FrameEvent::LATCH,
670 FrameEvent::FIRST_REFRESH_START,
671 FrameEvent::LAST_REFRESH_START,
672 FrameEvent::GPU_COMPOSITION_DONE,
673 FrameEvent::DEQUEUE_READY,
674 FrameEvent::RELEASE,
675 };
676 if (!getHwComposer().hasCapability(
677 HWC2::Capability::PresentFenceIsNotReliable)) {
678 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
679 }
680 return NO_ERROR;
681}
682
Dan Stoza7f7da322014-05-02 15:26:25 -0700683status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
684 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700685 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700686 return BAD_VALUE;
687 }
688
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500689 if (!display.get())
690 return NAME_NOT_FOUND;
691
Jesse Hall692c7232012-11-08 15:41:56 -0800692 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700693 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800694 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700695 type = i;
696 break;
697 }
698 }
699
700 if (type < 0) {
701 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700702 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700703
Mathias Agopian8b736f12012-08-13 17:54:26 -0700704 // TODO: Not sure if display density should handled by SF any longer
705 class Density {
706 static int getDensityFromProperty(char const* propName) {
707 char property[PROPERTY_VALUE_MAX];
708 int density = 0;
709 if (property_get(propName, property, NULL) > 0) {
710 density = atoi(property);
711 }
712 return density;
713 }
714 public:
715 static int getEmuDensity() {
716 return getDensityFromProperty("qemu.sf.lcd_density"); }
717 static int getBuildDensity() {
718 return getDensityFromProperty("ro.sf.lcd_density"); }
719 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700720
Dan Stoza7f7da322014-05-02 15:26:25 -0700721 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700724 DisplayInfo info = DisplayInfo();
725
Dan Stoza9e56aa02015-11-02 13:00:03 -0800726 float xdpi = hwConfig->getDpiX();
727 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700728
729 if (type == DisplayDevice::DISPLAY_PRIMARY) {
730 // The density of the device is provided by a build property
731 float density = Density::getBuildDensity() / 160.0f;
732 if (density == 0) {
733 // the build doesn't provide a density -- this is wrong!
734 // use xdpi instead
735 ALOGE("ro.sf.lcd_density must be defined as a build property");
736 density = xdpi / 160.0f;
737 }
738 if (Density::getEmuDensity()) {
739 // if "qemu.sf.lcd_density" is specified, it overrides everything
740 xdpi = ydpi = density = Density::getEmuDensity();
741 density /= 160.0f;
742 }
743 info.density = density;
744
745 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000746 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
747 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700748 } else {
749 // TODO: where should this value come from?
750 static const int TV_DENSITY = 213;
751 info.density = TV_DENSITY / 160.0f;
752 info.orientation = 0;
753 }
754
Dan Stoza9e56aa02015-11-02 13:00:03 -0800755 info.w = hwConfig->getWidth();
756 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700757 info.xdpi = xdpi;
758 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900760 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800761
Andy McFadden91b2ca82014-06-13 14:04:23 -0700762 // This is how far in advance a buffer must be queued for
763 // presentation at a given time. If you want a buffer to appear
764 // on the screen at time N, you must submit the buffer before
765 // (N - presentationDeadline).
766 //
767 // Normally it's one full refresh period (to give SF a chance to
768 // latch the buffer), but this can be reduced by configuring a
769 // DispSync offset. Any additional delays introduced by the hardware
770 // composer or panel must be accounted for here.
771 //
772 // We add an additional 1ms to allow for processing time and
773 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800774 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800775 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700776
777 // All non-virtual displays are currently considered secure.
778 info.secure = true;
779
Michael Wright28f24d02016-07-12 13:30:53 -0700780 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700781 }
782
Dan Stoza7f7da322014-05-02 15:26:25 -0700783 return NO_ERROR;
784}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700785
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800786status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700787 DisplayStatInfo* stats) {
788 if (stats == NULL) {
789 return BAD_VALUE;
790 }
791
792 // FIXME for now we always return stats for the primary display
793 memset(stats, 0, sizeof(*stats));
794 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
795 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
796 return NO_ERROR;
797}
798
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700799int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800800 if (display == NULL) {
801 ALOGE("%s : display is NULL", __func__);
802 return BAD_VALUE;
803 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700804
805 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700806 if (device != NULL) {
807 return device->getActiveConfig();
808 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700809
Dan Stoza24a42e92015-03-09 10:04:11 -0700810 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700811}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700812
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700813void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
814 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
815 this);
816 int32_t type = hw->getDisplayType();
817 int currentMode = hw->getActiveConfig();
818
819 if (mode == currentMode) {
820 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
821 return;
822 }
823
824 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
825 ALOGW("Trying to set config for virtual display");
826 return;
827 }
828
829 hw->setActiveConfig(mode);
830 getHwComposer().setActiveConfig(type, mode);
831}
832
833status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
834 class MessageSetActiveConfig: public MessageBase {
835 SurfaceFlinger& mFlinger;
836 sp<IBinder> mDisplay;
837 int mMode;
838 public:
839 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
840 int mode) :
841 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
842 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700843 Vector<DisplayInfo> configs;
844 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700845 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700846 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700847 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700848 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700849 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700850 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
851 if (hw == NULL) {
852 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700853 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700854 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
855 ALOGW("Attempt to set active config = %d for virtual display",
856 mMode);
857 } else {
858 mFlinger.setActiveConfigInternal(hw, mMode);
859 }
860 return true;
861 }
862 };
863 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
864 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700865 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700866}
Michael Wright28f24d02016-07-12 13:30:53 -0700867status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
868 Vector<android_color_mode_t>* outColorModes) {
869 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
870 return BAD_VALUE;
871 }
872
873 if (!display.get()) {
874 return NAME_NOT_FOUND;
875 }
876
877 int32_t type = NAME_NOT_FOUND;
878 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
879 if (display == mBuiltinDisplays[i]) {
880 type = i;
881 break;
882 }
883 }
884
885 if (type < 0) {
886 return type;
887 }
888
889 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
890 outColorModes->clear();
891 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
892
893 return NO_ERROR;
894}
895
896android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700897 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700898 if (device != nullptr) {
899 return device->getActiveColorMode();
900 }
901 return static_cast<android_color_mode_t>(BAD_VALUE);
902}
903
904void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
905 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700906 int32_t type = hw->getDisplayType();
907 android_color_mode_t currentMode = hw->getActiveColorMode();
908
909 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700910 return;
911 }
912
913 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
914 ALOGW("Trying to set config for virtual display");
915 return;
916 }
917
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600918 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
919 hw->getDisplayType());
920
Michael Wright28f24d02016-07-12 13:30:53 -0700921 hw->setActiveColorMode(mode);
922 getHwComposer().setActiveColorMode(type, mode);
923}
924
925
926status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
927 android_color_mode_t colorMode) {
928 class MessageSetActiveColorMode: public MessageBase {
929 SurfaceFlinger& mFlinger;
930 sp<IBinder> mDisplay;
931 android_color_mode_t mMode;
932 public:
933 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
934 android_color_mode_t mode) :
935 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
936 virtual bool handler() {
937 Vector<android_color_mode_t> modes;
938 mFlinger.getDisplayColorModes(mDisplay, &modes);
939 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
940 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600941 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
942 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700943 return true;
944 }
945 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
946 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600947 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
948 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700949 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600950 ALOGW("Attempt to set active color mode %s %d for virtual display",
951 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700952 } else {
953 mFlinger.setActiveColorModeInternal(hw, mMode);
954 }
955 return true;
956 }
957 };
958 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
959 postMessageSync(msg);
960 return NO_ERROR;
961}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700962
Svetoslavd85084b2014-03-20 10:28:31 -0700963status_t SurfaceFlinger::clearAnimationFrameStats() {
964 Mutex::Autolock _l(mStateLock);
965 mAnimFrameTracker.clearStats();
966 return NO_ERROR;
967}
968
969status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
970 Mutex::Autolock _l(mStateLock);
971 mAnimFrameTracker.getStats(outStats);
972 return NO_ERROR;
973}
974
Dan Stozac4f471e2016-03-24 09:31:08 -0700975status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
976 HdrCapabilities* outCapabilities) const {
977 Mutex::Autolock _l(mStateLock);
978
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700979 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700980 if (displayDevice == nullptr) {
981 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
982 return BAD_VALUE;
983 }
984
985 std::unique_ptr<HdrCapabilities> capabilities =
986 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
987 if (capabilities) {
988 std::swap(*outCapabilities, *capabilities);
989 } else {
990 return BAD_VALUE;
991 }
992
993 return NO_ERROR;
994}
995
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700996status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
997 if (enable == mInjectVSyncs) {
998 return NO_ERROR;
999 }
1000
1001 if (enable) {
1002 mInjectVSyncs = enable;
1003 ALOGV("VSync Injections enabled");
1004 if (mVSyncInjector.get() == nullptr) {
1005 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001006 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001007 }
1008 mEventQueue.setEventThread(mInjectorEventThread);
1009 } else {
1010 mInjectVSyncs = enable;
1011 ALOGV("VSync Injections disabled");
1012 mEventQueue.setEventThread(mSFEventThread);
1013 mVSyncInjector.clear();
1014 }
1015 return NO_ERROR;
1016}
1017
1018status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1019 if (!mInjectVSyncs) {
1020 ALOGE("VSync Injections not enabled");
1021 return BAD_VALUE;
1022 }
1023 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1024 ALOGV("Injecting VSync inside SurfaceFlinger");
1025 mVSyncInjector->onInjectSyncEvent(when);
1026 }
1027 return NO_ERROR;
1028}
1029
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001030// ----------------------------------------------------------------------------
1031
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001032sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1033 ISurfaceComposer::VsyncSource vsyncSource) {
1034 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1035 return mSFEventThread->createEventConnection();
1036 } else {
1037 return mEventThread->createEventConnection();
1038 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001039}
1040
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001041// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001042
1043void SurfaceFlinger::waitForEvent() {
1044 mEventQueue.waitMessage();
1045}
1046
1047void SurfaceFlinger::signalTransaction() {
1048 mEventQueue.invalidate();
1049}
1050
1051void SurfaceFlinger::signalLayerUpdate() {
1052 mEventQueue.invalidate();
1053}
1054
1055void SurfaceFlinger::signalRefresh() {
1056 mEventQueue.refresh();
1057}
1058
1059status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001060 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001061 return mEventQueue.postMessage(msg, reltime);
1062}
1063
1064status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001065 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001066 status_t res = mEventQueue.postMessage(msg, reltime);
1067 if (res == NO_ERROR) {
1068 msg->wait();
1069 }
1070 return res;
1071}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001072
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001073void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001074 do {
1075 waitForEvent();
1076 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001077}
1078
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079void SurfaceFlinger::enableHardwareVsync() {
1080 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001081 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001083 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1084 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001085 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001086 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001087}
1088
Jesse Hall948fe0c2013-10-14 12:56:09 -07001089void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001090 Mutex::Autolock _l(mHWVsyncLock);
1091
Jesse Hall948fe0c2013-10-14 12:56:09 -07001092 if (makeAvailable) {
1093 mHWVsyncAvailable = true;
1094 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001095 // Hardware vsync is not currently available, so abort the resync
1096 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001097 return;
1098 }
1099
Dan Stoza9e56aa02015-11-02 13:00:03 -08001100 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1101 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001102
1103 mPrimaryDispSync.reset();
1104 mPrimaryDispSync.setPeriod(period);
1105
1106 if (!mPrimaryHWVsyncEnabled) {
1107 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001108 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1109 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001110 mPrimaryHWVsyncEnabled = true;
1111 }
1112}
1113
Jesse Hall948fe0c2013-10-14 12:56:09 -07001114void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001115 Mutex::Autolock _l(mHWVsyncLock);
1116 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001117 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1118 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001119 mPrimaryDispSync.endResync();
1120 mPrimaryHWVsyncEnabled = false;
1121 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001122 if (makeUnavailable) {
1123 mHWVsyncAvailable = false;
1124 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001125}
1126
Tim Murray4a4e4a22016-04-19 16:29:23 +00001127void SurfaceFlinger::resyncWithRateLimit() {
1128 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001129
1130 // No explicit locking is needed here since EventThread holds a lock while calling this method
1131 static nsecs_t sLastResyncAttempted = 0;
1132 const nsecs_t now = systemTime();
1133 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001134 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001135 }
Dan Stoza57164302017-05-08 14:03:54 -07001136 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001137}
1138
Steven Thomas3cfac282017-02-06 12:29:30 -08001139void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1140 nsecs_t timestamp) {
1141 Mutex::Autolock lock(mStateLock);
1142 // Ignore any vsyncs from the non-active hardware composer.
1143 if (composer != mHwc) {
1144 return;
1145 }
1146
Jamie Gennisd1700752013-10-14 12:22:52 -07001147 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001148
Jamie Gennisd1700752013-10-14 12:22:52 -07001149 { // Scope for the lock
1150 Mutex::Autolock _l(mHWVsyncLock);
1151 if (type == 0 && mPrimaryHWVsyncEnabled) {
1152 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001153 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001154 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001155
1156 if (needsHwVsync) {
1157 enableHardwareVsync();
1158 } else {
1159 disableHardwareVsync(false);
1160 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001161}
1162
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001163void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001164 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001165 *compositorTiming = mCompositorTiming;
1166}
1167
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001168void SurfaceFlinger::createDefaultDisplayDevice() {
1169 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1170 wp<IBinder> token = mBuiltinDisplays[type];
1171
1172 // All non-virtual displays are currently considered secure.
1173 const bool isSecure = true;
1174
1175 sp<IGraphicBufferProducer> producer;
1176 sp<IGraphicBufferConsumer> consumer;
1177 BufferQueue::createBufferQueue(&producer, &consumer);
1178
1179 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1180
1181 bool hasWideColorModes = false;
1182 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1183 for (android_color_mode_t colorMode : modes) {
1184 switch (colorMode) {
1185 case HAL_COLOR_MODE_DISPLAY_P3:
1186 case HAL_COLOR_MODE_ADOBE_RGB:
1187 case HAL_COLOR_MODE_DCI_P3:
1188 hasWideColorModes = true;
1189 break;
1190 default:
1191 break;
1192 }
1193 }
1194 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1195 token, fbs, producer, mRenderEngine->getEGLConfig(),
1196 hasWideColorModes && hasWideColorDisplay);
1197 mDisplays.add(token, hw);
1198 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1199 if (hasWideColorModes && hasWideColorDisplay) {
1200 defaultColorMode = HAL_COLOR_MODE_SRGB;
1201 }
1202 setActiveColorModeInternal(hw, defaultColorMode);
1203}
1204
1205void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001206 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001207
1208 if (composer->isUsingVrComposer()) {
1209 // We handle initializing the primary display device for the VR
1210 // window manager hwc explicitly at the time of transition.
1211 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1212 ALOGE("External displays are not supported by the vr hardware composer.");
1213 }
1214 return;
1215 }
1216
Dan Stoza9e56aa02015-11-02 13:00:03 -08001217 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1218 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001219 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1220 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001221 } else {
1222 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001223 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001224 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001225 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001226 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001227 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1228 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001229 }
1230 setTransactionFlags(eDisplayTransactionNeeded);
1231
Andy McFadden9e9689c2012-10-10 18:17:51 -07001232 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001233 }
Mathias Agopian86303202012-07-24 22:46:10 -07001234}
1235
Steven Thomas3cfac282017-02-06 12:29:30 -08001236void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1237 Mutex::Autolock lock(mStateLock);
1238 if (composer == mHwc) {
1239 repaintEverything();
1240 } else {
1241 // This isn't from our current hardware composer. If it's a callback
1242 // from the real composer, forward the refresh request to vr
1243 // flinger. Otherwise ignore it.
1244 if (!composer->isUsingVrComposer()) {
1245 mVrFlinger->OnHardwareComposerRefresh();
1246 }
1247 }
1248}
1249
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001252 getHwComposer().setVsyncEnabled(disp,
1253 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001254}
1255
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001256void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1257 for (size_t i = 0; i < layers.size(); ++i) {
1258 layers[i]->clearHwcLayers();
1259 }
1260}
1261
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001262// Note: it is assumed the caller holds |mStateLock| when this is called
1263void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001264 disableHardwareVsync(true);
1265 clearHwcLayers(mDrawingState.layersSortedByZ);
1266 clearHwcLayers(mCurrentState.layersSortedByZ);
1267 // Clear the drawing state so that the logic inside of
1268 // handleTransactionLocked will fire. It will determine the delta between
1269 // mCurrentState and mDrawingState and re-apply all changes when we make the
1270 // transition.
1271 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001272 // Release virtual display hwcId during vr mode transition.
1273 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1274 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1275 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1276 displayDevice->disconnect(getHwComposer());
1277 }
1278 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001279 mDisplays.clear();
1280}
1281
Steven Thomas050b2c82017-03-06 11:45:16 -08001282void SurfaceFlinger::updateVrFlinger() {
1283 if (!mVrFlinger)
1284 return;
1285 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1286 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001287 return;
1288 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001289
Steven Thomas050b2c82017-03-06 11:45:16 -08001290 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001291 // Construct new HWComposer without holding any locks.
1292 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001293
1294 // Set up the event handlers. This step is neccessary to initialize the internal state of
1295 // the hardware composer object properly. Our callbacks are designed such that if they are
1296 // triggered between now and the point where the display is properly re-initialized, they
1297 // will not have any effect, so this is safe to do here, before the lock is aquired.
1298 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001299 ALOGV("Vr HWC created");
1300 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001301
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001302 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001303
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304 if (vrFlingerRequestsDisplay) {
1305 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307 mHwc = mVrHwc;
1308 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310 } else {
1311 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001312
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001313 resetHwcLocked();
1314
1315 mHwc = mRealHwc;
1316 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001317 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001318
1319 mVisibleRegionsDirty = true;
1320 invalidateHwcGeometry();
1321
1322 // Explicitly re-initialize the primary display. This is because some other
1323 // parts of this class rely on the primary display always being available.
1324 createDefaultDisplayDevice();
1325
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001326 // Re-enable default display.
1327 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1328 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1329 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1330
1331 // Reset the timing values to account for the period of the swapped in HWC
1332 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1333 const nsecs_t period = activeConfig->getVsyncPeriod();
1334 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1335
1336 // Use phase of 0 since phase is not known.
1337 // Use latency of 0, which will snap to the ideal latency.
1338 setCompositorTimingSnapped(0, period, 0);
1339 });
1340 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001341
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001342 android_atomic_or(1, &mRepaintEverything);
1343 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001344}
1345
Mathias Agopian4fec8732012-06-29 14:12:52 -07001346void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001347 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001348 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001349 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001350 bool frameMissed = !mHadClientComposition &&
1351 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001352 (mPreviousPresentFence->getSignalTime() ==
1353 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001354 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001355 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001356 signalLayerUpdate();
1357 break;
1358 }
1359
Steven Thomas050b2c82017-03-06 11:45:16 -08001360 // Now that we're going to make it to the handleMessageTransaction()
1361 // call below it's safe to call updateVrFlinger(), which will
1362 // potentially trigger a display handoff.
1363 updateVrFlinger();
1364
Dan Stoza6b9454d2014-11-07 16:00:59 -08001365 bool refreshNeeded = handleMessageTransaction();
1366 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001367 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001368 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001369 // Signal a refresh if a transaction modified the window state,
1370 // a new buffer was latched, or if HWC has requested a full
1371 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001372 signalRefresh();
1373 }
1374 break;
1375 }
1376 case MessageQueue::REFRESH: {
1377 handleMessageRefresh();
1378 break;
1379 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001380 }
1381}
1382
Dan Stoza6b9454d2014-11-07 16:00:59 -08001383bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001384 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001385 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001386 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001388 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001389 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001390}
1391
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001395}
1396
1397void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001398 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001399
Pablo Ceballos40845df2016-01-25 17:41:15 -08001400 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001401
Brian Andersond6927fb2016-07-23 23:37:30 -07001402 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001403 rebuildLayerStacks();
1404 setUpHWComposer();
1405 doDebugFlashRegions();
1406 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001407 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001408
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001409 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001410
1411 mHadClientComposition = false;
1412 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1413 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1414 mHadClientComposition = mHadClientComposition ||
1415 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1416 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001417
Dan Stoza9e56aa02015-11-02 13:00:03 -08001418 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001420
Mathias Agopiancd60f992012-08-16 16:28:27 -07001421void SurfaceFlinger::doDebugFlashRegions()
1422{
1423 // is debugging enabled
1424 if (CC_LIKELY(!mDebugRegion))
1425 return;
1426
1427 const bool repaintEverything = mRepaintEverything;
1428 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1429 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001430 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001431 // transform the dirty region into this screen's coordinate space
1432 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1433 if (!dirtyRegion.isEmpty()) {
1434 // redraw the whole screen
1435 doComposeSurfaces(hw, Region(hw->bounds()));
1436
1437 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001438 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001439 RenderEngine& engine(getRenderEngine());
1440 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1441
Mathias Agopianda27af92012-09-13 18:17:13 -07001442 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001443 }
1444 }
1445 }
1446
1447 postFramebuffer();
1448
1449 if (mDebugRegion > 1) {
1450 usleep(mDebugRegion * 1000);
1451 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001452
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001454 auto& displayDevice = mDisplays[displayId];
1455 if (!displayDevice->isDisplayOn()) {
1456 continue;
1457 }
1458
1459 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001460 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1461 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001462 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001463}
1464
Brian Andersond6927fb2016-07-23 23:37:30 -07001465void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001467 ATRACE_CALL();
1468 ALOGV("preComposition");
1469
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001471 mDrawingState.traverseInZOrder([&](Layer* layer) {
1472 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001473 needExtraInvalidate = true;
1474 }
Robert Carr2047fae2016-11-28 14:09:09 -08001475 });
1476
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 if (needExtraInvalidate) {
1478 signalLayerUpdate();
1479 }
1480}
1481
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001482void SurfaceFlinger::updateCompositorTiming(
1483 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1484 std::shared_ptr<FenceTime>& presentFenceTime) {
1485 // Update queue of past composite+present times and determine the
1486 // most recently known composite to present latency.
1487 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1488 nsecs_t compositeToPresentLatency = -1;
1489 while (!mCompositePresentTimes.empty()) {
1490 CompositePresentTime& cpt = mCompositePresentTimes.front();
1491 // Cached values should have been updated before calling this method,
1492 // which helps avoid duplicate syscalls.
1493 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1494 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1495 break;
1496 }
1497 compositeToPresentLatency = displayTime - cpt.composite;
1498 mCompositePresentTimes.pop();
1499 }
1500
1501 // Don't let mCompositePresentTimes grow unbounded, just in case.
1502 while (mCompositePresentTimes.size() > 16) {
1503 mCompositePresentTimes.pop();
1504 }
1505
Brian Andersond0010582017-03-07 13:20:31 -08001506 setCompositorTimingSnapped(
1507 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1508}
1509
1510void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1511 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001512 // Integer division and modulo round toward 0 not -inf, so we need to
1513 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001514 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001515 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1516 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1517
Brian Andersond0010582017-03-07 13:20:31 -08001518 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1519 if (idealLatency <= 0) {
1520 idealLatency = vsyncInterval;
1521 }
1522
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001523 // Snap the latency to a value that removes scheduling jitter from the
1524 // composition and present times, which often have >1ms of jitter.
1525 // Reducing jitter is important if an app attempts to extrapolate
1526 // something (such as user input) to an accurate diasplay time.
1527 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1528 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001529 nsecs_t bias = vsyncInterval / 2;
1530 int64_t extraVsyncs =
1531 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1532 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1533 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001534
Brian Andersond0010582017-03-07 13:20:31 -08001535 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1537 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001538 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001539}
1540
1541void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001542{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001543 ATRACE_CALL();
1544 ALOGV("postComposition");
1545
Brian Anderson3546a3f2016-07-14 11:51:14 -07001546 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001547 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001548 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001549 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001550 }
1551
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552 // |mStateLock| not needed as we are on the main thread
1553 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001554
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001555 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001556 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1557 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1558 glCompositionDoneFenceTime =
1559 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1560 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1561 } else {
1562 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1563 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001564
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001565 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001566 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1567 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1568 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001569
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1571 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1572
1573 // We use the refreshStartTime which might be sampled a little later than
1574 // when we started doing work for this frame, but that should be okay
1575 // since updateCompositorTiming has snapping logic.
1576 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001577 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001578 CompositorTiming compositorTiming;
1579 {
1580 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1581 compositorTiming = mCompositorTiming;
1582 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001583
Robert Carr2047fae2016-11-28 14:09:09 -08001584 mDrawingState.traverseInZOrder([&](Layer* layer) {
1585 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001586 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001587 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001588 recordBufferingStats(layer->getName().string(),
1589 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001590 }
Robert Carr2047fae2016-11-28 14:09:09 -08001591 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001592
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001593 if (presentFenceTime->isValid()) {
1594 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001595 enableHardwareVsync();
1596 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001597 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001598 }
1599 }
1600
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001601 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001602 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001603 enableHardwareVsync();
1604 }
1605 }
1606
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001607 if (mAnimCompositionPending) {
1608 mAnimCompositionPending = false;
1609
Brian Anderson4e606e32017-03-16 15:34:57 -07001610 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001611 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001612 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001613 } else {
1614 // The HWC doesn't support present fences, so use the refresh
1615 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001616 nsecs_t presentTime =
1617 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001618 mAnimFrameTracker.setActualPresentTime(presentTime);
1619 }
1620 mAnimFrameTracker.advanceFrame();
1621 }
Dan Stozab90cf072015-03-05 11:05:59 -08001622
1623 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1624 return;
1625 }
1626
1627 nsecs_t currentTime = systemTime();
1628 if (mHasPoweredOff) {
1629 mHasPoweredOff = false;
1630 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001631 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001632 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001633 if (numPeriods < NUM_BUCKETS - 1) {
1634 mFrameBuckets[numPeriods] += elapsedTime;
1635 } else {
1636 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1637 }
1638 mTotalTime += elapsedTime;
1639 }
1640 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641}
1642
1643void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001644 ATRACE_CALL();
1645 ALOGV("rebuildLayerStacks");
1646
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001648 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1649 ATRACE_CALL();
1650 mVisibleRegionsDirty = false;
1651 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001652
Jeff Sharkey76488112017-02-27 14:15:18 -07001653 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1654 Region opaqueRegion;
1655 Region dirtyRegion;
1656 Vector<sp<Layer>> layersSortedByZ;
1657 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1658 const Transform& tr(displayDevice->getTransform());
1659 const Rect bounds(displayDevice->getBounds());
1660 if (displayDevice->isDisplayOn()) {
1661 computeVisibleRegions(
1662 displayDevice->getLayerStack(), dirtyRegion,
1663 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001664
Jeff Sharkey76488112017-02-27 14:15:18 -07001665 mDrawingState.traverseInZOrder([&](Layer* layer) {
1666 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1667 Region drawRegion(tr.transform(
1668 layer->visibleNonTransparentRegion));
1669 drawRegion.andSelf(bounds);
1670 if (!drawRegion.isEmpty()) {
1671 layersSortedByZ.add(layer);
1672 } else {
1673 // Clear out the HWC layer if this layer was
1674 // previously visible, but no longer is
1675 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1676 nullptr);
1677 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001678 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001679 // WM changes displayDevice->layerStack upon sleep/awake.
1680 // Here we make sure we delete the HWC layers even if
1681 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001682 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1683 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001684 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001685 });
1686 }
1687 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1688 displayDevice->undefinedRegion.set(bounds);
1689 displayDevice->undefinedRegion.subtractSelf(
1690 tr.transform(opaqueRegion));
1691 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001692 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001693 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001695
Romain Guy0147a172017-06-01 13:53:56 -07001696mat4 SurfaceFlinger::computeSaturationMatrix() const {
1697 if (mSaturation == 1.0f) {
1698 return mat4();
1699 }
1700
1701 // Rec.709 luma coefficients
1702 float3 luminance{0.213f, 0.715f, 0.072f};
1703 luminance *= 1.0f - mSaturation;
1704 return mat4(
1705 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1706 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1707 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1708 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1709 );
1710}
1711
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001712// pickColorMode translates a given dataspace into the best available color mode.
1713// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001714android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001715 switch (dataSpace) {
1716 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1717 // system expects.
1718 case HAL_DATASPACE_UNKNOWN:
1719 case HAL_DATASPACE_SRGB:
1720 case HAL_DATASPACE_V0_SRGB:
1721 return HAL_COLOR_MODE_SRGB;
1722 break;
1723
1724 case HAL_DATASPACE_DISPLAY_P3:
1725 return HAL_COLOR_MODE_DISPLAY_P3;
1726 break;
1727
1728 default:
1729 // TODO (courtneygo): Do we want to assert an error here?
1730 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1731 dataSpace);
1732 return HAL_COLOR_MODE_SRGB;
1733 break;
1734 }
1735}
1736
Romain Guy0147a172017-06-01 13:53:56 -07001737android_dataspace SurfaceFlinger::bestTargetDataSpace(
1738 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001739 // Only support sRGB and Display-P3 right now.
1740 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1741 return HAL_DATASPACE_DISPLAY_P3;
1742 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001743 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1744 return HAL_DATASPACE_DISPLAY_P3;
1745 }
1746 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1747 return HAL_DATASPACE_DISPLAY_P3;
1748 }
1749
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001750 return HAL_DATASPACE_V0_SRGB;
1751}
1752
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001754 ATRACE_CALL();
1755 ALOGV("setUpHWComposer");
1756
Jesse Hall028dc8f2013-08-20 16:35:32 -07001757 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001758 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1759 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1760 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1761
1762 // If nothing has changed (!dirty), don't recompose.
1763 // If something changed, but we don't currently have any visible layers,
1764 // and didn't when we last did a composition, then skip it this time.
1765 // The second rule does two things:
1766 // - When all layers are removed from a display, we'll emit one black
1767 // frame, then nothing more until we get new layers.
1768 // - When a display is created with a private layer stack, we won't
1769 // emit any black frames until a layer is added to the layer stack.
1770 bool mustRecompose = dirty && !(empty && wasEmpty);
1771
1772 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1773 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1774 mustRecompose ? "doing" : "skipping",
1775 dirty ? "+" : "-",
1776 empty ? "+" : "-",
1777 wasEmpty ? "+" : "-");
1778
Dan Stoza71433162014-02-04 16:22:36 -08001779 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001780
1781 if (mustRecompose) {
1782 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1783 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001784 }
1785
Dan Stoza9e56aa02015-11-02 13:00:03 -08001786 // build the h/w work list
1787 if (CC_UNLIKELY(mGeometryInvalid)) {
1788 mGeometryInvalid = false;
1789 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1790 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1791 const auto hwcId = displayDevice->getHwcDisplayId();
1792 if (hwcId >= 0) {
1793 const Vector<sp<Layer>>& currentLayers(
1794 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001795 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001796 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001797 if (!layer->hasHwcLayer(hwcId)) {
1798 auto hwcLayer = mHwc->createLayer(hwcId);
1799 if (hwcLayer) {
1800 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1801 } else {
1802 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001803 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001804 }
1805 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001806
Robert Carrae060832016-11-28 10:51:00 -08001807 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001808 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001810 }
1811 }
1812 }
1813 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001814 }
Riley Andrews03414a12014-07-01 14:22:59 -07001815
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001816
Romain Guy0147a172017-06-01 13:53:56 -07001817 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001818
Dan Stoza9e56aa02015-11-02 13:00:03 -08001819 // Set the per-frame data
1820 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1821 auto& displayDevice = mDisplays[displayId];
1822 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001823
Dan Stoza9e56aa02015-11-02 13:00:03 -08001824 if (hwcId < 0) {
1825 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001826 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001827 if (colorMatrix != mPreviousColorMatrix) {
1828 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1829 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1830 "display %zd: %d", displayId, result);
1831 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1833 layer->setPerFrameData(displayDevice);
1834 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001835
1836 if (hasWideColorDisplay) {
1837 android_color_mode newColorMode;
1838 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1839
1840 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1841 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1842 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1843 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1844 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1845 }
1846 newColorMode = pickColorMode(newDataSpace);
1847
1848 setActiveColorModeInternal(displayDevice, newColorMode);
1849 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001850 }
1851
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001852 mPreviousColorMatrix = colorMatrix;
1853
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001855 auto& displayDevice = mDisplays[displayId];
1856 if (!displayDevice->isDisplayOn()) {
1857 continue;
1858 }
1859
1860 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1862 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001863 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001865
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866void SurfaceFlinger::doComposition() {
1867 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 ALOGV("doComposition");
1869
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001870 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001871 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001872 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001873 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001874 // transform the dirty region into this screen's coordinate space
1875 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001876
1877 // repaint the framebuffer (if needed)
1878 doDisplayComposition(hw, dirtyRegion);
1879
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880 hw->dirtyRegion.clear();
1881 hw->flip(hw->swapRegion);
1882 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001883 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001884 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001885 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001886}
1887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001888void SurfaceFlinger::postFramebuffer()
1889{
Mathias Agopian841cde52012-03-01 15:44:37 -08001890 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001892
Mathias Agopiana44b0412011-10-16 18:46:35 -07001893 const nsecs_t now = systemTime();
1894 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001895
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1897 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001898 if (!displayDevice->isDisplayOn()) {
1899 continue;
1900 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 const auto hwcId = displayDevice->getHwcDisplayId();
1902 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001903 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001904 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001905 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001906 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001907 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1908 sp<Fence> releaseFence = Fence::NO_FENCE;
1909 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1910 releaseFence = displayDevice->getClientTargetAcquireFence();
1911 } else {
1912 auto hwcLayer = layer->getHwcLayer(hwcId);
1913 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001914 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001915 layer->onLayerDisplayed(releaseFence);
1916 }
1917 if (hwcId >= 0) {
1918 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001919 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001920 }
1921
Mathias Agopiana44b0412011-10-16 18:46:35 -07001922 mLastSwapBufferTime = systemTime() - now;
1923 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001924
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001925 // |mStateLock| not needed as we are on the main thread
1926 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001927 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1928 logFrameStats();
1929 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001930}
1931
Mathias Agopian87baae12012-07-31 12:38:26 -07001932void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001933{
Mathias Agopian841cde52012-03-01 15:44:37 -08001934 ATRACE_CALL();
1935
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001936 // here we keep a copy of the drawing state (that is the state that's
1937 // going to be overwritten by handleTransactionLocked()) outside of
1938 // mStateLock so that the side-effects of the State assignment
1939 // don't happen with mStateLock held (which can cause deadlocks).
1940 State drawingState(mDrawingState);
1941
Mathias Agopianca4d3602011-05-19 15:38:14 -07001942 Mutex::Autolock _l(mStateLock);
1943 const nsecs_t now = systemTime();
1944 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001945
Mathias Agopianca4d3602011-05-19 15:38:14 -07001946 // Here we're guaranteed that some transaction flags are set
1947 // so we can call handleTransactionLocked() unconditionally.
1948 // We call getTransactionFlags(), which will also clear the flags,
1949 // with mStateLock held to guarantee that mCurrentState won't change
1950 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001951
Mathias Agopiane57f2922012-08-09 16:29:12 -07001952 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001953 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001954
Mathias Agopianca4d3602011-05-19 15:38:14 -07001955 mLastTransactionTime = systemTime() - now;
1956 mDebugInTransaction = 0;
1957 invalidateHwcGeometry();
1958 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001959}
1960
Mathias Agopian87baae12012-07-31 12:38:26 -07001961void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001962{
Dan Stoza7dde5992015-05-22 09:51:44 -07001963 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001964 mCurrentState.traverseInZOrder([](Layer* layer) {
1965 layer->notifyAvailableFrames();
1966 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001967
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001968 /*
1969 * Traversal of the children
1970 * (perform the transaction for each of them if needed)
1971 */
1972
Mathias Agopian3559b072012-08-15 13:46:03 -07001973 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001974 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001976 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977
1978 const uint32_t flags = layer->doTransaction(0);
1979 if (flags & Layer::eVisibleRegion)
1980 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001981 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001982 }
1983
1984 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001985 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986 */
1987
Mathias Agopiane57f2922012-08-09 16:29:12 -07001988 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001989 // here we take advantage of Vector's copy-on-write semantics to
1990 // improve performance by skipping the transaction entirely when
1991 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001992 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1993 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001994 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001995 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001996 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001997 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001998
1999 // find the displays that were removed
2000 // (ie: in drawing state but not in current state)
2001 // also handle displays that changed
2002 // (ie: displays that are in both lists)
2003 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002004 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2005 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002006 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002007 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002008 // Call makeCurrent() on the primary display so we can
2009 // be sure that nothing associated with this display
2010 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002011 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002012 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002014 if (hw != NULL)
2015 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002016 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002017 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002018 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002019 } else {
2020 ALOGW("trying to remove the main display");
2021 }
2022 } else {
2023 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002024 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002025 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002026 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2027 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002028 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002029 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002030 // recreating the DisplayDevice, so we just remove it
2031 // from the drawing state, so that it get re-added
2032 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002033 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002034 if (hw != NULL)
2035 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002036 mDisplays.removeItem(display);
2037 mDrawingState.displays.removeItemsAt(i);
2038 dc--; i--;
2039 // at this point we must loop to the next item
2040 continue;
2041 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002042
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002043 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002044 if (disp != NULL) {
2045 if (state.layerStack != draw[i].layerStack) {
2046 disp->setLayerStack(state.layerStack);
2047 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002048 if ((state.orientation != draw[i].orientation)
2049 || (state.viewport != draw[i].viewport)
2050 || (state.frame != draw[i].frame))
2051 {
2052 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002053 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002054 }
Michael Lentine47e45402014-07-18 15:34:25 -07002055 if (state.width != draw[i].width || state.height != draw[i].height) {
2056 disp->setDisplaySize(state.width, state.height);
2057 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002058 }
2059 }
2060 }
2061
2062 // find displays that were added
2063 // (ie: in current state but not in drawing state)
2064 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002065 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002066 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002067
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002068 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002069 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002070 sp<IGraphicBufferProducer> bqProducer;
2071 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002072 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002073
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002075 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002076 // Virtual displays without a surface are dormant:
2077 // they have external state (layer stack, projection,
2078 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002079 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002080
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002081 // Allow VR composer to use virtual displays.
2082 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002083 int width = 0;
2084 int status = state.surface->query(
2085 NATIVE_WINDOW_WIDTH, &width);
2086 ALOGE_IF(status != NO_ERROR,
2087 "Unable to query width (%d)", status);
2088 int height = 0;
2089 status = state.surface->query(
2090 NATIVE_WINDOW_HEIGHT, &height);
2091 ALOGE_IF(status != NO_ERROR,
2092 "Unable to query height (%d)", status);
2093 int intFormat = 0;
2094 status = state.surface->query(
2095 NATIVE_WINDOW_FORMAT, &intFormat);
2096 ALOGE_IF(status != NO_ERROR,
2097 "Unable to query format (%d)", status);
2098 auto format = static_cast<android_pixel_format_t>(
2099 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002100
Dan Stoza8cf150a2016-08-02 10:27:31 -07002101 mHwc->allocateVirtualDisplay(width, height, &format,
2102 &hwcId);
2103 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002104
Dan Stoza5cf424b2016-05-20 14:02:39 -07002105 // TODO: Plumb requested format back up to consumer
2106
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 sp<VirtualDisplaySurface> vds =
2108 new VirtualDisplaySurface(*mHwc,
2109 hwcId, state.surface, bqProducer,
2110 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002111
2112 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002113 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002114 }
2115 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002116 ALOGE_IF(state.surface!=NULL,
2117 "adding a supported display, but rendering "
2118 "surface is provided (%p), ignoring it",
2119 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002120
2121 hwcId = state.type;
2122 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2123 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002124 }
2125
2126 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002127 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002128 sp<DisplayDevice> hw =
2129 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2130 dispSurface, producer,
2131 mRenderEngine->getEGLConfig(),
2132 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002133 hw->setLayerStack(state.layerStack);
2134 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002135 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002136 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002137 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002139 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002140 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002141 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002142 }
2143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002145 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146
Mathias Agopian84300952012-11-21 16:02:13 -08002147 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2148 // The transform hint might have changed for some layers
2149 // (either because a display has changed, or because a layer
2150 // as changed).
2151 //
2152 // Walk through all the layers in currentLayers,
2153 // and update their transform hint.
2154 //
2155 // If a layer is visible only on a single display, then that
2156 // display is used to calculate the hint, otherwise we use the
2157 // default display.
2158 //
2159 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2160 // the hint is set before we acquire a buffer from the surface texture.
2161 //
2162 // NOTE: layer transactions have taken place already, so we use their
2163 // drawing state. However, SurfaceFlinger's own transaction has not
2164 // happened yet, so we must use the current state layer list
2165 // (soon to become the drawing state list).
2166 //
2167 sp<const DisplayDevice> disp;
2168 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002169 bool first = true;
2170 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002171 // NOTE: we rely on the fact that layers are sorted by
2172 // layerStack first (so we don't have to traverse the list
2173 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002174 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002175 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002176 currentlayerStack = layerStack;
2177 // figure out if this layerstack is mirrored
2178 // (more than one display) if so, pick the default display,
2179 // if not, pick the only display it's on.
2180 disp.clear();
2181 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2182 sp<const DisplayDevice> hw(mDisplays[dpy]);
2183 if (hw->getLayerStack() == currentlayerStack) {
2184 if (disp == NULL) {
2185 disp = hw;
2186 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002187 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002188 break;
2189 }
2190 }
2191 }
2192 }
Chet Haase91d25932013-04-11 15:24:55 -07002193 if (disp == NULL) {
2194 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2195 // redraw after transform hint changes. See bug 8508397.
2196
2197 // could be null when this layer is using a layerStack
2198 // that is not visible on any display. Also can occur at
2199 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002200 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002201 }
Chet Haase91d25932013-04-11 15:24:55 -07002202 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002203
2204 first = false;
2205 });
Mathias Agopian84300952012-11-21 16:02:13 -08002206 }
2207
2208
Mathias Agopian3559b072012-08-15 13:46:03 -07002209 /*
2210 * Perform our own transaction if needed
2211 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002212
2213 if (mLayersAdded) {
2214 mLayersAdded = false;
2215 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002216 mVisibleRegionsDirty = true;
2217 }
2218
2219 // some layers might have been removed, so
2220 // we need to update the regions they're exposing.
2221 if (mLayersRemoved) {
2222 mLayersRemoved = false;
2223 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002224 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002225 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002226 // this layer is not visible anymore
2227 // TODO: we could traverse the tree from front to back and
2228 // compute the actual visible region
2229 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002230 Region visibleReg;
2231 visibleReg.set(layer->computeScreenBounds());
2232 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002233 }
Robert Carr2047fae2016-11-28 14:09:09 -08002234 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002235 }
2236
2237 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002238
2239 updateCursorAsync();
2240}
2241
2242void SurfaceFlinger::updateCursorAsync()
2243{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2245 auto& displayDevice = mDisplays[displayId];
2246 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002247 continue;
2248 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249
2250 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2251 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002252 }
2253 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002254}
2255
2256void SurfaceFlinger::commitTransaction()
2257{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002258 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002259 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002260 for (const auto& l : mLayersPendingRemoval) {
2261 recordBufferingStats(l->getName().string(),
2262 l->getOccupancyHistory(true));
2263 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002264 }
2265 mLayersPendingRemoval.clear();
2266 }
2267
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002268 // If this transaction is part of a window animation then the next frame
2269 // we composite should be considered an animation as well.
2270 mAnimCompositionPending = mAnimTransactionPending;
2271
Mathias Agopian4fec8732012-06-29 14:12:52 -07002272 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002273 mDrawingState.traverseInZOrder([](Layer* layer) {
2274 layer->commitChildList();
2275 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002276 mTransactionPending = false;
2277 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002278 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002279}
2280
Robert Carr2047fae2016-11-28 14:09:09 -08002281void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002282 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002283{
Mathias Agopian841cde52012-03-01 15:44:37 -08002284 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002285 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002286
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287 Region aboveOpaqueLayers;
2288 Region aboveCoveredLayers;
2289 Region dirty;
2290
Mathias Agopian87baae12012-07-31 12:38:26 -07002291 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292
Robert Carr2047fae2016-11-28 14:09:09 -08002293 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002295 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296
Jesse Hall01e29052013-02-19 16:13:35 -08002297 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002298 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002299 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002300
Mathias Agopianab028732010-03-16 16:41:46 -07002301 /*
2302 * opaqueRegion: area of a surface that is fully opaque.
2303 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002304 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002305
2306 /*
2307 * visibleRegion: area of a surface that is visible on screen
2308 * and not fully transparent. This is essentially the layer's
2309 * footprint minus the opaque regions above it.
2310 * Areas covered by a translucent surface are considered visible.
2311 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002312 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002313
2314 /*
2315 * coveredRegion: area of a surface that is covered by all
2316 * visible regions above it (which includes the translucent areas).
2317 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002318 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002319
Jesse Halla8026d22012-09-25 13:25:04 -07002320 /*
2321 * transparentRegion: area of a surface that is hinted to be completely
2322 * transparent. This is only used to tell when the layer has no visible
2323 * non-transparent regions and can be removed from the layer list. It
2324 * does not affect the visibleRegion of this layer or any layers
2325 * beneath it. The hint may not be correct if apps don't respect the
2326 * SurfaceView restrictions (which, sadly, some don't).
2327 */
2328 Region transparentRegion;
2329
Mathias Agopianab028732010-03-16 16:41:46 -07002330
2331 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002332 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002333 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002334 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002336 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002337 if (!visibleRegion.isEmpty()) {
2338 // Remove the transparent area from the visible region
2339 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002340 if (tr.preserveRects()) {
2341 // transform the transparent region
2342 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002343 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002344 // transformation too complex, can't do the
2345 // transparent region optimization.
2346 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002347 }
Mathias Agopianab028732010-03-16 16:41:46 -07002348 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349
Mathias Agopianab028732010-03-16 16:41:46 -07002350 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002351 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002352 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002353 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2354 // the opaque region is the layer's footprint
2355 opaqueRegion = visibleRegion;
2356 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357 }
2358 }
2359
Mathias Agopianab028732010-03-16 16:41:46 -07002360 // Clip the covered region to the visible region
2361 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2362
2363 // Update aboveCoveredLayers for next (lower) layer
2364 aboveCoveredLayers.orSelf(visibleRegion);
2365
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366 // subtract the opaque region covered by the layers above us
2367 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002368
2369 // compute this layer's dirty region
2370 if (layer->contentDirty) {
2371 // we need to invalidate the whole region
2372 dirty = visibleRegion;
2373 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002374 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375 layer->contentDirty = false;
2376 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002377 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002378 * the exposed region consists of two components:
2379 * 1) what's VISIBLE now and was COVERED before
2380 * 2) what's EXPOSED now less what was EXPOSED before
2381 *
2382 * note that (1) is conservative, we start with the whole
2383 * visible region but only keep what used to be covered by
2384 * something -- which mean it may have been exposed.
2385 *
2386 * (2) handles areas that were not covered by anything but got
2387 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002388 */
Mathias Agopianab028732010-03-16 16:41:46 -07002389 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002390 const Region oldVisibleRegion = layer->visibleRegion;
2391 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002392 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2393 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002394 }
2395 dirty.subtractSelf(aboveOpaqueLayers);
2396
2397 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002398 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399
Mathias Agopianab028732010-03-16 16:41:46 -07002400 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002402
Jesse Halla8026d22012-09-25 13:25:04 -07002403 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404 layer->setVisibleRegion(visibleRegion);
2405 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002406 layer->setVisibleNonTransparentRegion(
2407 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002408 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409
Mathias Agopian87baae12012-07-31 12:38:26 -07002410 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411}
2412
Mathias Agopian87baae12012-07-31 12:38:26 -07002413void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2414 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002415 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002416 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2417 if (hw->getLayerStack() == layerStack) {
2418 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002419 }
2420 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002421}
2422
Dan Stoza6b9454d2014-11-07 16:00:59 -08002423bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002425 ALOGV("handlePageFlip");
2426
Brian Andersond6927fb2016-07-23 23:37:30 -07002427 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428
Mathias Agopian4fec8732012-06-29 14:12:52 -07002429 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002430 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002431 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002432
2433 // Store the set of layers that need updates. This set must not change as
2434 // buffers are being latched, as this could result in a deadlock.
2435 // Example: Two producers share the same command stream and:
2436 // 1.) Layer 0 is latched
2437 // 2.) Layer 0 gets a new frame
2438 // 2.) Layer 1 gets a new frame
2439 // 3.) Layer 1 is latched.
2440 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2441 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002442 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002443 if (layer->hasQueuedFrame()) {
2444 frameQueued = true;
2445 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002446 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002447 } else {
2448 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002449 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002450 } else {
2451 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002452 }
Robert Carr2047fae2016-11-28 14:09:09 -08002453 });
2454
Dan Stoza9e56aa02015-11-02 13:00:03 -08002455 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002456 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002457 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002458 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002459 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002460 newDataLatched = true;
2461 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002463
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002464 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002465
2466 // If we will need to wake up at some time in the future to deal with a
2467 // queued frame that shouldn't be displayed during this vsync period, wake
2468 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002469 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002470 signalLayerUpdate();
2471 }
2472
2473 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002474 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475}
2476
Mathias Agopianad456f92011-01-13 17:53:01 -08002477void SurfaceFlinger::invalidateHwcGeometry()
2478{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002479 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002480}
2481
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002482
Fabien Sanglard830b8472016-11-30 16:35:58 -08002483void SurfaceFlinger::doDisplayComposition(
2484 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002485 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002486{
Dan Stoza71433162014-02-04 16:22:36 -08002487 // We only need to actually compose the display if:
2488 // 1) It is being handled by hardware composer, which may need this to
2489 // keep its virtual display state machine in sync, or
2490 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002491 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002492 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002493 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002494 return;
2495 }
2496
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 ALOGV("doDisplayComposition");
2498
Mathias Agopian87baae12012-07-31 12:38:26 -07002499 Region dirtyRegion(inDirtyRegion);
2500
Mathias Agopianb8a55602009-06-26 19:06:36 -07002501 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002502 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503
Fabien Sanglard830b8472016-11-30 16:35:58 -08002504 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002505 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002506 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2507 // takes a rectangle, we must make sure to update that whole
2508 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002509 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002510 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002511 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002512 // We need to redraw the rectangle that will be updated
2513 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002514 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002515 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002516 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002517 } else {
2518 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002519 dirtyRegion.set(displayDevice->bounds());
2520 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002521 }
2522 }
2523
Fabien Sanglard830b8472016-11-30 16:35:58 -08002524 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002526 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002527 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002528
2529 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002530 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002531}
2532
Dan Stoza9e56aa02015-11-02 13:00:03 -08002533bool SurfaceFlinger::doComposeSurfaces(
2534 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002535{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002536 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002537
Dan Stoza9e56aa02015-11-02 13:00:03 -08002538 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002539
2540 mat4 oldColorMatrix;
2541 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2542 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2543 if (applyColorMatrix) {
2544 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2545 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2546 }
2547
Dan Stoza9e56aa02015-11-02 13:00:03 -08002548 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2549 if (hasClientComposition) {
2550 ALOGV("hasClientComposition");
2551
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002552#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002553 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002554 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002555#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002557 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002559 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002560
2561 // |mStateLock| not needed as we are on the main thread
2562 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002563 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2564 }
2565 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002566 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002567
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002568 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2570 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002571 // when using overlays, we assume a fully transparent framebuffer
2572 // NOTE: we could reduce how much we need to clear, for instance
2573 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002574 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002575 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002576 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002577 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002578 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002579 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002580
2581 // we remove the scissor part
2582 // we're left with the letterbox region
2583 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002585
2586 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002588
2589 // but limit it to the dirty region
2590 region.andSelf(dirty);
2591
Mathias Agopianb9494d52012-04-18 02:28:45 -07002592 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002593 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002594 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002595 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002596 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002597 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002598
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002600 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002601 // scissor on the main display. It should never be needed
2602 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002603 const Rect& bounds(displayDevice->getBounds());
2604 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002605 if (scissor != bounds) {
2606 // scissor doesn't match the screen's dimensions, so we
2607 // need to clear everything outside of it and enable
2608 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002609
Mathias Agopianf45c5102012-10-24 16:29:17 -07002610 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 const uint32_t height = displayDevice->getHeight();
2612 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002613 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002614 }
2615 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002616 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002617
Mathias Agopian85d751c2012-08-29 16:59:24 -07002618 /*
2619 * and then, render the layers targeted at the framebuffer
2620 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002621
Dan Stoza9e56aa02015-11-02 13:00:03 -08002622 ALOGV("Rendering client layers");
2623 const Transform& displayTransform = displayDevice->getTransform();
2624 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002625 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002626 bool firstLayer = true;
2627 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2628 const Region clip(dirty.intersect(
2629 displayTransform.transform(layer->visibleRegion)));
2630 ALOGV("Layer: %s", layer->getName().string());
2631 ALOGV(" Composition type: %s",
2632 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002633 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002634 switch (layer->getCompositionType(hwcId)) {
2635 case HWC2::Composition::Cursor:
2636 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002637 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002638 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002639 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2641 layer->isOpaque(state) && (state.alpha == 1.0f)
2642 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002643 // never clear the very first layer since we're
2644 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002645 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002646 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002647 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002648 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 case HWC2::Composition::Client: {
2650 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002651 break;
2652 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002653 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002654 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002655 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 } else {
2657 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002658 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002660 }
2661 } else {
2662 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002664 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002666 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002668 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002669 }
2670 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002671
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002672 if (applyColorMatrix) {
2673 getRenderEngine().setupColorTransform(oldColorMatrix);
2674 }
2675
Mathias Agopianf45c5102012-10-24 16:29:17 -07002676 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002677 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002678 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679}
2680
Fabien Sanglard830b8472016-11-30 16:35:58 -08002681void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2682 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002683 RenderEngine& engine(getRenderEngine());
2684 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685}
2686
Dan Stoza7d89d062015-04-30 13:29:25 -07002687status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002688 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002689 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 const sp<Layer>& lbc,
2691 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002692{
Dan Stoza7d89d062015-04-30 13:29:25 -07002693 // add this layer to the current state list
2694 {
2695 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002697 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2698 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002699 return NO_MEMORY;
2700 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 if (parent == nullptr) {
2702 mCurrentState.layersSortedByZ.add(lbc);
2703 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002704 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2705 ALOGE("addClientLayer called with a removed parent");
2706 return NAME_NOT_FOUND;
2707 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 parent->addChild(lbc);
2709 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002710
Dan Stoza7d89d062015-04-30 13:29:25 -07002711 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002712 mLayersAdded = true;
2713 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002714 }
2715
Mathias Agopian96f08192010-06-02 23:28:45 -07002716 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002717 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002718
Dan Stoza7d89d062015-04-30 13:29:25 -07002719 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002720}
2721
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002722status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002723 Mutex::Autolock _l(mStateLock);
2724
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002726 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002727 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002728 if (topLevelOnly) {
2729 return NO_ERROR;
2730 }
2731
Chia-I Wu98f1c102017-05-30 14:54:08 -07002732 sp<Layer> ancestor = p;
2733 while (ancestor->getParent() != nullptr) {
2734 ancestor = ancestor->getParent();
2735 }
2736 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2737 ALOGE("removeLayer called with a layer whose parent has been removed");
2738 return NAME_NOT_FOUND;
2739 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002740
2741 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002742 } else {
2743 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002744 }
2745
Robert Carr136e2f62017-02-08 17:54:29 -08002746 // As a matter of normal operation, the LayerCleaner will produce a second
2747 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2748 // so we will succeed in promoting it, but it's already been removed
2749 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2750 // otherwise something has gone wrong and we are leaking the layer.
2751 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2753 layer->getName().string(),
2754 (p != nullptr) ? p->getName().string() : "no-parent");
2755 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002756 } else if (index < 0) {
2757 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002758 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759
2760 mLayersPendingRemoval.add(layer);
2761 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002762 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002763 setTransactionFlags(eTransactionNeeded);
2764 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765}
2766
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002767uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002768 return android_atomic_release_load(&mTransactionFlags);
2769}
2770
Mathias Agopian3f844832013-08-07 21:24:32 -07002771uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2773}
2774
Mathias Agopian3f844832013-08-07 21:24:32 -07002775uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2777 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002778 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 }
2780 return old;
2781}
2782
Mathias Agopian8b33f032012-07-24 20:43:54 -07002783void SurfaceFlinger::setTransactionState(
2784 const Vector<ComposerState>& state,
2785 const Vector<DisplayState>& displays,
2786 uint32_t flags)
2787{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002788 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002789 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002790 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002791
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002792 if (flags & eAnimation) {
2793 // For window updates that are part of an animation we must wait for
2794 // previous animation "frames" to be handled.
2795 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002796 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002797 if (CC_UNLIKELY(err != NO_ERROR)) {
2798 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002799 // caller after a few seconds.
2800 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2801 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002802 mAnimTransactionPending = false;
2803 break;
2804 }
2805 }
2806 }
2807
Mathias Agopiane57f2922012-08-09 16:29:12 -07002808 size_t count = displays.size();
2809 for (size_t i=0 ; i<count ; i++) {
2810 const DisplayState& s(displays[i]);
2811 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002812 }
2813
Mathias Agopiane57f2922012-08-09 16:29:12 -07002814 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002815 for (size_t i=0 ; i<count ; i++) {
2816 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002817 // Here we need to check that the interface we're given is indeed
2818 // one of our own. A malicious client could give us a NULL
2819 // IInterface, or one of its own or even one of our own but a
2820 // different type. All these situations would cause us to crash.
2821 //
2822 // NOTE: it would be better to use RTTI as we could directly check
2823 // that we have a Client*. however, RTTI is disabled in Android.
2824 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002825 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002826 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002827 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002828 sp<Client> client( static_cast<Client *>(s.client.get()) );
2829 transactionFlags |= setClientStateLocked(client, s.state);
2830 }
2831 }
2832 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002833 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002834
Robert Carr2a7dbb42016-05-24 11:41:28 -07002835 // If a synchronous transaction is explicitly requested without any changes,
2836 // force a transaction anyway. This can be used as a flush mechanism for
2837 // previous async transactions.
2838 if (transactionFlags == 0 && (flags & eSynchronous)) {
2839 transactionFlags = eTransactionNeeded;
2840 }
2841
Mathias Agopian386aa982011-11-07 21:58:03 -08002842 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002843 if (mInterceptor.isEnabled()) {
2844 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2845 }
Irvel468051e2016-06-13 16:44:44 -07002846
Mathias Agopian386aa982011-11-07 21:58:03 -08002847 // this triggers the transaction
2848 setTransactionFlags(transactionFlags);
2849
2850 // if this is a synchronous transaction, wait for it to take effect
2851 // before returning.
2852 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002853 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002854 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002855 if (flags & eAnimation) {
2856 mAnimTransactionPending = true;
2857 }
2858 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002859 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2860 if (CC_UNLIKELY(err != NO_ERROR)) {
2861 // just in case something goes wrong in SF, return to the
2862 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002863 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2864 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002865 break;
2866 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002867 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 }
2869}
2870
Mathias Agopiane57f2922012-08-09 16:29:12 -07002871uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2872{
Jesse Hall9a143922012-10-04 16:29:19 -07002873 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2874 if (dpyIdx < 0)
2875 return 0;
2876
Mathias Agopiane57f2922012-08-09 16:29:12 -07002877 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002878 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002879 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002880 const uint32_t what = s.what;
2881 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002882 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002883 disp.surface = s.surface;
2884 flags |= eDisplayTransactionNeeded;
2885 }
2886 }
2887 if (what & DisplayState::eLayerStackChanged) {
2888 if (disp.layerStack != s.layerStack) {
2889 disp.layerStack = s.layerStack;
2890 flags |= eDisplayTransactionNeeded;
2891 }
2892 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002893 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002894 if (disp.orientation != s.orientation) {
2895 disp.orientation = s.orientation;
2896 flags |= eDisplayTransactionNeeded;
2897 }
2898 if (disp.frame != s.frame) {
2899 disp.frame = s.frame;
2900 flags |= eDisplayTransactionNeeded;
2901 }
2902 if (disp.viewport != s.viewport) {
2903 disp.viewport = s.viewport;
2904 flags |= eDisplayTransactionNeeded;
2905 }
2906 }
Michael Lentine47e45402014-07-18 15:34:25 -07002907 if (what & DisplayState::eDisplaySizeChanged) {
2908 if (disp.width != s.width) {
2909 disp.width = s.width;
2910 flags |= eDisplayTransactionNeeded;
2911 }
2912 if (disp.height != s.height) {
2913 disp.height = s.height;
2914 flags |= eDisplayTransactionNeeded;
2915 }
2916 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002917 }
2918 return flags;
2919}
2920
2921uint32_t SurfaceFlinger::setClientStateLocked(
2922 const sp<Client>& client,
2923 const layer_state_t& s)
2924{
2925 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002926 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002927 if (layer != 0) {
2928 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002929 bool geometryAppliesWithResize =
2930 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002931 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002932 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002934 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002935 }
2936 if (what & layer_state_t::eLayerChanged) {
2937 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002938 const auto& p = layer->getParent();
2939 if (p == nullptr) {
2940 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2941 if (layer->setLayer(s.z) && idx >= 0) {
2942 mCurrentState.layersSortedByZ.removeAt(idx);
2943 mCurrentState.layersSortedByZ.add(layer);
2944 // we need traversal (state changed)
2945 // AND transaction (list changed)
2946 flags |= eTransactionNeeded|eTraversalNeeded;
2947 }
2948 } else {
2949 if (p->setChildLayer(layer, s.z)) {
2950 flags |= eTransactionNeeded|eTraversalNeeded;
2951 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 }
2953 }
Robert Carrdb66e622017-04-10 16:55:57 -07002954 if (what & layer_state_t::eRelativeLayerChanged) {
chaviw64f7b422017-07-12 10:31:58 -07002955 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07002956 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
chaviw64f7b422017-07-12 10:31:58 -07002957 mCurrentState.layersSortedByZ.removeAt(idx);
2958 mCurrentState.layersSortedByZ.add(layer);
Robert Carrdb66e622017-04-10 16:55:57 -07002959 flags |= eTransactionNeeded|eTraversalNeeded;
2960 }
2961 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002962 if (what & layer_state_t::eSizeChanged) {
2963 if (layer->setSize(s.w, s.h)) {
2964 flags |= eTraversalNeeded;
2965 }
2966 }
2967 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 flags |= eTraversalNeeded;
2970 }
2971 if (what & layer_state_t::eMatrixChanged) {
2972 if (layer->setMatrix(s.matrix))
2973 flags |= eTraversalNeeded;
2974 }
2975 if (what & layer_state_t::eTransparentRegionChanged) {
2976 if (layer->setTransparentRegionHint(s.transparentRegion))
2977 flags |= eTraversalNeeded;
2978 }
Dan Stoza23116082015-06-18 14:58:39 -07002979 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 if (layer->setFlags(s.flags, s.mask))
2981 flags |= eTraversalNeeded;
2982 }
2983 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002984 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002985 flags |= eTraversalNeeded;
2986 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002987 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002988 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002989 flags |= eTraversalNeeded;
2990 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002992 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002993 // We only allow setting layer stacks for top level layers,
2994 // everything else inherits layer stack from its parent.
2995 if (layer->hasParent()) {
2996 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2997 layer->getName().string());
2998 } else if (idx < 0) {
2999 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3000 "that also does not appear in the top level layer list. Something"
3001 " has gone wrong.", layer->getName().string());
3002 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003003 mCurrentState.layersSortedByZ.removeAt(idx);
3004 mCurrentState.layersSortedByZ.add(layer);
3005 // we need traversal (state changed)
3006 // AND transaction (list changed)
3007 flags |= eTransactionNeeded|eTraversalNeeded;
3008 }
3009 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003010 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003011 if (s.barrierHandle != nullptr) {
3012 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3013 } else if (s.barrierGbp != nullptr) {
3014 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3015 if (authenticateSurfaceTextureLocked(gbp)) {
3016 const auto& otherLayer =
3017 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3018 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3019 } else {
3020 ALOGE("Attempt to defer transaction to to an"
3021 " unrecognized GraphicBufferProducer");
3022 }
3023 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003024 // We don't trigger a traversal here because if no other state is
3025 // changed, we don't want this to cause any more work
3026 }
Robert Carr1db73f62016-12-21 12:58:51 -08003027 if (what & layer_state_t::eReparentChildren) {
3028 if (layer->reparentChildren(s.reparentHandle)) {
3029 flags |= eTransactionNeeded|eTraversalNeeded;
3030 }
3031 }
Robert Carr9524cb32017-02-13 11:32:32 -08003032 if (what & layer_state_t::eDetachChildren) {
3033 layer->detachChildren();
3034 }
Robert Carrc3574f72016-03-24 12:19:32 -07003035 if (what & layer_state_t::eOverrideScalingModeChanged) {
3036 layer->setOverrideScalingMode(s.overrideScalingMode);
3037 // We don't trigger a traversal here because if no other state is
3038 // changed, we don't want this to cause any more work
3039 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003040 }
3041 return flags;
3042}
3043
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003044status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003045 const String8& name,
3046 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003047 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003048 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3049 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003051 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003052 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003053 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003054 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003055 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003056
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003057 status_t result = NO_ERROR;
3058
3059 sp<Layer> layer;
3060
Cody Northropbc755282017-03-31 12:00:08 -06003061 String8 uniqueName = getUniqueLayerName(name);
3062
Mathias Agopian3165cc22012-08-08 19:42:09 -07003063 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3064 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003065 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003066 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003069 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003070 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003071 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003072 handle, gbp, &layer);
3073 break;
3074 default:
3075 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 break;
3077 }
3078
Dan Stoza7d89d062015-04-30 13:29:25 -07003079 if (result != NO_ERROR) {
3080 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003082
Albert Chaulk479c60c2017-01-27 14:21:34 -05003083 layer->setInfo(windowType, ownerUid);
3084
Robert Carr1f0a16a2016-10-24 16:27:39 -07003085 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003086 if (result != NO_ERROR) {
3087 return result;
3088 }
Irvelffc9efc2016-07-27 15:16:37 -07003089 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003090
3091 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003092 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093}
3094
Cody Northropbc755282017-03-31 12:00:08 -06003095String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3096{
3097 bool matchFound = true;
3098 uint32_t dupeCounter = 0;
3099
3100 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3101 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3102
3103 // Loop over layers until we're sure there is no matching name
3104 while (matchFound) {
3105 matchFound = false;
3106 mDrawingState.traverseInZOrder([&](Layer* layer) {
3107 if (layer->getName() == uniqueName) {
3108 matchFound = true;
3109 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3110 }
3111 });
3112 }
3113
3114 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3115
3116 return uniqueName;
3117}
3118
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003119status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3120 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3121 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122{
3123 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003124 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125 case PIXEL_FORMAT_TRANSPARENT:
3126 case PIXEL_FORMAT_TRANSLUCENT:
3127 format = PIXEL_FORMAT_RGBA_8888;
3128 break;
3129 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003130 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 break;
3132 }
3133
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003134 *outLayer = new Layer(this, client, name, w, h, flags);
3135 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3136 if (err == NO_ERROR) {
3137 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003138 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003139 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003140
3141 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3142 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143}
3144
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003145status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3146 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3147 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003149 *outLayer = new LayerDim(this, client, name, w, h, flags);
3150 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003151 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003152 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003153}
3154
Mathias Agopianac9fa422013-02-11 16:40:36 -08003155status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156{
Robert Carr9524cb32017-02-13 11:32:32 -08003157 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003158 status_t err = NO_ERROR;
3159 sp<Layer> l(client->getLayerUser(handle));
3160 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003161 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003162 err = removeLayer(l);
3163 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3164 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003165 }
3166 return err;
3167}
3168
Mathias Agopian13127d82013-03-05 17:47:11 -08003169status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003170{
Mathias Agopian67106042013-03-14 19:18:13 -07003171 // called by ~LayerCleaner() when all references to the IBinder (handle)
3172 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003173 sp<Layer> l = layer.promote();
3174 if (l == nullptr) {
3175 // The layer has already been removed, carry on
3176 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003177 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003178 // If we have a parent, then we can continue to live as long as it does.
3179 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180}
3181
Mathias Agopianb60314a2012-04-10 22:09:54 -07003182// ---------------------------------------------------------------------------
3183
Andy McFadden13a082e2012-08-24 10:16:42 -07003184void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003185 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003186 Vector<ComposerState> state;
3187 Vector<DisplayState> displays;
3188 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003189 d.what = DisplayState::eDisplayProjectionChanged |
3190 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003191 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003192 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003193 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003194 d.frame.makeInvalid();
3195 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003196 d.width = 0;
3197 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003198 displays.add(d);
3199 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003200 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003201
Dan Stoza9e56aa02015-11-02 13:00:03 -08003202 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3203 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003204 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003205
Brian Andersond0010582017-03-07 13:20:31 -08003206 // Use phase of 0 since phase is not known.
3207 // Use latency of 0, which will snap to the ideal latency.
3208 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003209}
3210
3211void SurfaceFlinger::initializeDisplays() {
3212 class MessageScreenInitialized : public MessageBase {
3213 SurfaceFlinger* flinger;
3214 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003215 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003216 virtual bool handler() {
3217 flinger->onInitializeDisplays();
3218 return true;
3219 }
3220 };
3221 sp<MessageBase> msg = new MessageScreenInitialized(this);
3222 postMessageAsync(msg); // we may be called from main thread, use async message
3223}
3224
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003225void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3226 int mode) {
3227 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3228 this);
3229 int32_t type = hw->getDisplayType();
3230 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003231
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003232 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003233 return;
3234 }
3235
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003236 hw->setPowerMode(mode);
3237 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3238 ALOGW("Trying to set power mode for virtual display");
3239 return;
3240 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003241
Irvelffc9efc2016-07-27 15:16:37 -07003242 if (mInterceptor.isEnabled()) {
3243 Mutex::Autolock _l(mStateLock);
3244 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3245 if (idx < 0) {
3246 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3247 return;
3248 }
3249 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3250 }
3251
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003252 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003253 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003254 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003255 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3256 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003257 // FIXME: eventthread only knows about the main display right now
3258 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003259 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003260 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003262 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003263 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003264 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003265
3266 struct sched_param param = {0};
3267 param.sched_priority = 1;
3268 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3269 ALOGW("Couldn't set SCHED_FIFO on display on");
3270 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003271 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003272 // Turn off the display
3273 struct sched_param param = {0};
3274 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3275 ALOGW("Couldn't set SCHED_OTHER on display off");
3276 }
3277
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003278 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003279 disableHardwareVsync(true); // also cancels any in-progress resync
3280
Mathias Agopiancde87a32012-09-13 14:09:01 -07003281 // FIXME: eventthread only knows about the main display right now
3282 mEventThread->onScreenReleased();
3283 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003284
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003285 getHwComposer().setPowerMode(type, mode);
3286 mVisibleRegionsDirty = true;
3287 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003288 } else if (mode == HWC_POWER_MODE_DOZE ||
3289 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003290 // Update display while dozing
3291 getHwComposer().setPowerMode(type, mode);
3292 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3293 // FIXME: eventthread only knows about the main display right now
3294 mEventThread->onScreenAcquired();
3295 resyncToHardwareVsync(true);
3296 }
3297 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3298 // Leave display going to doze
3299 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3300 disableHardwareVsync(true); // also cancels any in-progress resync
3301 // FIXME: eventthread only knows about the main display right now
3302 mEventThread->onScreenReleased();
3303 }
3304 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003305 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003306 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003307 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003308 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003309}
3310
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003311void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3312 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003313 SurfaceFlinger& mFlinger;
3314 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003315 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003316 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003317 MessageSetPowerMode(SurfaceFlinger& flinger,
3318 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3319 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003320 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003321 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003322 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003323 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003324 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003325 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003326 ALOGW("Attempt to set power mode = %d for virtual display",
3327 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003328 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003329 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003330 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003331 return true;
3332 }
3333 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003334 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003335 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003336}
3337
3338// ---------------------------------------------------------------------------
3339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003340status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3341{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003342 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003343
Mathias Agopianbd115332013-04-18 16:41:04 -07003344 IPCThreadState* ipc = IPCThreadState::self();
3345 const int pid = ipc->getCallingPid();
3346 const int uid = ipc->getCallingUid();
3347 if ((uid != AID_SHELL) &&
3348 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003349 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003350 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003352 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003353 // (this would indicate SF is stuck, but we want to be able to
3354 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003355 status_t err = mStateLock.timedLock(s2ns(1));
3356 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003357 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003358 result.appendFormat(
3359 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3360 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003361 }
3362
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003363 bool dumpAll = true;
3364 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003365 size_t numArgs = args.size();
3366 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003367 if ((index < numArgs) &&
3368 (args[index] == String16("--list"))) {
3369 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003370 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003371 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003372 }
3373
3374 if ((index < numArgs) &&
3375 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003376 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003377 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003378 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003379 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003380
3381 if ((index < numArgs) &&
3382 (args[index] == String16("--latency-clear"))) {
3383 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003384 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003385 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003386 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003387
3388 if ((index < numArgs) &&
3389 (args[index] == String16("--dispsync"))) {
3390 index++;
3391 mPrimaryDispSync.dump(result);
3392 dumpAll = false;
3393 }
Dan Stozab90cf072015-03-05 11:05:59 -08003394
3395 if ((index < numArgs) &&
3396 (args[index] == String16("--static-screen"))) {
3397 index++;
3398 dumpStaticScreenStats(result);
3399 dumpAll = false;
3400 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003401
3402 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003403 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003404 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003405 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003406 dumpAll = false;
3407 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003408
3409 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3410 index++;
3411 dumpWideColorInfo(result);
3412 dumpAll = false;
3413 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003414 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003415
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003416 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003417 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003418 }
3419
Mathias Agopian9795c422009-08-26 16:36:26 -07003420 if (locked) {
3421 mStateLock.unlock();
3422 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423 }
3424 write(fd, result.string(), result.size());
3425 return NO_ERROR;
3426}
3427
Dan Stozac7014012014-02-14 15:03:43 -08003428void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3429 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003430{
Robert Carr2047fae2016-11-28 14:09:09 -08003431 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003433 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003434}
3435
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003436void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003437 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438{
3439 String8 name;
3440 if (index < args.size()) {
3441 name = String8(args[index]);
3442 index++;
3443 }
3444
Dan Stoza9e56aa02015-11-02 13:00:03 -08003445 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3446 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003447 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003448
3449 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003450 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003451 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003452 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003453 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003454 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003455 }
Robert Carr2047fae2016-11-28 14:09:09 -08003456 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003457 }
3458}
3459
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003460void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003461 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003462{
3463 String8 name;
3464 if (index < args.size()) {
3465 name = String8(args[index]);
3466 index++;
3467 }
3468
Robert Carr2047fae2016-11-28 14:09:09 -08003469 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003470 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003471 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003472 }
Robert Carr2047fae2016-11-28 14:09:09 -08003473 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003474
Svetoslavd85084b2014-03-20 10:28:31 -07003475 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003476}
3477
Jamie Gennis6547ff42013-07-16 20:12:42 -07003478// This should only be called from the main thread. Otherwise it would need
3479// the lock and should use mCurrentState rather than mDrawingState.
3480void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003481 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003482 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003483 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003484
3485 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3486}
3487
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003488void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003489{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003490 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003491 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3492
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003493 if (isLayerTripleBufferingDisabled())
3494 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003495
3496 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003497 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003498 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003499 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003500 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3501 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003502 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003503}
3504
Dan Stozab90cf072015-03-05 11:05:59 -08003505void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3506{
3507 result.appendFormat("Static screen stats:\n");
3508 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3509 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3510 float percent = 100.0f *
3511 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3512 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3513 b + 1, bucketTimeSec, percent);
3514 }
3515 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3516 float percent = 100.0f *
3517 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3518 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3519 NUM_BUCKETS - 1, bucketTimeSec, percent);
3520}
3521
Dan Stozae77c7662016-05-13 11:37:28 -07003522void SurfaceFlinger::recordBufferingStats(const char* layerName,
3523 std::vector<OccupancyTracker::Segment>&& history) {
3524 Mutex::Autolock lock(mBufferingStatsMutex);
3525 auto& stats = mBufferingStats[layerName];
3526 for (const auto& segment : history) {
3527 if (!segment.usedThirdBuffer) {
3528 stats.twoBufferTime += segment.totalTime;
3529 }
3530 if (segment.occupancyAverage < 1.0f) {
3531 stats.doubleBufferedTime += segment.totalTime;
3532 } else if (segment.occupancyAverage < 2.0f) {
3533 stats.tripleBufferedTime += segment.totalTime;
3534 }
3535 ++stats.numSegments;
3536 stats.totalTime += segment.totalTime;
3537 }
3538}
3539
Brian Andersond6927fb2016-07-23 23:37:30 -07003540void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3541 result.appendFormat("Layer frame timestamps:\n");
3542
3543 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3544 const size_t count = currentLayers.size();
3545 for (size_t i=0 ; i<count ; i++) {
3546 currentLayers[i]->dumpFrameEvents(result);
3547 }
3548}
3549
Dan Stozae77c7662016-05-13 11:37:28 -07003550void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3551 result.append("Buffering stats:\n");
3552 result.append(" [Layer name] <Active time> <Two buffer> "
3553 "<Double buffered> <Triple buffered>\n");
3554 Mutex::Autolock lock(mBufferingStatsMutex);
3555 typedef std::tuple<std::string, float, float, float> BufferTuple;
3556 std::map<float, BufferTuple, std::greater<float>> sorted;
3557 for (const auto& statsPair : mBufferingStats) {
3558 const char* name = statsPair.first.c_str();
3559 const BufferingStats& stats = statsPair.second;
3560 if (stats.numSegments == 0) {
3561 continue;
3562 }
3563 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3564 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3565 stats.totalTime;
3566 float doubleBufferRatio = static_cast<float>(
3567 stats.doubleBufferedTime) / stats.totalTime;
3568 float tripleBufferRatio = static_cast<float>(
3569 stats.tripleBufferedTime) / stats.totalTime;
3570 sorted.insert({activeTime, {name, twoBufferRatio,
3571 doubleBufferRatio, tripleBufferRatio}});
3572 }
3573 for (const auto& sortedPair : sorted) {
3574 float activeTime = sortedPair.first;
3575 const BufferTuple& values = sortedPair.second;
3576 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3577 std::get<0>(values).c_str(), activeTime,
3578 std::get<1>(values), std::get<2>(values),
3579 std::get<3>(values));
3580 }
3581 result.append("\n");
3582}
3583
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003584void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3585 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3586
3587 // TODO: print out if wide-color mode is active or not
3588
3589 for (size_t d = 0; d < mDisplays.size(); d++) {
3590 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3591 int32_t hwcId = displayDevice->getHwcDisplayId();
3592 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3593 continue;
3594 }
3595
3596 result.appendFormat("Display %d color modes:\n", hwcId);
3597 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3598 for (auto&& mode : modes) {
3599 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3600 }
3601
3602 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3603 result.appendFormat(" Current color mode: %s (%d)\n",
3604 decodeColorMode(currentMode).c_str(), currentMode);
3605 }
3606 result.append("\n");
3607}
3608
Mathias Agopian74d211a2013-04-22 16:55:35 +02003609void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3610 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003611{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003612 bool colorize = false;
3613 if (index < args.size()
3614 && (args[index] == String16("--color"))) {
3615 colorize = true;
3616 index++;
3617 }
3618
3619 Colorizer colorizer(colorize);
3620
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003621 // figure out if we're stuck somewhere
3622 const nsecs_t now = systemTime();
3623 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3624 const nsecs_t inTransaction(mDebugInTransaction);
3625 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3626 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3627
3628 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003629 * Dump library configuration.
3630 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003631
3632 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003633 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003634 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003635 appendSfConfigString(result);
3636 appendUiConfigString(result);
3637 appendGuiConfigString(result);
3638 result.append("\n");
3639
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003640 result.append("\nWide-Color information:\n");
3641 dumpWideColorInfo(result);
3642
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003643 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003644 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003645 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003646 result.append(SyncFeatures::getInstance().toString());
3647 result.append("\n");
3648
Dan Stoza9e56aa02015-11-02 13:00:03 -08003649 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3650
Andy McFadden41d67d72014-04-25 16:58:34 -07003651 colorizer.bold(result);
3652 result.append("DispSync configuration: ");
3653 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003654 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003655 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003656 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003657 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003658 result.append("\n");
3659
Dan Stozab90cf072015-03-05 11:05:59 -08003660 // Dump static screen stats
3661 result.append("\n");
3662 dumpStaticScreenStats(result);
3663 result.append("\n");
3664
Dan Stozae77c7662016-05-13 11:37:28 -07003665 dumpBufferingStats(result);
3666
Andy McFadden4803b742012-09-24 19:07:20 -07003667 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003668 * Dump the visible layer list
3669 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003670 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003671 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003672 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003673 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003674 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003675 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003676
3677 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003678 * Dump Display state
3679 */
3680
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003681 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003682 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003683 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003684 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3685 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003686 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003687 }
3688
3689 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003690 * Dump SurfaceFlinger global state
3691 */
3692
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003693 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003694 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003695 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003696
Mathias Agopian888c8222012-08-04 21:10:38 -07003697 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003698 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003699
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003700 colorizer.bold(result);
3701 result.appendFormat("EGL implementation : %s\n",
3702 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3703 colorizer.reset(result);
3704 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003705 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003706
Mathias Agopian875d8e12013-06-07 15:35:48 -07003707 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003708
Mathias Agopian42977342012-08-05 00:40:46 -07003709 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003710 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3711 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003712 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003713 " last eglSwapBuffers() time: %f us\n"
3714 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003715 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716 " refresh-rate : %f fps\n"
3717 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003718 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003719 " gpu_to_cpu_unsupported : %d\n"
3720 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003721 mLastSwapBufferTime/1000.0,
3722 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003723 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003724 1e9 / activeConfig->getVsyncPeriod(),
3725 activeConfig->getDpiX(),
3726 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003727 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003728
Mathias Agopian74d211a2013-04-22 16:55:35 +02003729 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003730 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731
Mathias Agopian74d211a2013-04-22 16:55:35 +02003732 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003733 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003734
3735 /*
3736 * VSYNC state
3737 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003738 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003739 result.append("\n");
3740
3741 /*
3742 * HWC layer minidump
3743 */
3744 for (size_t d = 0; d < mDisplays.size(); d++) {
3745 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3746 int32_t hwcId = displayDevice->getHwcDisplayId();
3747 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3748 continue;
3749 }
3750
3751 result.appendFormat("Display %d HWC layers:\n", hwcId);
3752 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003753 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003754 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003755 });
Dan Stozae22aec72016-08-01 13:20:59 -07003756 result.append("\n");
3757 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758
3759 /*
3760 * Dump HWComposer state
3761 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003762 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003764 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003765 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003766 result.appendFormat(" h/w composer %s\n",
3767 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003768 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003769
3770 /*
3771 * Dump gralloc state
3772 */
3773 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3774 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003775
3776 /*
3777 * Dump VrFlinger state if in use.
3778 */
3779 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3780 result.append("VrFlinger state:\n");
3781 result.append(mVrFlinger->Dump().c_str());
3782 result.append("\n");
3783 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784}
3785
Mathias Agopian13127d82013-03-05 17:47:11 -08003786const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003787SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003788 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003789 wp<IBinder> dpy;
3790 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3791 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3792 dpy = mDisplays.keyAt(i);
3793 break;
3794 }
3795 }
3796 if (dpy == NULL) {
3797 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3798 // Just use the primary display so we have something to return
3799 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3800 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003801 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003802}
3803
Keun young Park63f165f2012-08-31 10:53:36 -07003804bool SurfaceFlinger::startDdmConnection()
3805{
3806 void* libddmconnection_dso =
3807 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3808 if (!libddmconnection_dso) {
3809 return false;
3810 }
3811 void (*DdmConnection_start)(const char* name);
3812 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003813 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003814 if (!DdmConnection_start) {
3815 dlclose(libddmconnection_dso);
3816 return false;
3817 }
3818 (*DdmConnection_start)(getServiceName());
3819 return true;
3820}
3821
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003822status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 switch (code) {
3824 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003825 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003827 case CLEAR_ANIMATION_FRAME_STATS:
3828 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003829 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003830 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003831 {
3832 // codes that require permission check
3833 IPCThreadState* ipc = IPCThreadState::self();
3834 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003835 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003836 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003837 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003838 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003839 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003840 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003841 break;
3842 }
Robert Carr1db73f62016-12-21 12:58:51 -08003843 /*
3844 * Calling setTransactionState is safe, because you need to have been
3845 * granted a reference to Client* and Handle* to do anything with it.
3846 *
3847 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3848 */
3849 case SET_TRANSACTION_STATE:
3850 case CREATE_SCOPED_CONNECTION:
3851 {
3852 return OK;
3853 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003854 case CAPTURE_SCREEN:
3855 {
3856 // codes that require permission check
3857 IPCThreadState* ipc = IPCThreadState::self();
3858 const int pid = ipc->getCallingPid();
3859 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003860 if ((uid != AID_GRAPHICS) &&
3861 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003862 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003863 return PERMISSION_DENIED;
3864 }
3865 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 }
3867 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003868 return OK;
3869}
3870
3871status_t SurfaceFlinger::onTransact(
3872 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3873{
3874 status_t credentialCheck = CheckTransactCodeCredentials(code);
3875 if (credentialCheck != OK) {
3876 return credentialCheck;
3877 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003878
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3880 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003881 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003882 IPCThreadState* ipc = IPCThreadState::self();
3883 const int uid = ipc->getCallingUid();
3884 if (CC_UNLIKELY(uid != AID_SYSTEM
3885 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003886 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003887 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003888 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 return PERMISSION_DENIED;
3890 }
3891 int n;
3892 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003893 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003894 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003895 return NO_ERROR;
3896 case 1002: // SHOW_UPDATES
3897 n = data.readInt32();
3898 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003899 invalidateHwcGeometry();
3900 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003902 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003903 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003904 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003906 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003907 setTransactionFlags(
3908 eTransactionNeeded|
3909 eDisplayTransactionNeeded|
3910 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003911 return NO_ERROR;
3912 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003913 case 1006:{ // send empty update
3914 signalRefresh();
3915 return NO_ERROR;
3916 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003917 case 1008: // toggle use of hw composer
3918 n = data.readInt32();
3919 mDebugDisableHWC = n ? 1 : 0;
3920 invalidateHwcGeometry();
3921 repaintEverything();
3922 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003923 case 1009: // toggle use of transform hint
3924 n = data.readInt32();
3925 mDebugDisableTransformHint = n ? 1 : 0;
3926 invalidateHwcGeometry();
3927 repaintEverything();
3928 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003930 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 reply->writeInt32(0);
3932 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003933 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003934 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003935 return NO_ERROR;
3936 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003937 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003938 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003939 return NO_ERROR;
3940 }
3941 case 1014: {
3942 // daltonize
3943 n = data.readInt32();
3944 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003945 case 1:
3946 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3947 break;
3948 case 2:
3949 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3950 break;
3951 case 3:
3952 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3953 break;
3954 default:
3955 mDaltonizer.setType(ColorBlindnessType::None);
3956 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003957 }
3958 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003959 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003960 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003961 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003962 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003963 invalidateHwcGeometry();
3964 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003965 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003967 case 1015: {
3968 // apply a color matrix
3969 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003970 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003971 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003972 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003973 for (size_t j = 0; j < 4; j++) {
3974 mColorMatrix[i][j] = data.readFloat();
3975 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003976 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003977 } else {
3978 mColorMatrix = mat4();
3979 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003980
3981 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3982 // the division by w in the fragment shader
3983 float4 lastRow(transpose(mColorMatrix)[3]);
3984 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3985 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3986 }
3987
Alan Viverette9c5a3332013-09-12 20:04:35 -07003988 invalidateHwcGeometry();
3989 repaintEverything();
3990 return NO_ERROR;
3991 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003992 // This is an experimental interface
3993 // Needs to be shifted to proper binder interface when we productize
3994 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003995 n = data.readInt32();
3996 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003997 return NO_ERROR;
3998 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003999 case 1017: {
4000 n = data.readInt32();
4001 mForceFullDamage = static_cast<bool>(n);
4002 return NO_ERROR;
4003 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004004 case 1018: { // Modify Choreographer's phase offset
4005 n = data.readInt32();
4006 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4007 return NO_ERROR;
4008 }
4009 case 1019: { // Modify SurfaceFlinger's phase offset
4010 n = data.readInt32();
4011 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4012 return NO_ERROR;
4013 }
Irvel468051e2016-06-13 16:44:44 -07004014 case 1020: { // Layer updates interceptor
4015 n = data.readInt32();
4016 if (n) {
4017 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004018 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004019 }
4020 else{
4021 ALOGV("Interceptor disabled");
4022 mInterceptor.disable();
4023 }
4024 return NO_ERROR;
4025 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004026 case 1021: { // Disable HWC virtual displays
4027 n = data.readInt32();
4028 mUseHwcVirtualDisplays = !n;
4029 return NO_ERROR;
4030 }
Romain Guy0147a172017-06-01 13:53:56 -07004031 case 1022: { // Set saturation boost
4032 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4033
4034 invalidateHwcGeometry();
4035 repaintEverything();
4036 return NO_ERROR;
4037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038 }
4039 }
4040 return err;
4041}
4042
Mathias Agopian53331da2011-08-22 21:44:41 -07004043void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004044 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004045 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004046}
4047
Mathias Agopian59119e62010-10-11 12:37:43 -07004048// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004049// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004050// ---------------------------------------------------------------------------
4051
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004052/* The code below is here to handle b/8734824
4053 *
4054 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07004055 * from the surfaceflinger thread to the calling binder thread, where they
4056 * are executed. This allows the calling thread in the calling process to be
4057 * reused and not depend on having "enough" binder threads to handle the
4058 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004059 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004060class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07004061 /* Parts of GraphicProducerWrapper are run on two different threads,
4062 * communicating by sending messages via Looper but also by shared member
4063 * data. Coherence maintenance is subtle and in places implicit (ugh).
4064 *
4065 * Don't rely on Looper's sendMessage/handleMessage providing
4066 * release/acquire semantics for any data not actually in the Message.
4067 * Data going from surfaceflinger to binder threads needs to be
4068 * synchronized explicitly.
4069 *
4070 * Barrier open/wait do provide release/acquire semantics. This provides
4071 * implicit synchronization for data coming back from binder to
4072 * surfaceflinger threads.
4073 */
4074
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004075 sp<IGraphicBufferProducer> impl;
4076 sp<Looper> looper;
4077 status_t result;
4078 bool exitPending;
4079 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07004080 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004081 uint32_t code;
4082 Parcel const* data;
4083 Parcel* reply;
4084
4085 enum {
4086 MSG_API_CALL,
4087 MSG_EXIT
4088 };
4089
4090 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004091 * Called on surfaceflinger thread. This is called by our "fake"
4092 * BpGraphicBufferProducer. We package the data and reply Parcel and
4093 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004094 */
4095 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08004096 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004097 this->code = code;
4098 this->data = &data;
4099 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004100 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07004101 // if we've exited, we run the message synchronously right here.
4102 // note (JH): as far as I can tell from looking at the code, this
4103 // never actually happens. if it does, i'm not sure if it happens
4104 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004105 handleMessage(Message(MSG_API_CALL));
4106 } else {
4107 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004108 // Prevent stores to this->{code, data, reply} from being
4109 // reordered later than the construction of Message.
4110 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004111 looper->sendMessage(this, Message(MSG_API_CALL));
4112 barrier.wait();
4113 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004114 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004115 }
4116
4117 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004118 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004119 * call the real BpGraphicBufferProducer.
4120 */
4121 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004122 int what = message.what;
4123 // Prevent reads below from happening before the read from Message
4124 atomic_thread_fence(memory_order_acquire);
4125 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004126 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004127 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004128 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004129 exitRequested = true;
4130 }
4131 }
4132
4133public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004134 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004135 : impl(impl),
4136 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004137 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004138 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004139 exitRequested(false),
4140 code(0),
4141 data(NULL),
4142 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004143 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004144
Jesse Hallb154c422014-07-13 12:47:02 -07004145 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004146 status_t waitForResponse() {
4147 do {
4148 looper->pollOnce(-1);
4149 } while (!exitRequested);
4150 return result;
4151 }
4152
Jesse Hallb154c422014-07-13 12:47:02 -07004153 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004154 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004155 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004156 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004157 // Ensure this->result is visible to the binder thread before it
4158 // handles the message.
4159 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004160 looper->sendMessage(this, Message(MSG_EXIT));
4161 }
4162};
4163
4164
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004165status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4166 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004167 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004168 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004169 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004170
4171 if (CC_UNLIKELY(display == 0))
4172 return BAD_VALUE;
4173
4174 if (CC_UNLIKELY(producer == 0))
4175 return BAD_VALUE;
4176
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004177 // if we have secure windows on this display, never allow the screen capture
4178 // unless the producer interface is local (i.e.: we can take a screenshot for
4179 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004180 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004181
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004182 // Convert to surfaceflinger's internal rotation type.
4183 Transform::orientation_flags rotationFlags;
4184 switch (rotation) {
4185 case ISurfaceComposer::eRotateNone:
4186 rotationFlags = Transform::ROT_0;
4187 break;
4188 case ISurfaceComposer::eRotate90:
4189 rotationFlags = Transform::ROT_90;
4190 break;
4191 case ISurfaceComposer::eRotate180:
4192 rotationFlags = Transform::ROT_180;
4193 break;
4194 case ISurfaceComposer::eRotate270:
4195 rotationFlags = Transform::ROT_270;
4196 break;
4197 default:
4198 rotationFlags = Transform::ROT_0;
4199 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4200 break;
4201 }
4202
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004203 class MessageCaptureScreen : public MessageBase {
4204 SurfaceFlinger* flinger;
4205 sp<IBinder> display;
4206 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004207 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004208 uint32_t reqWidth, reqHeight;
4209 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004210 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004211 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004212 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004213 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004214 public:
4215 MessageCaptureScreen(SurfaceFlinger* flinger,
4216 const sp<IBinder>& display,
4217 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004218 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004219 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004220 bool useIdentityTransform,
4221 Transform::orientation_flags rotation,
4222 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004223 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004224 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004225 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004226 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004227 rotation(rotation), result(PERMISSION_DENIED),
4228 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004229 {
4230 }
4231 status_t getResult() const {
4232 return result;
4233 }
4234 virtual bool handler() {
4235 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004236 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004237 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004238 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004239 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004240 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004241 return true;
4242 }
4243 };
4244
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004245 // this creates a "fake" BBinder which will serve as a "fake" remote
4246 // binder to receive the marshaled calls and forward them to the
4247 // real remote (a BpGraphicBufferProducer)
4248 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4249
4250 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4251 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004252 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004253 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004254 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004255 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004256
4257 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004258 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004259 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004260 }
4261 return res;
4262}
4263
Mathias Agopian180f10d2013-04-10 22:55:41 -07004264
4265void SurfaceFlinger::renderScreenImplLocked(
4266 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004267 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004268 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004269 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004270{
4271 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004272 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004273
4274 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004275 const int32_t hw_w = hw->getWidth();
4276 const int32_t hw_h = hw->getHeight();
4277 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004278 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004279
Dan Stozac1879002014-05-22 15:59:05 -07004280 // if a default or invalid sourceCrop is passed in, set reasonable values
4281 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4282 !sourceCrop.isValid()) {
4283 sourceCrop.setLeftTop(Point(0, 0));
4284 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4285 }
4286
4287 // ensure that sourceCrop is inside screen
4288 if (sourceCrop.left < 0) {
4289 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4290 }
Dan Stozabe31f442014-06-11 11:20:54 -07004291 if (sourceCrop.right > hw_w) {
4292 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004293 }
4294 if (sourceCrop.top < 0) {
4295 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4296 }
Dan Stozabe31f442014-06-11 11:20:54 -07004297 if (sourceCrop.bottom > hw_h) {
4298 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004299 }
4300
Romain Guy88d37dd2017-05-26 17:57:05 -07004301#ifdef USE_HWC2
4302 engine.setWideColor(hw->getWideColorSupport());
4303 engine.setColorMode(hw->getActiveColorMode());
4304#endif
4305
Mathias Agopian180f10d2013-04-10 22:55:41 -07004306 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004307 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004308
4309 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004310 engine.setViewportAndProjection(
4311 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004312 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004313
4314 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004315 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004316
Robert Carr1f0a16a2016-10-24 16:27:39 -07004317 // We loop through the first level of layers without traversing,
4318 // as we need to interpret min/max layer Z in the top level Z space.
4319 for (const auto& layer : mDrawingState.layersSortedByZ) {
4320 if (layer->getLayerStack() != hw->getLayerStack()) {
4321 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004322 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004323 const Layer::State& state(layer->getDrawingState());
4324 if (state.z < minLayerZ || state.z > maxLayerZ) {
4325 continue;
4326 }
Dan Stoza412903f2017-04-27 13:42:17 -07004327 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004328 if (!layer->isVisible()) {
4329 return;
4330 }
4331 if (filtering) layer->setFiltering(true);
4332 layer->draw(hw, useIdentityTransform);
4333 if (filtering) layer->setFiltering(false);
4334 });
4335 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004336
Mathias Agopian931bda12013-08-28 18:11:46 -07004337 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004338}
4339
4340
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004341status_t SurfaceFlinger::captureScreenImplLocked(
4342 const sp<const DisplayDevice>& hw,
4343 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004344 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004345 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004346 bool useIdentityTransform, Transform::orientation_flags rotation,
4347 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004348{
4349 ATRACE_CALL();
4350
Mathias Agopian180f10d2013-04-10 22:55:41 -07004351 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004352 uint32_t hw_w = hw->getWidth();
4353 uint32_t hw_h = hw->getHeight();
4354
4355 if (rotation & Transform::ROT_90) {
4356 std::swap(hw_w, hw_h);
4357 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004358
Mathias Agopian180f10d2013-04-10 22:55:41 -07004359 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4360 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4361 reqWidth, reqHeight, hw_w, hw_h);
4362 return BAD_VALUE;
4363 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004364
Mathias Agopian180f10d2013-04-10 22:55:41 -07004365 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4366 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4367
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004368 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004369 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004370 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004371 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4372 (state.z < minLayerZ || state.z > maxLayerZ)) {
4373 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004374 }
Dan Stoza412903f2017-04-27 13:42:17 -07004375 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004376 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4377 layer->isSecure());
4378 });
4379 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004380
4381 if (!isLocalScreenshot && secureLayerIsVisible) {
4382 ALOGW("FB is protected: PERMISSION_DENIED");
4383 return PERMISSION_DENIED;
4384 }
4385
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004386 // create a surface (because we're a producer, and we need to
4387 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004388 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004389
4390 // Put the screenshot Surface into async mode so that
4391 // Layer::headFenceHasSignaled will always return true and we'll latch the
4392 // first buffer regardless of whether or not its acquire fence has
4393 // signaled. This is needed to avoid a race condition in the rotation
4394 // animation. See b/30209608
4395 sur->setAsyncMode(true);
4396
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004397 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004398
Michael Lentine5a16a622015-05-21 13:48:24 -07004399 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4400 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004401 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4402 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004403
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004404 int err = 0;
4405 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004406 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004407 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4408 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004409
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004410 if (err == NO_ERROR) {
4411 ANativeWindowBuffer* buffer;
4412 /* TODO: Once we have the sync framework everywhere this can use
4413 * server-side waits on the fence that dequeueBuffer returns.
4414 */
4415 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4416 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004417 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004418 // create an EGLImage from the buffer so we can later
4419 // turn it into a texture
4420 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4421 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4422 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004423 // this binds the given EGLImage as a framebuffer for the
4424 // duration of this scope.
4425 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4426 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004427 // this will in fact render into our dequeued buffer
4428 // via an FBO, which means we didn't have to create
4429 // an EGLSurface and therefore we're not
4430 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004431 renderScreenImplLocked(
4432 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4433 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004434
Romain Guy8ec6ff22017-05-31 19:22:30 -07004435#ifdef USE_HWC2
4436 if (hasWideColorDisplay) {
4437 native_window_set_buffers_data_space(window,
4438 getRenderEngine().usesWideColor() ?
4439 HAL_DATASPACE_DISPLAY_P3 : HAL_DATASPACE_V0_SRGB);
4440 }
4441#endif
4442
Riley Andrews86639902014-08-15 12:27:24 -07004443 // Attempt to create a sync khr object that can produce a sync point. If that
4444 // isn't available, create a non-dupable sync object in the fallback path and
4445 // wait on it directly.
4446 EGLSyncKHR sync;
4447 if (!DEBUG_SCREENSHOTS) {
4448 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004449 // native fence fd will not be populated until flush() is done.
4450 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004451 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004452 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004453 }
Riley Andrews86639902014-08-15 12:27:24 -07004454 if (sync != EGL_NO_SYNC_KHR) {
4455 // get the sync fd
4456 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4457 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4458 ALOGW("captureScreen: failed to dup sync khr object");
4459 syncFd = -1;
4460 }
4461 eglDestroySyncKHR(mEGLDisplay, sync);
4462 } else {
4463 // fallback path
4464 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4465 if (sync != EGL_NO_SYNC_KHR) {
4466 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4467 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4468 EGLint eglErr = eglGetError();
4469 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4470 ALOGW("captureScreen: fence wait timed out");
4471 } else {
4472 ALOGW_IF(eglErr != EGL_SUCCESS,
4473 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4474 }
4475 eglDestroySyncKHR(mEGLDisplay, sync);
4476 } else {
4477 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4478 }
4479 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004480 if (DEBUG_SCREENSHOTS) {
4481 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4482 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4483 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4484 hw, minLayerZ, maxLayerZ);
4485 delete [] pixels;
4486 }
4487
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004488 } else {
4489 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4490 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004491 window->cancelBuffer(window, buffer, syncFd);
4492 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004493 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004494 // destroy our image
4495 eglDestroyImageKHR(mEGLDisplay, image);
4496 } else {
4497 result = BAD_VALUE;
4498 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004499 if (buffer) {
4500 // queueBuffer takes ownership of syncFd
4501 result = window->queueBuffer(window, buffer, syncFd);
4502 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004503 }
4504 } else {
4505 result = BAD_VALUE;
4506 }
4507 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4508 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004509
Mathias Agopian74c40c02010-09-29 13:02:36 -07004510 return result;
4511}
4512
Mathias Agopiand5556842013-09-19 17:08:37 -07004513void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004514 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004515 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004516 for (size_t y=0 ; y<h ; y++) {
4517 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4518 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004519 if (p[x] != 0xFF000000) return;
4520 }
4521 }
4522 ALOGE("*** we just took a black screenshot ***\n"
4523 "requested minz=%d, maxz=%d, layerStack=%d",
4524 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004525
Robert Carr2047fae2016-11-28 14:09:09 -08004526 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004527 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004528 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004529 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4530 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004531 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004532 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4533 layer->isVisible() ? '+' : '-',
4534 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004535 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004536 i++;
4537 });
4538 }
4539 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004540 }
4541}
4542
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004543// ---------------------------------------------------------------------------
4544
Dan Stoza412903f2017-04-27 13:42:17 -07004545void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4546 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004547}
4548
Dan Stoza412903f2017-04-27 13:42:17 -07004549void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4550 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004551}
4552
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004554
4555
4556#if defined(__gl_h_)
4557#error "don't include gl/gl.h in this file"
4558#endif
4559
4560#if defined(__gl2_h_)
4561#error "don't include gl2/gl2.h in this file"
4562#endif