blob: 8a9b2ed094575c6e7d9e452a88ade97c3aab4244 [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
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001256// Note: it is assumed the caller holds |mStateLock| when this is called
1257void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001258 disableHardwareVsync(true);
1259 clearHwcLayers(mDrawingState.layersSortedByZ);
1260 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001261 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1262 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1263 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001264 // Clear the drawing state so that the logic inside of
1265 // handleTransactionLocked will fire. It will determine the delta between
1266 // mCurrentState and mDrawingState and re-apply all changes when we make the
1267 // transition.
1268 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001269 // Release virtual display hwcId during vr mode transition.
1270 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1271 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1272 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1273 displayDevice->disconnect(getHwComposer());
1274 }
1275 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001276 mDisplays.clear();
1277}
1278
Steven Thomas050b2c82017-03-06 11:45:16 -08001279void SurfaceFlinger::updateVrFlinger() {
1280 if (!mVrFlinger)
1281 return;
1282 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1283 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001284 return;
1285 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001286
Steven Thomas050b2c82017-03-06 11:45:16 -08001287 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001288 // Construct new HWComposer without holding any locks.
1289 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001290
1291 // Set up the event handlers. This step is neccessary to initialize the internal state of
1292 // the hardware composer object properly. Our callbacks are designed such that if they are
1293 // triggered between now and the point where the display is properly re-initialized, they
1294 // will not have any effect, so this is safe to do here, before the lock is aquired.
1295 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001296 ALOGV("Vr HWC created");
1297 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001298
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001299 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001300
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301 if (vrFlingerRequestsDisplay) {
1302 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001303
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001304 mHwc = mVrHwc;
1305 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001306
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307 } else {
1308 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310 resetHwcLocked();
1311
1312 mHwc = mRealHwc;
1313 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001314 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001315
1316 mVisibleRegionsDirty = true;
1317 invalidateHwcGeometry();
1318
1319 // Explicitly re-initialize the primary display. This is because some other
1320 // parts of this class rely on the primary display always being available.
1321 createDefaultDisplayDevice();
1322
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001323 // Re-enable default display.
1324 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1325 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1326 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1327
1328 // Reset the timing values to account for the period of the swapped in HWC
1329 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1330 const nsecs_t period = activeConfig->getVsyncPeriod();
1331 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1332
1333 // Use phase of 0 since phase is not known.
1334 // Use latency of 0, which will snap to the ideal latency.
1335 setCompositorTimingSnapped(0, period, 0);
1336 });
1337 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001338
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339 android_atomic_or(1, &mRepaintEverything);
1340 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001341}
1342
Mathias Agopian4fec8732012-06-29 14:12:52 -07001343void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001344 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001346 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001347 bool frameMissed = !mHadClientComposition &&
1348 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001349 (mPreviousPresentFence->getSignalTime() ==
1350 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001351 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001352 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001353 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001354 signalLayerUpdate();
1355 break;
1356 }
1357
Steven Thomas050b2c82017-03-06 11:45:16 -08001358 // Now that we're going to make it to the handleMessageTransaction()
1359 // call below it's safe to call updateVrFlinger(), which will
1360 // potentially trigger a display handoff.
1361 updateVrFlinger();
1362
Dan Stoza6b9454d2014-11-07 16:00:59 -08001363 bool refreshNeeded = handleMessageTransaction();
1364 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001365 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001366 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001367 // Signal a refresh if a transaction modified the window state,
1368 // a new buffer was latched, or if HWC has requested a full
1369 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001370 signalRefresh();
1371 }
1372 break;
1373 }
1374 case MessageQueue::REFRESH: {
1375 handleMessageRefresh();
1376 break;
1377 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001378 }
1379}
1380
Dan Stoza6b9454d2014-11-07 16:00:59 -08001381bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001382 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001383 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001384 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001385 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001386 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001388}
1389
Dan Stoza6b9454d2014-11-07 16:00:59 -08001390bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001391 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001393}
1394
1395void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001396 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001397
Pablo Ceballos40845df2016-01-25 17:41:15 -08001398 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001399
Brian Andersond6927fb2016-07-23 23:37:30 -07001400 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001401 rebuildLayerStacks();
1402 setUpHWComposer();
1403 doDebugFlashRegions();
1404 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001405 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001406
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001407 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001408
1409 mHadClientComposition = false;
1410 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1411 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1412 mHadClientComposition = mHadClientComposition ||
1413 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1414 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001415
Dan Stoza9e56aa02015-11-02 13:00:03 -08001416 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001417}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001418
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419void SurfaceFlinger::doDebugFlashRegions()
1420{
1421 // is debugging enabled
1422 if (CC_LIKELY(!mDebugRegion))
1423 return;
1424
1425 const bool repaintEverything = mRepaintEverything;
1426 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1427 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001428 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001429 // transform the dirty region into this screen's coordinate space
1430 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1431 if (!dirtyRegion.isEmpty()) {
1432 // redraw the whole screen
1433 doComposeSurfaces(hw, Region(hw->bounds()));
1434
1435 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001437 RenderEngine& engine(getRenderEngine());
1438 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1439
Mathias Agopianda27af92012-09-13 18:17:13 -07001440 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441 }
1442 }
1443 }
1444
1445 postFramebuffer();
1446
1447 if (mDebugRegion > 1) {
1448 usleep(mDebugRegion * 1000);
1449 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001450
Dan Stoza9e56aa02015-11-02 13:00:03 -08001451 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001452 auto& displayDevice = mDisplays[displayId];
1453 if (!displayDevice->isDisplayOn()) {
1454 continue;
1455 }
1456
1457 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001458 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1459 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001460 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001461}
1462
Brian Andersond6927fb2016-07-23 23:37:30 -07001463void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001464{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001465 ATRACE_CALL();
1466 ALOGV("preComposition");
1467
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001469 mDrawingState.traverseInZOrder([&](Layer* layer) {
1470 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 needExtraInvalidate = true;
1472 }
Robert Carr2047fae2016-11-28 14:09:09 -08001473 });
1474
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 if (needExtraInvalidate) {
1476 signalLayerUpdate();
1477 }
1478}
1479
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001480void SurfaceFlinger::updateCompositorTiming(
1481 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1482 std::shared_ptr<FenceTime>& presentFenceTime) {
1483 // Update queue of past composite+present times and determine the
1484 // most recently known composite to present latency.
1485 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1486 nsecs_t compositeToPresentLatency = -1;
1487 while (!mCompositePresentTimes.empty()) {
1488 CompositePresentTime& cpt = mCompositePresentTimes.front();
1489 // Cached values should have been updated before calling this method,
1490 // which helps avoid duplicate syscalls.
1491 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1492 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1493 break;
1494 }
1495 compositeToPresentLatency = displayTime - cpt.composite;
1496 mCompositePresentTimes.pop();
1497 }
1498
1499 // Don't let mCompositePresentTimes grow unbounded, just in case.
1500 while (mCompositePresentTimes.size() > 16) {
1501 mCompositePresentTimes.pop();
1502 }
1503
Brian Andersond0010582017-03-07 13:20:31 -08001504 setCompositorTimingSnapped(
1505 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1506}
1507
1508void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1509 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510 // Integer division and modulo round toward 0 not -inf, so we need to
1511 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001512 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001513 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1514 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1515
Brian Andersond0010582017-03-07 13:20:31 -08001516 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1517 if (idealLatency <= 0) {
1518 idealLatency = vsyncInterval;
1519 }
1520
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521 // Snap the latency to a value that removes scheduling jitter from the
1522 // composition and present times, which often have >1ms of jitter.
1523 // Reducing jitter is important if an app attempts to extrapolate
1524 // something (such as user input) to an accurate diasplay time.
1525 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1526 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001527 nsecs_t bias = vsyncInterval / 2;
1528 int64_t extraVsyncs =
1529 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1530 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1531 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532
Brian Andersond0010582017-03-07 13:20:31 -08001533 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001534 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1535 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001536 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001537}
1538
1539void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001541 ATRACE_CALL();
1542 ALOGV("postComposition");
1543
Brian Anderson3546a3f2016-07-14 11:51:14 -07001544 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001545 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001546 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001547 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001548 }
1549
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001550 // |mStateLock| not needed as we are on the main thread
1551 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001552
1553 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1554 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1555 glCompositionDoneFenceTime =
1556 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1557 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1558 } else {
1559 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1560 }
1561 mGlCompositionDoneTimeline.updateSignalTimes();
1562
Brian Anderson4e606e32017-03-16 15:34:57 -07001563 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1564 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1565 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001566 mDisplayTimeline.updateSignalTimes();
1567
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1569 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1570
1571 // We use the refreshStartTime which might be sampled a little later than
1572 // when we started doing work for this frame, but that should be okay
1573 // since updateCompositorTiming has snapping logic.
1574 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001575 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001576 CompositorTiming compositorTiming;
1577 {
1578 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1579 compositorTiming = mCompositorTiming;
1580 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001581
Robert Carr2047fae2016-11-28 14:09:09 -08001582 mDrawingState.traverseInZOrder([&](Layer* layer) {
1583 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001584 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001585 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001586 recordBufferingStats(layer->getName().string(),
1587 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001588 }
Robert Carr2047fae2016-11-28 14:09:09 -08001589 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001590
Brian Anderson4e606e32017-03-16 15:34:57 -07001591 if (presentFence->isValid()) {
1592 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001593 enableHardwareVsync();
1594 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001595 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001596 }
1597 }
1598
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001599 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001600 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001601 enableHardwareVsync();
1602 }
1603 }
1604
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001605 if (mAnimCompositionPending) {
1606 mAnimCompositionPending = false;
1607
Brian Anderson4e606e32017-03-16 15:34:57 -07001608 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001609 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001610 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001611 } else {
1612 // The HWC doesn't support present fences, so use the refresh
1613 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001614 nsecs_t presentTime =
1615 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001616 mAnimFrameTracker.setActualPresentTime(presentTime);
1617 }
1618 mAnimFrameTracker.advanceFrame();
1619 }
Dan Stozab90cf072015-03-05 11:05:59 -08001620
1621 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1622 return;
1623 }
1624
1625 nsecs_t currentTime = systemTime();
1626 if (mHasPoweredOff) {
1627 mHasPoweredOff = false;
1628 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001629 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001630 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001631 if (numPeriods < NUM_BUCKETS - 1) {
1632 mFrameBuckets[numPeriods] += elapsedTime;
1633 } else {
1634 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1635 }
1636 mTotalTime += elapsedTime;
1637 }
1638 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001639}
1640
1641void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001642 ATRACE_CALL();
1643 ALOGV("rebuildLayerStacks");
1644
Mathias Agopiancd60f992012-08-16 16:28:27 -07001645 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001646 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1647 ATRACE_CALL();
1648 mVisibleRegionsDirty = false;
1649 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001650
Jeff Sharkey76488112017-02-27 14:15:18 -07001651 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1652 Region opaqueRegion;
1653 Region dirtyRegion;
1654 Vector<sp<Layer>> layersSortedByZ;
1655 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1656 const Transform& tr(displayDevice->getTransform());
1657 const Rect bounds(displayDevice->getBounds());
1658 if (displayDevice->isDisplayOn()) {
1659 computeVisibleRegions(
1660 displayDevice->getLayerStack(), dirtyRegion,
1661 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001662
Jeff Sharkey76488112017-02-27 14:15:18 -07001663 mDrawingState.traverseInZOrder([&](Layer* layer) {
1664 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1665 Region drawRegion(tr.transform(
1666 layer->visibleNonTransparentRegion));
1667 drawRegion.andSelf(bounds);
1668 if (!drawRegion.isEmpty()) {
1669 layersSortedByZ.add(layer);
1670 } else {
1671 // Clear out the HWC layer if this layer was
1672 // previously visible, but no longer is
1673 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1674 nullptr);
1675 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001676 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001677 // WM changes displayDevice->layerStack upon sleep/awake.
1678 // Here we make sure we delete the HWC layers even if
1679 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001680 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1681 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001682 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001683 });
1684 }
1685 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1686 displayDevice->undefinedRegion.set(bounds);
1687 displayDevice->undefinedRegion.subtractSelf(
1688 tr.transform(opaqueRegion));
1689 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001690 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001691 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001692}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001693
Romain Guy0147a172017-06-01 13:53:56 -07001694mat4 SurfaceFlinger::computeSaturationMatrix() const {
1695 if (mSaturation == 1.0f) {
1696 return mat4();
1697 }
1698
1699 // Rec.709 luma coefficients
1700 float3 luminance{0.213f, 0.715f, 0.072f};
1701 luminance *= 1.0f - mSaturation;
1702 return mat4(
1703 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1704 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1705 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1706 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1707 );
1708}
1709
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001710// pickColorMode translates a given dataspace into the best available color mode.
1711// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001712android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001713 switch (dataSpace) {
1714 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1715 // system expects.
1716 case HAL_DATASPACE_UNKNOWN:
1717 case HAL_DATASPACE_SRGB:
1718 case HAL_DATASPACE_V0_SRGB:
1719 return HAL_COLOR_MODE_SRGB;
1720 break;
1721
1722 case HAL_DATASPACE_DISPLAY_P3:
1723 return HAL_COLOR_MODE_DISPLAY_P3;
1724 break;
1725
1726 default:
1727 // TODO (courtneygo): Do we want to assert an error here?
1728 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1729 dataSpace);
1730 return HAL_COLOR_MODE_SRGB;
1731 break;
1732 }
1733}
1734
Romain Guy0147a172017-06-01 13:53:56 -07001735android_dataspace SurfaceFlinger::bestTargetDataSpace(
1736 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001737 // Only support sRGB and Display-P3 right now.
1738 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1739 return HAL_DATASPACE_DISPLAY_P3;
1740 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001741 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1742 return HAL_DATASPACE_DISPLAY_P3;
1743 }
1744 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1745 return HAL_DATASPACE_DISPLAY_P3;
1746 }
1747
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001748 return HAL_DATASPACE_V0_SRGB;
1749}
1750
Mathias Agopiancd60f992012-08-16 16:28:27 -07001751void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001752 ATRACE_CALL();
1753 ALOGV("setUpHWComposer");
1754
Jesse Hall028dc8f2013-08-20 16:35:32 -07001755 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001756 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1757 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1758 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1759
1760 // If nothing has changed (!dirty), don't recompose.
1761 // If something changed, but we don't currently have any visible layers,
1762 // and didn't when we last did a composition, then skip it this time.
1763 // The second rule does two things:
1764 // - When all layers are removed from a display, we'll emit one black
1765 // frame, then nothing more until we get new layers.
1766 // - When a display is created with a private layer stack, we won't
1767 // emit any black frames until a layer is added to the layer stack.
1768 bool mustRecompose = dirty && !(empty && wasEmpty);
1769
1770 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1771 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1772 mustRecompose ? "doing" : "skipping",
1773 dirty ? "+" : "-",
1774 empty ? "+" : "-",
1775 wasEmpty ? "+" : "-");
1776
Dan Stoza71433162014-02-04 16:22:36 -08001777 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001778
1779 if (mustRecompose) {
1780 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1781 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001782 }
1783
Dan Stoza9e56aa02015-11-02 13:00:03 -08001784 // build the h/w work list
1785 if (CC_UNLIKELY(mGeometryInvalid)) {
1786 mGeometryInvalid = false;
1787 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1788 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1789 const auto hwcId = displayDevice->getHwcDisplayId();
1790 if (hwcId >= 0) {
1791 const Vector<sp<Layer>>& currentLayers(
1792 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001793 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001794 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001795 if (!layer->hasHwcLayer(hwcId)) {
1796 auto hwcLayer = mHwc->createLayer(hwcId);
1797 if (hwcLayer) {
1798 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1799 } else {
1800 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001801 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001802 }
1803 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001804
Robert Carrae060832016-11-28 10:51:00 -08001805 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001806 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001808 }
1809 }
1810 }
1811 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 }
Riley Andrews03414a12014-07-01 14:22:59 -07001813
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001814
Romain Guy0147a172017-06-01 13:53:56 -07001815 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001816
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817 // Set the per-frame data
1818 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1819 auto& displayDevice = mDisplays[displayId];
1820 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001821
Dan Stoza9e56aa02015-11-02 13:00:03 -08001822 if (hwcId < 0) {
1823 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001824 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001825 if (colorMatrix != mPreviousColorMatrix) {
1826 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1827 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1828 "display %zd: %d", displayId, result);
1829 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1831 layer->setPerFrameData(displayDevice);
1832 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001833
1834 if (hasWideColorDisplay) {
1835 android_color_mode newColorMode;
1836 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1837
1838 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1839 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1840 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1841 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1842 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1843 }
1844 newColorMode = pickColorMode(newDataSpace);
1845
1846 setActiveColorModeInternal(displayDevice, newColorMode);
1847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001848 }
1849
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001850 mPreviousColorMatrix = colorMatrix;
1851
Dan Stoza9e56aa02015-11-02 13:00:03 -08001852 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001853 auto& displayDevice = mDisplays[displayId];
1854 if (!displayDevice->isDisplayOn()) {
1855 continue;
1856 }
1857
1858 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001859 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1860 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001861 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001863
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864void SurfaceFlinger::doComposition() {
1865 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 ALOGV("doComposition");
1867
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001868 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001869 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001870 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001871 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001872 // transform the dirty region into this screen's coordinate space
1873 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001874
1875 // repaint the framebuffer (if needed)
1876 doDisplayComposition(hw, dirtyRegion);
1877
Mathias Agopiancd60f992012-08-16 16:28:27 -07001878 hw->dirtyRegion.clear();
1879 hw->flip(hw->swapRegion);
1880 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001881 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001882 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001883 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001884}
1885
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886void SurfaceFlinger::postFramebuffer()
1887{
Mathias Agopian841cde52012-03-01 15:44:37 -08001888 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001890
Mathias Agopiana44b0412011-10-16 18:46:35 -07001891 const nsecs_t now = systemTime();
1892 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001893
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1895 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001896 if (!displayDevice->isDisplayOn()) {
1897 continue;
1898 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001899 const auto hwcId = displayDevice->getHwcDisplayId();
1900 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001901 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001902 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001903 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001904 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 sp<Fence> releaseFence = Fence::NO_FENCE;
1907 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1908 releaseFence = displayDevice->getClientTargetAcquireFence();
1909 } else {
1910 auto hwcLayer = layer->getHwcLayer(hwcId);
1911 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001912 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 layer->onLayerDisplayed(releaseFence);
1914 }
1915 if (hwcId >= 0) {
1916 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001917 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001918 }
1919
Mathias Agopiana44b0412011-10-16 18:46:35 -07001920 mLastSwapBufferTime = systemTime() - now;
1921 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001922
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001923 // |mStateLock| not needed as we are on the main thread
1924 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001925 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1926 logFrameStats();
1927 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001928}
1929
Mathias Agopian87baae12012-07-31 12:38:26 -07001930void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931{
Mathias Agopian841cde52012-03-01 15:44:37 -08001932 ATRACE_CALL();
1933
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001934 // here we keep a copy of the drawing state (that is the state that's
1935 // going to be overwritten by handleTransactionLocked()) outside of
1936 // mStateLock so that the side-effects of the State assignment
1937 // don't happen with mStateLock held (which can cause deadlocks).
1938 State drawingState(mDrawingState);
1939
Mathias Agopianca4d3602011-05-19 15:38:14 -07001940 Mutex::Autolock _l(mStateLock);
1941 const nsecs_t now = systemTime();
1942 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001943
Mathias Agopianca4d3602011-05-19 15:38:14 -07001944 // Here we're guaranteed that some transaction flags are set
1945 // so we can call handleTransactionLocked() unconditionally.
1946 // We call getTransactionFlags(), which will also clear the flags,
1947 // with mStateLock held to guarantee that mCurrentState won't change
1948 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001949
Mathias Agopiane57f2922012-08-09 16:29:12 -07001950 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001951 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001952
Mathias Agopianca4d3602011-05-19 15:38:14 -07001953 mLastTransactionTime = systemTime() - now;
1954 mDebugInTransaction = 0;
1955 invalidateHwcGeometry();
1956 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001957}
1958
Mathias Agopian87baae12012-07-31 12:38:26 -07001959void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001960{
Dan Stoza7dde5992015-05-22 09:51:44 -07001961 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001962 mCurrentState.traverseInZOrder([](Layer* layer) {
1963 layer->notifyAvailableFrames();
1964 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001965
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001966 /*
1967 * Traversal of the children
1968 * (perform the transaction for each of them if needed)
1969 */
1970
Mathias Agopian3559b072012-08-15 13:46:03 -07001971 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001972 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001973 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001974 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975
1976 const uint32_t flags = layer->doTransaction(0);
1977 if (flags & Layer::eVisibleRegion)
1978 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001979 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980 }
1981
1982 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001983 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001984 */
1985
Mathias Agopiane57f2922012-08-09 16:29:12 -07001986 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001987 // here we take advantage of Vector's copy-on-write semantics to
1988 // improve performance by skipping the transaction entirely when
1989 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001990 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1991 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001992 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001993 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001994 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001995 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001996
1997 // find the displays that were removed
1998 // (ie: in drawing state but not in current state)
1999 // also handle displays that changed
2000 // (ie: displays that are in both lists)
2001 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002002 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2003 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002004 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002005 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002006 // Call makeCurrent() on the primary display so we can
2007 // be sure that nothing associated with this display
2008 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002009 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002010 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002011 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002012 if (hw != NULL)
2013 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002014 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002015 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002016 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002017 } else {
2018 ALOGW("trying to remove the main display");
2019 }
2020 } else {
2021 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002022 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002023 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002024 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2025 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002026 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002027 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002028 // recreating the DisplayDevice, so we just remove it
2029 // from the drawing state, so that it get re-added
2030 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002031 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002032 if (hw != NULL)
2033 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002034 mDisplays.removeItem(display);
2035 mDrawingState.displays.removeItemsAt(i);
2036 dc--; i--;
2037 // at this point we must loop to the next item
2038 continue;
2039 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002040
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002041 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002042 if (disp != NULL) {
2043 if (state.layerStack != draw[i].layerStack) {
2044 disp->setLayerStack(state.layerStack);
2045 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002046 if ((state.orientation != draw[i].orientation)
2047 || (state.viewport != draw[i].viewport)
2048 || (state.frame != draw[i].frame))
2049 {
2050 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002051 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002052 }
Michael Lentine47e45402014-07-18 15:34:25 -07002053 if (state.width != draw[i].width || state.height != draw[i].height) {
2054 disp->setDisplaySize(state.width, state.height);
2055 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002056 }
2057 }
2058 }
2059
2060 // find displays that were added
2061 // (ie: in current state but not in drawing state)
2062 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002063 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002064 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002065
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002066 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002067 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002068 sp<IGraphicBufferProducer> bqProducer;
2069 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002070 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002071
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002073 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002074 // Virtual displays without a surface are dormant:
2075 // they have external state (layer stack, projection,
2076 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002077 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002078
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002079 // Allow VR composer to use virtual displays.
2080 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002081 int width = 0;
2082 int status = state.surface->query(
2083 NATIVE_WINDOW_WIDTH, &width);
2084 ALOGE_IF(status != NO_ERROR,
2085 "Unable to query width (%d)", status);
2086 int height = 0;
2087 status = state.surface->query(
2088 NATIVE_WINDOW_HEIGHT, &height);
2089 ALOGE_IF(status != NO_ERROR,
2090 "Unable to query height (%d)", status);
2091 int intFormat = 0;
2092 status = state.surface->query(
2093 NATIVE_WINDOW_FORMAT, &intFormat);
2094 ALOGE_IF(status != NO_ERROR,
2095 "Unable to query format (%d)", status);
2096 auto format = static_cast<android_pixel_format_t>(
2097 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002098
Dan Stoza8cf150a2016-08-02 10:27:31 -07002099 mHwc->allocateVirtualDisplay(width, height, &format,
2100 &hwcId);
2101 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102
Dan Stoza5cf424b2016-05-20 14:02:39 -07002103 // TODO: Plumb requested format back up to consumer
2104
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 sp<VirtualDisplaySurface> vds =
2106 new VirtualDisplaySurface(*mHwc,
2107 hwcId, state.surface, bqProducer,
2108 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002109
2110 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002111 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002112 }
2113 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002114 ALOGE_IF(state.surface!=NULL,
2115 "adding a supported display, but rendering "
2116 "surface is provided (%p), ignoring it",
2117 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002118
2119 hwcId = state.type;
2120 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2121 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002122 }
2123
2124 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002125 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002126 sp<DisplayDevice> hw =
2127 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2128 dispSurface, producer,
2129 mRenderEngine->getEGLConfig(),
2130 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002131 hw->setLayerStack(state.layerStack);
2132 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002133 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002134 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002135 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002136 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002137 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002138 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002139 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002140 }
2141 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002142 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002143 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144
Mathias Agopian84300952012-11-21 16:02:13 -08002145 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2146 // The transform hint might have changed for some layers
2147 // (either because a display has changed, or because a layer
2148 // as changed).
2149 //
2150 // Walk through all the layers in currentLayers,
2151 // and update their transform hint.
2152 //
2153 // If a layer is visible only on a single display, then that
2154 // display is used to calculate the hint, otherwise we use the
2155 // default display.
2156 //
2157 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2158 // the hint is set before we acquire a buffer from the surface texture.
2159 //
2160 // NOTE: layer transactions have taken place already, so we use their
2161 // drawing state. However, SurfaceFlinger's own transaction has not
2162 // happened yet, so we must use the current state layer list
2163 // (soon to become the drawing state list).
2164 //
2165 sp<const DisplayDevice> disp;
2166 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002167 bool first = true;
2168 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002169 // NOTE: we rely on the fact that layers are sorted by
2170 // layerStack first (so we don't have to traverse the list
2171 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002172 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002173 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002174 currentlayerStack = layerStack;
2175 // figure out if this layerstack is mirrored
2176 // (more than one display) if so, pick the default display,
2177 // if not, pick the only display it's on.
2178 disp.clear();
2179 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2180 sp<const DisplayDevice> hw(mDisplays[dpy]);
2181 if (hw->getLayerStack() == currentlayerStack) {
2182 if (disp == NULL) {
2183 disp = hw;
2184 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002185 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002186 break;
2187 }
2188 }
2189 }
2190 }
Chet Haase91d25932013-04-11 15:24:55 -07002191 if (disp == NULL) {
2192 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2193 // redraw after transform hint changes. See bug 8508397.
2194
2195 // could be null when this layer is using a layerStack
2196 // that is not visible on any display. Also can occur at
2197 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002198 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002199 }
Chet Haase91d25932013-04-11 15:24:55 -07002200 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002201
2202 first = false;
2203 });
Mathias Agopian84300952012-11-21 16:02:13 -08002204 }
2205
2206
Mathias Agopian3559b072012-08-15 13:46:03 -07002207 /*
2208 * Perform our own transaction if needed
2209 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002210
2211 if (mLayersAdded) {
2212 mLayersAdded = false;
2213 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002214 mVisibleRegionsDirty = true;
2215 }
2216
2217 // some layers might have been removed, so
2218 // we need to update the regions they're exposing.
2219 if (mLayersRemoved) {
2220 mLayersRemoved = false;
2221 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002222 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002223 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002224 // this layer is not visible anymore
2225 // TODO: we could traverse the tree from front to back and
2226 // compute the actual visible region
2227 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002228 Region visibleReg;
2229 visibleReg.set(layer->computeScreenBounds());
2230 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002231 }
Robert Carr2047fae2016-11-28 14:09:09 -08002232 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002233 }
2234
2235 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002236
2237 updateCursorAsync();
2238}
2239
2240void SurfaceFlinger::updateCursorAsync()
2241{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2243 auto& displayDevice = mDisplays[displayId];
2244 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002245 continue;
2246 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002247
2248 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2249 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002250 }
2251 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002252}
2253
2254void SurfaceFlinger::commitTransaction()
2255{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002256 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002257 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002258 for (const auto& l : mLayersPendingRemoval) {
2259 recordBufferingStats(l->getName().string(),
2260 l->getOccupancyHistory(true));
2261 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002262 }
2263 mLayersPendingRemoval.clear();
2264 }
2265
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002266 // If this transaction is part of a window animation then the next frame
2267 // we composite should be considered an animation as well.
2268 mAnimCompositionPending = mAnimTransactionPending;
2269
Mathias Agopian4fec8732012-06-29 14:12:52 -07002270 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002271 mDrawingState.traverseInZOrder([](Layer* layer) {
2272 layer->commitChildList();
2273 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002274 mTransactionPending = false;
2275 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002276 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002277}
2278
Robert Carr2047fae2016-11-28 14:09:09 -08002279void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002280 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281{
Mathias Agopian841cde52012-03-01 15:44:37 -08002282 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002283 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285 Region aboveOpaqueLayers;
2286 Region aboveCoveredLayers;
2287 Region dirty;
2288
Mathias Agopian87baae12012-07-31 12:38:26 -07002289 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002290
Robert Carr2047fae2016-11-28 14:09:09 -08002291 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002292 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002293 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294
Jesse Hall01e29052013-02-19 16:13:35 -08002295 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002296 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002297 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002298
Mathias Agopianab028732010-03-16 16:41:46 -07002299 /*
2300 * opaqueRegion: area of a surface that is fully opaque.
2301 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002303
2304 /*
2305 * visibleRegion: area of a surface that is visible on screen
2306 * and not fully transparent. This is essentially the layer's
2307 * footprint minus the opaque regions above it.
2308 * Areas covered by a translucent surface are considered visible.
2309 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002311
2312 /*
2313 * coveredRegion: area of a surface that is covered by all
2314 * visible regions above it (which includes the translucent areas).
2315 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002316 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002317
Jesse Halla8026d22012-09-25 13:25:04 -07002318 /*
2319 * transparentRegion: area of a surface that is hinted to be completely
2320 * transparent. This is only used to tell when the layer has no visible
2321 * non-transparent regions and can be removed from the layer list. It
2322 * does not affect the visibleRegion of this layer or any layers
2323 * beneath it. The hint may not be correct if apps don't respect the
2324 * SurfaceView restrictions (which, sadly, some don't).
2325 */
2326 Region transparentRegion;
2327
Mathias Agopianab028732010-03-16 16:41:46 -07002328
2329 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002330 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002331 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002332 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002334 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002335 if (!visibleRegion.isEmpty()) {
2336 // Remove the transparent area from the visible region
2337 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002338 if (tr.preserveRects()) {
2339 // transform the transparent region
2340 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002341 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002342 // transformation too complex, can't do the
2343 // transparent region optimization.
2344 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002345 }
Mathias Agopianab028732010-03-16 16:41:46 -07002346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347
Mathias Agopianab028732010-03-16 16:41:46 -07002348 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002349 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002350 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002351 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2352 // the opaque region is the layer's footprint
2353 opaqueRegion = visibleRegion;
2354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355 }
2356 }
2357
Mathias Agopianab028732010-03-16 16:41:46 -07002358 // Clip the covered region to the visible region
2359 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2360
2361 // Update aboveCoveredLayers for next (lower) layer
2362 aboveCoveredLayers.orSelf(visibleRegion);
2363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 // subtract the opaque region covered by the layers above us
2365 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366
2367 // compute this layer's dirty region
2368 if (layer->contentDirty) {
2369 // we need to invalidate the whole region
2370 dirty = visibleRegion;
2371 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002372 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373 layer->contentDirty = false;
2374 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002375 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002376 * the exposed region consists of two components:
2377 * 1) what's VISIBLE now and was COVERED before
2378 * 2) what's EXPOSED now less what was EXPOSED before
2379 *
2380 * note that (1) is conservative, we start with the whole
2381 * visible region but only keep what used to be covered by
2382 * something -- which mean it may have been exposed.
2383 *
2384 * (2) handles areas that were not covered by anything but got
2385 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002386 */
Mathias Agopianab028732010-03-16 16:41:46 -07002387 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002388 const Region oldVisibleRegion = layer->visibleRegion;
2389 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002390 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2391 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 }
2393 dirty.subtractSelf(aboveOpaqueLayers);
2394
2395 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002396 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397
Mathias Agopianab028732010-03-16 16:41:46 -07002398 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002399 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002400
Jesse Halla8026d22012-09-25 13:25:04 -07002401 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402 layer->setVisibleRegion(visibleRegion);
2403 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002404 layer->setVisibleNonTransparentRegion(
2405 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002406 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002407
Mathias Agopian87baae12012-07-31 12:38:26 -07002408 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409}
2410
Mathias Agopian87baae12012-07-31 12:38:26 -07002411void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2412 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002413 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002414 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2415 if (hw->getLayerStack() == layerStack) {
2416 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002417 }
2418 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002419}
2420
Dan Stoza6b9454d2014-11-07 16:00:59 -08002421bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423 ALOGV("handlePageFlip");
2424
Brian Andersond6927fb2016-07-23 23:37:30 -07002425 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426
Mathias Agopian4fec8732012-06-29 14:12:52 -07002427 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002428 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002429 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002430
2431 // Store the set of layers that need updates. This set must not change as
2432 // buffers are being latched, as this could result in a deadlock.
2433 // Example: Two producers share the same command stream and:
2434 // 1.) Layer 0 is latched
2435 // 2.) Layer 0 gets a new frame
2436 // 2.) Layer 1 gets a new frame
2437 // 3.) Layer 1 is latched.
2438 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2439 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002440 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002441 if (layer->hasQueuedFrame()) {
2442 frameQueued = true;
2443 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002444 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002445 } else {
2446 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002447 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002448 } else {
2449 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002450 }
Robert Carr2047fae2016-11-28 14:09:09 -08002451 });
2452
Dan Stoza9e56aa02015-11-02 13:00:03 -08002453 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002454 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002455 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002456 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002457 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002458 newDataLatched = true;
2459 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002460 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002461
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002462 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002463
2464 // If we will need to wake up at some time in the future to deal with a
2465 // queued frame that shouldn't be displayed during this vsync period, wake
2466 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002467 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002468 signalLayerUpdate();
2469 }
2470
2471 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002472 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473}
2474
Mathias Agopianad456f92011-01-13 17:53:01 -08002475void SurfaceFlinger::invalidateHwcGeometry()
2476{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002478}
2479
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002480
Fabien Sanglard830b8472016-11-30 16:35:58 -08002481void SurfaceFlinger::doDisplayComposition(
2482 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002483 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484{
Dan Stoza71433162014-02-04 16:22:36 -08002485 // We only need to actually compose the display if:
2486 // 1) It is being handled by hardware composer, which may need this to
2487 // keep its virtual display state machine in sync, or
2488 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002489 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002490 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002491 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002492 return;
2493 }
2494
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 ALOGV("doDisplayComposition");
2496
Mathias Agopian87baae12012-07-31 12:38:26 -07002497 Region dirtyRegion(inDirtyRegion);
2498
Mathias Agopianb8a55602009-06-26 19:06:36 -07002499 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002500 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002501
Fabien Sanglard830b8472016-11-30 16:35:58 -08002502 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002503 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002504 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2505 // takes a rectangle, we must make sure to update that whole
2506 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002507 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002508 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002509 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002510 // We need to redraw the rectangle that will be updated
2511 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002512 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002513 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002514 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002515 } else {
2516 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002517 dirtyRegion.set(displayDevice->bounds());
2518 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519 }
2520 }
2521
Fabien Sanglard830b8472016-11-30 16:35:58 -08002522 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002524 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002525 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002526
2527 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002528 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529}
2530
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531bool SurfaceFlinger::doComposeSurfaces(
2532 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002533{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002534 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002535
Dan Stoza9e56aa02015-11-02 13:00:03 -08002536 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002537
2538 mat4 oldColorMatrix;
2539 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2540 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2541 if (applyColorMatrix) {
2542 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2543 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2544 }
2545
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2547 if (hasClientComposition) {
2548 ALOGV("hasClientComposition");
2549
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002550#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002551 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002552 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002553#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002554 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002555 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002556 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002557 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002558
2559 // |mStateLock| not needed as we are on the main thread
2560 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002561 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2562 }
2563 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002564 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002565
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002566 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002567 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2568 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002569 // when using overlays, we assume a fully transparent framebuffer
2570 // NOTE: we could reduce how much we need to clear, for instance
2571 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002572 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002573 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002574 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002575 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002576 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002578
2579 // we remove the scissor part
2580 // we're left with the letterbox region
2581 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002582 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002583
2584 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002585 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002586
2587 // but limit it to the dirty region
2588 region.andSelf(dirty);
2589
Mathias Agopianb9494d52012-04-18 02:28:45 -07002590 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002591 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002592 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002593 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002594 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002595 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002596
Dan Stoza9e56aa02015-11-02 13:00:03 -08002597 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002598 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002599 // scissor on the main display. It should never be needed
2600 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 const Rect& bounds(displayDevice->getBounds());
2602 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002603 if (scissor != bounds) {
2604 // scissor doesn't match the screen's dimensions, so we
2605 // need to clear everything outside of it and enable
2606 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002607
Mathias Agopianf45c5102012-10-24 16:29:17 -07002608 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 const uint32_t height = displayDevice->getHeight();
2610 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002611 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002612 }
2613 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002614 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002615
Mathias Agopian85d751c2012-08-29 16:59:24 -07002616 /*
2617 * and then, render the layers targeted at the framebuffer
2618 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002619
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 ALOGV("Rendering client layers");
2621 const Transform& displayTransform = displayDevice->getTransform();
2622 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002623 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 bool firstLayer = true;
2625 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2626 const Region clip(dirty.intersect(
2627 displayTransform.transform(layer->visibleRegion)));
2628 ALOGV("Layer: %s", layer->getName().string());
2629 ALOGV(" Composition type: %s",
2630 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002631 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 switch (layer->getCompositionType(hwcId)) {
2633 case HWC2::Composition::Cursor:
2634 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002635 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002636 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002637 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002638 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2639 layer->isOpaque(state) && (state.alpha == 1.0f)
2640 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002641 // never clear the very first layer since we're
2642 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002643 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002644 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002645 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002646 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002647 case HWC2::Composition::Client: {
2648 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002649 break;
2650 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002652 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002653 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 } else {
2655 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002656 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002657 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002658 }
2659 } else {
2660 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002662 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002663 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002664 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002666 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002667 }
2668 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002669
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002670 if (applyColorMatrix) {
2671 getRenderEngine().setupColorTransform(oldColorMatrix);
2672 }
2673
Mathias Agopianf45c5102012-10-24 16:29:17 -07002674 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002676 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677}
2678
Fabien Sanglard830b8472016-11-30 16:35:58 -08002679void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2680 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002681 RenderEngine& engine(getRenderEngine());
2682 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002683}
2684
Dan Stoza7d89d062015-04-30 13:29:25 -07002685status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002686 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002687 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688 const sp<Layer>& lbc,
2689 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002690{
Dan Stoza7d89d062015-04-30 13:29:25 -07002691 // add this layer to the current state list
2692 {
2693 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002695 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2696 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002697 return NO_MEMORY;
2698 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002699 if (parent == nullptr) {
2700 mCurrentState.layersSortedByZ.add(lbc);
2701 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002702 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2703 ALOGE("addClientLayer called with a removed parent");
2704 return NAME_NOT_FOUND;
2705 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002706 parent->addChild(lbc);
2707 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002708
Dan Stoza7d89d062015-04-30 13:29:25 -07002709 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 mLayersAdded = true;
2711 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002712 }
2713
Mathias Agopian96f08192010-06-02 23:28:45 -07002714 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002715 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002716
Dan Stoza7d89d062015-04-30 13:29:25 -07002717 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002718}
2719
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002720status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002721 Mutex::Autolock _l(mStateLock);
2722
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002724 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002725 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002726 if (topLevelOnly) {
2727 return NO_ERROR;
2728 }
2729
Chia-I Wu98f1c102017-05-30 14:54:08 -07002730 sp<Layer> ancestor = p;
2731 while (ancestor->getParent() != nullptr) {
2732 ancestor = ancestor->getParent();
2733 }
2734 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2735 ALOGE("removeLayer called with a layer whose parent has been removed");
2736 return NAME_NOT_FOUND;
2737 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002738
2739 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002740 } else {
2741 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002742 }
2743
Robert Carr136e2f62017-02-08 17:54:29 -08002744 // As a matter of normal operation, the LayerCleaner will produce a second
2745 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2746 // so we will succeed in promoting it, but it's already been removed
2747 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2748 // otherwise something has gone wrong and we are leaking the layer.
2749 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2751 layer->getName().string(),
2752 (p != nullptr) ? p->getName().string() : "no-parent");
2753 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002754 } else if (index < 0) {
2755 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002756 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002757
2758 mLayersPendingRemoval.add(layer);
2759 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002760 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 setTransactionFlags(eTransactionNeeded);
2762 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763}
2764
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002765uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002766 return android_atomic_release_load(&mTransactionFlags);
2767}
2768
Mathias Agopian3f844832013-08-07 21:24:32 -07002769uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2771}
2772
Mathias Agopian3f844832013-08-07 21:24:32 -07002773uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2775 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002776 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002777 }
2778 return old;
2779}
2780
Mathias Agopian8b33f032012-07-24 20:43:54 -07002781void SurfaceFlinger::setTransactionState(
2782 const Vector<ComposerState>& state,
2783 const Vector<DisplayState>& displays,
2784 uint32_t flags)
2785{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002786 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002787 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002788 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002789
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002790 if (flags & eAnimation) {
2791 // For window updates that are part of an animation we must wait for
2792 // previous animation "frames" to be handled.
2793 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002794 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002795 if (CC_UNLIKELY(err != NO_ERROR)) {
2796 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002797 // caller after a few seconds.
2798 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2799 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002800 mAnimTransactionPending = false;
2801 break;
2802 }
2803 }
2804 }
2805
Mathias Agopiane57f2922012-08-09 16:29:12 -07002806 size_t count = displays.size();
2807 for (size_t i=0 ; i<count ; i++) {
2808 const DisplayState& s(displays[i]);
2809 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002810 }
2811
Mathias Agopiane57f2922012-08-09 16:29:12 -07002812 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002813 for (size_t i=0 ; i<count ; i++) {
2814 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002815 // Here we need to check that the interface we're given is indeed
2816 // one of our own. A malicious client could give us a NULL
2817 // IInterface, or one of its own or even one of our own but a
2818 // different type. All these situations would cause us to crash.
2819 //
2820 // NOTE: it would be better to use RTTI as we could directly check
2821 // that we have a Client*. however, RTTI is disabled in Android.
2822 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002823 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002824 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002825 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002826 sp<Client> client( static_cast<Client *>(s.client.get()) );
2827 transactionFlags |= setClientStateLocked(client, s.state);
2828 }
2829 }
2830 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002831 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002832
Robert Carr2a7dbb42016-05-24 11:41:28 -07002833 // If a synchronous transaction is explicitly requested without any changes,
2834 // force a transaction anyway. This can be used as a flush mechanism for
2835 // previous async transactions.
2836 if (transactionFlags == 0 && (flags & eSynchronous)) {
2837 transactionFlags = eTransactionNeeded;
2838 }
2839
Mathias Agopian386aa982011-11-07 21:58:03 -08002840 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002841 if (mInterceptor.isEnabled()) {
2842 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2843 }
Irvel468051e2016-06-13 16:44:44 -07002844
Mathias Agopian386aa982011-11-07 21:58:03 -08002845 // this triggers the transaction
2846 setTransactionFlags(transactionFlags);
2847
2848 // if this is a synchronous transaction, wait for it to take effect
2849 // before returning.
2850 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002851 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002852 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002853 if (flags & eAnimation) {
2854 mAnimTransactionPending = true;
2855 }
2856 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002857 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2858 if (CC_UNLIKELY(err != NO_ERROR)) {
2859 // just in case something goes wrong in SF, return to the
2860 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002861 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2862 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002863 break;
2864 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002865 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866 }
2867}
2868
Mathias Agopiane57f2922012-08-09 16:29:12 -07002869uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2870{
Jesse Hall9a143922012-10-04 16:29:19 -07002871 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2872 if (dpyIdx < 0)
2873 return 0;
2874
Mathias Agopiane57f2922012-08-09 16:29:12 -07002875 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002876 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002877 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878 const uint32_t what = s.what;
2879 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002880 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002881 disp.surface = s.surface;
2882 flags |= eDisplayTransactionNeeded;
2883 }
2884 }
2885 if (what & DisplayState::eLayerStackChanged) {
2886 if (disp.layerStack != s.layerStack) {
2887 disp.layerStack = s.layerStack;
2888 flags |= eDisplayTransactionNeeded;
2889 }
2890 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002891 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002892 if (disp.orientation != s.orientation) {
2893 disp.orientation = s.orientation;
2894 flags |= eDisplayTransactionNeeded;
2895 }
2896 if (disp.frame != s.frame) {
2897 disp.frame = s.frame;
2898 flags |= eDisplayTransactionNeeded;
2899 }
2900 if (disp.viewport != s.viewport) {
2901 disp.viewport = s.viewport;
2902 flags |= eDisplayTransactionNeeded;
2903 }
2904 }
Michael Lentine47e45402014-07-18 15:34:25 -07002905 if (what & DisplayState::eDisplaySizeChanged) {
2906 if (disp.width != s.width) {
2907 disp.width = s.width;
2908 flags |= eDisplayTransactionNeeded;
2909 }
2910 if (disp.height != s.height) {
2911 disp.height = s.height;
2912 flags |= eDisplayTransactionNeeded;
2913 }
2914 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002915 }
2916 return flags;
2917}
2918
2919uint32_t SurfaceFlinger::setClientStateLocked(
2920 const sp<Client>& client,
2921 const layer_state_t& s)
2922{
2923 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002924 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002925 if (layer != 0) {
2926 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002927 bool geometryAppliesWithResize =
2928 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002929 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002930 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002931 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002932 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 }
2934 if (what & layer_state_t::eLayerChanged) {
2935 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002936 const auto& p = layer->getParent();
2937 if (p == nullptr) {
2938 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2939 if (layer->setLayer(s.z) && idx >= 0) {
2940 mCurrentState.layersSortedByZ.removeAt(idx);
2941 mCurrentState.layersSortedByZ.add(layer);
2942 // we need traversal (state changed)
2943 // AND transaction (list changed)
2944 flags |= eTransactionNeeded|eTraversalNeeded;
2945 }
2946 } else {
2947 if (p->setChildLayer(layer, s.z)) {
2948 flags |= eTransactionNeeded|eTraversalNeeded;
2949 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002950 }
2951 }
Robert Carrdb66e622017-04-10 16:55:57 -07002952 if (what & layer_state_t::eRelativeLayerChanged) {
2953 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2954 flags |= eTransactionNeeded|eTraversalNeeded;
2955 }
2956 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957 if (what & layer_state_t::eSizeChanged) {
2958 if (layer->setSize(s.w, s.h)) {
2959 flags |= eTraversalNeeded;
2960 }
2961 }
2962 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002963 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002964 flags |= eTraversalNeeded;
2965 }
2966 if (what & layer_state_t::eMatrixChanged) {
2967 if (layer->setMatrix(s.matrix))
2968 flags |= eTraversalNeeded;
2969 }
2970 if (what & layer_state_t::eTransparentRegionChanged) {
2971 if (layer->setTransparentRegionHint(s.transparentRegion))
2972 flags |= eTraversalNeeded;
2973 }
Dan Stoza23116082015-06-18 14:58:39 -07002974 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002975 if (layer->setFlags(s.flags, s.mask))
2976 flags |= eTraversalNeeded;
2977 }
2978 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002979 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002980 flags |= eTraversalNeeded;
2981 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002982 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002983 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002984 flags |= eTraversalNeeded;
2985 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002986 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002987 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002988 // We only allow setting layer stacks for top level layers,
2989 // everything else inherits layer stack from its parent.
2990 if (layer->hasParent()) {
2991 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2992 layer->getName().string());
2993 } else if (idx < 0) {
2994 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2995 "that also does not appear in the top level layer list. Something"
2996 " has gone wrong.", layer->getName().string());
2997 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002998 mCurrentState.layersSortedByZ.removeAt(idx);
2999 mCurrentState.layersSortedByZ.add(layer);
3000 // we need traversal (state changed)
3001 // AND transaction (list changed)
3002 flags |= eTransactionNeeded|eTraversalNeeded;
3003 }
3004 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003005 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003006 if (s.barrierHandle != nullptr) {
3007 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3008 } else if (s.barrierGbp != nullptr) {
3009 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3010 if (authenticateSurfaceTextureLocked(gbp)) {
3011 const auto& otherLayer =
3012 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3013 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3014 } else {
3015 ALOGE("Attempt to defer transaction to to an"
3016 " unrecognized GraphicBufferProducer");
3017 }
3018 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003019 // We don't trigger a traversal here because if no other state is
3020 // changed, we don't want this to cause any more work
3021 }
Robert Carr1db73f62016-12-21 12:58:51 -08003022 if (what & layer_state_t::eReparentChildren) {
3023 if (layer->reparentChildren(s.reparentHandle)) {
3024 flags |= eTransactionNeeded|eTraversalNeeded;
3025 }
3026 }
Robert Carr9524cb32017-02-13 11:32:32 -08003027 if (what & layer_state_t::eDetachChildren) {
3028 layer->detachChildren();
3029 }
Robert Carrc3574f72016-03-24 12:19:32 -07003030 if (what & layer_state_t::eOverrideScalingModeChanged) {
3031 layer->setOverrideScalingMode(s.overrideScalingMode);
3032 // We don't trigger a traversal here because if no other state is
3033 // changed, we don't want this to cause any more work
3034 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003035 }
3036 return flags;
3037}
3038
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003039status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003040 const String8& name,
3041 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003042 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003043 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3044 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003046 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003047 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003048 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003049 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003050 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003051
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003052 status_t result = NO_ERROR;
3053
3054 sp<Layer> layer;
3055
Cody Northropbc755282017-03-31 12:00:08 -06003056 String8 uniqueName = getUniqueLayerName(name);
3057
Mathias Agopian3165cc22012-08-08 19:42:09 -07003058 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3059 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003060 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003061 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003062 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003064 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003065 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003066 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003067 handle, gbp, &layer);
3068 break;
3069 default:
3070 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071 break;
3072 }
3073
Dan Stoza7d89d062015-04-30 13:29:25 -07003074 if (result != NO_ERROR) {
3075 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003076 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003077
Albert Chaulk479c60c2017-01-27 14:21:34 -05003078 layer->setInfo(windowType, ownerUid);
3079
Robert Carr1f0a16a2016-10-24 16:27:39 -07003080 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003081 if (result != NO_ERROR) {
3082 return result;
3083 }
Irvelffc9efc2016-07-27 15:16:37 -07003084 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003085
3086 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003087 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088}
3089
Cody Northropbc755282017-03-31 12:00:08 -06003090String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3091{
3092 bool matchFound = true;
3093 uint32_t dupeCounter = 0;
3094
3095 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3096 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3097
3098 // Loop over layers until we're sure there is no matching name
3099 while (matchFound) {
3100 matchFound = false;
3101 mDrawingState.traverseInZOrder([&](Layer* layer) {
3102 if (layer->getName() == uniqueName) {
3103 matchFound = true;
3104 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3105 }
3106 });
3107 }
3108
3109 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3110
3111 return uniqueName;
3112}
3113
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003114status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3115 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3116 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117{
3118 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003119 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120 case PIXEL_FORMAT_TRANSPARENT:
3121 case PIXEL_FORMAT_TRANSLUCENT:
3122 format = PIXEL_FORMAT_RGBA_8888;
3123 break;
3124 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003125 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126 break;
3127 }
3128
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003129 *outLayer = new Layer(this, client, name, w, h, flags);
3130 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3131 if (err == NO_ERROR) {
3132 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003133 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003135
3136 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3137 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138}
3139
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003140status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3141 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3142 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003144 *outLayer = new LayerDim(this, client, name, w, h, flags);
3145 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003146 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003147 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003148}
3149
Mathias Agopianac9fa422013-02-11 16:40:36 -08003150status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151{
Robert Carr9524cb32017-02-13 11:32:32 -08003152 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003153 status_t err = NO_ERROR;
3154 sp<Layer> l(client->getLayerUser(handle));
3155 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003156 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003157 err = removeLayer(l);
3158 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3159 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003160 }
3161 return err;
3162}
3163
Mathias Agopian13127d82013-03-05 17:47:11 -08003164status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003165{
Mathias Agopian67106042013-03-14 19:18:13 -07003166 // called by ~LayerCleaner() when all references to the IBinder (handle)
3167 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003168 sp<Layer> l = layer.promote();
3169 if (l == nullptr) {
3170 // The layer has already been removed, carry on
3171 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003172 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003173 // If we have a parent, then we can continue to live as long as it does.
3174 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175}
3176
Mathias Agopianb60314a2012-04-10 22:09:54 -07003177// ---------------------------------------------------------------------------
3178
Andy McFadden13a082e2012-08-24 10:16:42 -07003179void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003180 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003181 Vector<ComposerState> state;
3182 Vector<DisplayState> displays;
3183 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003184 d.what = DisplayState::eDisplayProjectionChanged |
3185 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003186 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003187 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003188 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003189 d.frame.makeInvalid();
3190 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003191 d.width = 0;
3192 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003193 displays.add(d);
3194 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003195 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003196
Dan Stoza9e56aa02015-11-02 13:00:03 -08003197 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3198 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003199 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003200
Brian Andersond0010582017-03-07 13:20:31 -08003201 // Use phase of 0 since phase is not known.
3202 // Use latency of 0, which will snap to the ideal latency.
3203 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003204}
3205
3206void SurfaceFlinger::initializeDisplays() {
3207 class MessageScreenInitialized : public MessageBase {
3208 SurfaceFlinger* flinger;
3209 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003210 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003211 virtual bool handler() {
3212 flinger->onInitializeDisplays();
3213 return true;
3214 }
3215 };
3216 sp<MessageBase> msg = new MessageScreenInitialized(this);
3217 postMessageAsync(msg); // we may be called from main thread, use async message
3218}
3219
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003220void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3221 int mode) {
3222 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3223 this);
3224 int32_t type = hw->getDisplayType();
3225 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003226
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003227 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003228 return;
3229 }
3230
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003231 hw->setPowerMode(mode);
3232 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3233 ALOGW("Trying to set power mode for virtual display");
3234 return;
3235 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003236
Irvelffc9efc2016-07-27 15:16:37 -07003237 if (mInterceptor.isEnabled()) {
3238 Mutex::Autolock _l(mStateLock);
3239 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3240 if (idx < 0) {
3241 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3242 return;
3243 }
3244 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3245 }
3246
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003247 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003248 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003249 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003250 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3251 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003252 // FIXME: eventthread only knows about the main display right now
3253 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003254 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003255 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003257 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003258 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003259 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003260
3261 struct sched_param param = {0};
3262 param.sched_priority = 1;
3263 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3264 ALOGW("Couldn't set SCHED_FIFO on display on");
3265 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003266 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003267 // Turn off the display
3268 struct sched_param param = {0};
3269 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3270 ALOGW("Couldn't set SCHED_OTHER on display off");
3271 }
3272
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003273 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003274 disableHardwareVsync(true); // also cancels any in-progress resync
3275
Mathias Agopiancde87a32012-09-13 14:09:01 -07003276 // FIXME: eventthread only knows about the main display right now
3277 mEventThread->onScreenReleased();
3278 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003279
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003280 getHwComposer().setPowerMode(type, mode);
3281 mVisibleRegionsDirty = true;
3282 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003283 } else if (mode == HWC_POWER_MODE_DOZE ||
3284 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003285 // Update display while dozing
3286 getHwComposer().setPowerMode(type, mode);
3287 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3288 // FIXME: eventthread only knows about the main display right now
3289 mEventThread->onScreenAcquired();
3290 resyncToHardwareVsync(true);
3291 }
3292 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3293 // Leave display going to doze
3294 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3295 disableHardwareVsync(true); // also cancels any in-progress resync
3296 // FIXME: eventthread only knows about the main display right now
3297 mEventThread->onScreenReleased();
3298 }
3299 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003300 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003301 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003302 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003303 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003304}
3305
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003306void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3307 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003308 SurfaceFlinger& mFlinger;
3309 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003310 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003311 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003312 MessageSetPowerMode(SurfaceFlinger& flinger,
3313 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3314 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003315 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003316 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003317 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003318 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003319 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003320 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003321 ALOGW("Attempt to set power mode = %d for virtual display",
3322 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003323 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003324 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003325 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003326 return true;
3327 }
3328 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003329 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003330 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003331}
3332
3333// ---------------------------------------------------------------------------
3334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003335status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3336{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003338
Mathias Agopianbd115332013-04-18 16:41:04 -07003339 IPCThreadState* ipc = IPCThreadState::self();
3340 const int pid = ipc->getCallingPid();
3341 const int uid = ipc->getCallingUid();
3342 if ((uid != AID_SHELL) &&
3343 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003344 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003345 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003346 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003347 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003348 // (this would indicate SF is stuck, but we want to be able to
3349 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003350 status_t err = mStateLock.timedLock(s2ns(1));
3351 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003352 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003353 result.appendFormat(
3354 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3355 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003356 }
3357
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003358 bool dumpAll = true;
3359 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003360 size_t numArgs = args.size();
3361 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003362 if ((index < numArgs) &&
3363 (args[index] == String16("--list"))) {
3364 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003365 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003366 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003367 }
3368
3369 if ((index < numArgs) &&
3370 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003371 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003372 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003373 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003374 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003375
3376 if ((index < numArgs) &&
3377 (args[index] == String16("--latency-clear"))) {
3378 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003379 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003380 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003381 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003382
3383 if ((index < numArgs) &&
3384 (args[index] == String16("--dispsync"))) {
3385 index++;
3386 mPrimaryDispSync.dump(result);
3387 dumpAll = false;
3388 }
Dan Stozab90cf072015-03-05 11:05:59 -08003389
3390 if ((index < numArgs) &&
3391 (args[index] == String16("--static-screen"))) {
3392 index++;
3393 dumpStaticScreenStats(result);
3394 dumpAll = false;
3395 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003396
3397 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003398 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003399 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003400 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003401 dumpAll = false;
3402 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003403
3404 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3405 index++;
3406 dumpWideColorInfo(result);
3407 dumpAll = false;
3408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003410
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003411 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003412 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003413 }
3414
Mathias Agopian9795c422009-08-26 16:36:26 -07003415 if (locked) {
3416 mStateLock.unlock();
3417 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003418 }
3419 write(fd, result.string(), result.size());
3420 return NO_ERROR;
3421}
3422
Dan Stozac7014012014-02-14 15:03:43 -08003423void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3424 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003425{
Robert Carr2047fae2016-11-28 14:09:09 -08003426 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003427 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003428 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003429}
3430
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003431void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003433{
3434 String8 name;
3435 if (index < args.size()) {
3436 name = String8(args[index]);
3437 index++;
3438 }
3439
Dan Stoza9e56aa02015-11-02 13:00:03 -08003440 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3441 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003442 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003443
3444 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003445 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003446 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003447 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003448 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003449 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003450 }
Robert Carr2047fae2016-11-28 14:09:09 -08003451 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003452 }
3453}
3454
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003455void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003456 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003457{
3458 String8 name;
3459 if (index < args.size()) {
3460 name = String8(args[index]);
3461 index++;
3462 }
3463
Robert Carr2047fae2016-11-28 14:09:09 -08003464 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003465 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003466 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003467 }
Robert Carr2047fae2016-11-28 14:09:09 -08003468 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003469
Svetoslavd85084b2014-03-20 10:28:31 -07003470 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003471}
3472
Jamie Gennis6547ff42013-07-16 20:12:42 -07003473// This should only be called from the main thread. Otherwise it would need
3474// the lock and should use mCurrentState rather than mDrawingState.
3475void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003476 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003477 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003478 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003479
3480 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3481}
3482
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003483void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003484{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003485 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003486 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3487
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003488 if (isLayerTripleBufferingDisabled())
3489 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003490
3491 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003492 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003493 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003494 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003495 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3496 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003497 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003498}
3499
Dan Stozab90cf072015-03-05 11:05:59 -08003500void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3501{
3502 result.appendFormat("Static screen stats:\n");
3503 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3504 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3505 float percent = 100.0f *
3506 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3507 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3508 b + 1, bucketTimeSec, percent);
3509 }
3510 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3511 float percent = 100.0f *
3512 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3513 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3514 NUM_BUCKETS - 1, bucketTimeSec, percent);
3515}
3516
Dan Stozae77c7662016-05-13 11:37:28 -07003517void SurfaceFlinger::recordBufferingStats(const char* layerName,
3518 std::vector<OccupancyTracker::Segment>&& history) {
3519 Mutex::Autolock lock(mBufferingStatsMutex);
3520 auto& stats = mBufferingStats[layerName];
3521 for (const auto& segment : history) {
3522 if (!segment.usedThirdBuffer) {
3523 stats.twoBufferTime += segment.totalTime;
3524 }
3525 if (segment.occupancyAverage < 1.0f) {
3526 stats.doubleBufferedTime += segment.totalTime;
3527 } else if (segment.occupancyAverage < 2.0f) {
3528 stats.tripleBufferedTime += segment.totalTime;
3529 }
3530 ++stats.numSegments;
3531 stats.totalTime += segment.totalTime;
3532 }
3533}
3534
Brian Andersond6927fb2016-07-23 23:37:30 -07003535void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3536 result.appendFormat("Layer frame timestamps:\n");
3537
3538 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3539 const size_t count = currentLayers.size();
3540 for (size_t i=0 ; i<count ; i++) {
3541 currentLayers[i]->dumpFrameEvents(result);
3542 }
3543}
3544
Dan Stozae77c7662016-05-13 11:37:28 -07003545void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3546 result.append("Buffering stats:\n");
3547 result.append(" [Layer name] <Active time> <Two buffer> "
3548 "<Double buffered> <Triple buffered>\n");
3549 Mutex::Autolock lock(mBufferingStatsMutex);
3550 typedef std::tuple<std::string, float, float, float> BufferTuple;
3551 std::map<float, BufferTuple, std::greater<float>> sorted;
3552 for (const auto& statsPair : mBufferingStats) {
3553 const char* name = statsPair.first.c_str();
3554 const BufferingStats& stats = statsPair.second;
3555 if (stats.numSegments == 0) {
3556 continue;
3557 }
3558 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3559 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3560 stats.totalTime;
3561 float doubleBufferRatio = static_cast<float>(
3562 stats.doubleBufferedTime) / stats.totalTime;
3563 float tripleBufferRatio = static_cast<float>(
3564 stats.tripleBufferedTime) / stats.totalTime;
3565 sorted.insert({activeTime, {name, twoBufferRatio,
3566 doubleBufferRatio, tripleBufferRatio}});
3567 }
3568 for (const auto& sortedPair : sorted) {
3569 float activeTime = sortedPair.first;
3570 const BufferTuple& values = sortedPair.second;
3571 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3572 std::get<0>(values).c_str(), activeTime,
3573 std::get<1>(values), std::get<2>(values),
3574 std::get<3>(values));
3575 }
3576 result.append("\n");
3577}
3578
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003579void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3580 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3581
3582 // TODO: print out if wide-color mode is active or not
3583
3584 for (size_t d = 0; d < mDisplays.size(); d++) {
3585 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3586 int32_t hwcId = displayDevice->getHwcDisplayId();
3587 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3588 continue;
3589 }
3590
3591 result.appendFormat("Display %d color modes:\n", hwcId);
3592 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3593 for (auto&& mode : modes) {
3594 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3595 }
3596
3597 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3598 result.appendFormat(" Current color mode: %s (%d)\n",
3599 decodeColorMode(currentMode).c_str(), currentMode);
3600 }
3601 result.append("\n");
3602}
3603
Mathias Agopian74d211a2013-04-22 16:55:35 +02003604void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3605 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003606{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003607 bool colorize = false;
3608 if (index < args.size()
3609 && (args[index] == String16("--color"))) {
3610 colorize = true;
3611 index++;
3612 }
3613
3614 Colorizer colorizer(colorize);
3615
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003616 // figure out if we're stuck somewhere
3617 const nsecs_t now = systemTime();
3618 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3619 const nsecs_t inTransaction(mDebugInTransaction);
3620 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3621 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3622
3623 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003624 * Dump library configuration.
3625 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003626
3627 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003628 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003629 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003630 appendSfConfigString(result);
3631 appendUiConfigString(result);
3632 appendGuiConfigString(result);
3633 result.append("\n");
3634
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003635 result.append("\nWide-Color information:\n");
3636 dumpWideColorInfo(result);
3637
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003638 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003639 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003640 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003641 result.append(SyncFeatures::getInstance().toString());
3642 result.append("\n");
3643
Dan Stoza9e56aa02015-11-02 13:00:03 -08003644 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3645
Andy McFadden41d67d72014-04-25 16:58:34 -07003646 colorizer.bold(result);
3647 result.append("DispSync configuration: ");
3648 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003649 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003650 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003651 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003652 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003653 result.append("\n");
3654
Dan Stozab90cf072015-03-05 11:05:59 -08003655 // Dump static screen stats
3656 result.append("\n");
3657 dumpStaticScreenStats(result);
3658 result.append("\n");
3659
Dan Stozae77c7662016-05-13 11:37:28 -07003660 dumpBufferingStats(result);
3661
Andy McFadden4803b742012-09-24 19:07:20 -07003662 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003663 * Dump the visible layer list
3664 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003665 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003666 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003667 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003668 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003669 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003670 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003671
3672 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003673 * Dump Display state
3674 */
3675
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003676 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003677 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003678 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003679 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3680 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003681 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003682 }
3683
3684 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003685 * Dump SurfaceFlinger global state
3686 */
3687
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003688 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003689 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003690 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003691
Mathias Agopian888c8222012-08-04 21:10:38 -07003692 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003693 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003694
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003695 colorizer.bold(result);
3696 result.appendFormat("EGL implementation : %s\n",
3697 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3698 colorizer.reset(result);
3699 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003700 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003701
Mathias Agopian875d8e12013-06-07 15:35:48 -07003702 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003703
Mathias Agopian42977342012-08-05 00:40:46 -07003704 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003705 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3706 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003707 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003708 " last eglSwapBuffers() time: %f us\n"
3709 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003710 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003711 " refresh-rate : %f fps\n"
3712 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003713 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003714 " gpu_to_cpu_unsupported : %d\n"
3715 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716 mLastSwapBufferTime/1000.0,
3717 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003718 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003719 1e9 / activeConfig->getVsyncPeriod(),
3720 activeConfig->getDpiX(),
3721 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003722 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003723
Mathias Agopian74d211a2013-04-22 16:55:35 +02003724 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003725 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003726
Mathias Agopian74d211a2013-04-22 16:55:35 +02003727 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003728 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003729
3730 /*
3731 * VSYNC state
3732 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003733 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003734 result.append("\n");
3735
3736 /*
3737 * HWC layer minidump
3738 */
3739 for (size_t d = 0; d < mDisplays.size(); d++) {
3740 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3741 int32_t hwcId = displayDevice->getHwcDisplayId();
3742 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3743 continue;
3744 }
3745
3746 result.appendFormat("Display %d HWC layers:\n", hwcId);
3747 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003748 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003749 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003750 });
Dan Stozae22aec72016-08-01 13:20:59 -07003751 result.append("\n");
3752 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003753
3754 /*
3755 * Dump HWComposer state
3756 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003757 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003758 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003759 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003760 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003761 result.appendFormat(" h/w composer %s\n",
3762 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764
3765 /*
3766 * Dump gralloc state
3767 */
3768 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3769 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003770
3771 /*
3772 * Dump VrFlinger state if in use.
3773 */
3774 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3775 result.append("VrFlinger state:\n");
3776 result.append(mVrFlinger->Dump().c_str());
3777 result.append("\n");
3778 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003779}
3780
Mathias Agopian13127d82013-03-05 17:47:11 -08003781const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003782SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003783 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003784 wp<IBinder> dpy;
3785 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3786 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3787 dpy = mDisplays.keyAt(i);
3788 break;
3789 }
3790 }
3791 if (dpy == NULL) {
3792 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3793 // Just use the primary display so we have something to return
3794 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3795 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003796 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003797}
3798
Keun young Park63f165f2012-08-31 10:53:36 -07003799bool SurfaceFlinger::startDdmConnection()
3800{
3801 void* libddmconnection_dso =
3802 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3803 if (!libddmconnection_dso) {
3804 return false;
3805 }
3806 void (*DdmConnection_start)(const char* name);
3807 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003808 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003809 if (!DdmConnection_start) {
3810 dlclose(libddmconnection_dso);
3811 return false;
3812 }
3813 (*DdmConnection_start)(getServiceName());
3814 return true;
3815}
3816
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003817status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818 switch (code) {
3819 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003820 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003821 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003822 case CLEAR_ANIMATION_FRAME_STATS:
3823 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003824 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003825 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 {
3827 // codes that require permission check
3828 IPCThreadState* ipc = IPCThreadState::self();
3829 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003830 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003831 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003832 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003833 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003834 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003835 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003836 break;
3837 }
Robert Carr1db73f62016-12-21 12:58:51 -08003838 /*
3839 * Calling setTransactionState is safe, because you need to have been
3840 * granted a reference to Client* and Handle* to do anything with it.
3841 *
3842 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3843 */
3844 case SET_TRANSACTION_STATE:
3845 case CREATE_SCOPED_CONNECTION:
3846 {
3847 return OK;
3848 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003849 case CAPTURE_SCREEN:
3850 {
3851 // codes that require permission check
3852 IPCThreadState* ipc = IPCThreadState::self();
3853 const int pid = ipc->getCallingPid();
3854 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003855 if ((uid != AID_GRAPHICS) &&
3856 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003857 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003858 return PERMISSION_DENIED;
3859 }
3860 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003861 }
3862 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003863 return OK;
3864}
3865
3866status_t SurfaceFlinger::onTransact(
3867 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3868{
3869 status_t credentialCheck = CheckTransactCodeCredentials(code);
3870 if (credentialCheck != OK) {
3871 return credentialCheck;
3872 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003873
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003874 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3875 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003876 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003877 IPCThreadState* ipc = IPCThreadState::self();
3878 const int uid = ipc->getCallingUid();
3879 if (CC_UNLIKELY(uid != AID_SYSTEM
3880 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003881 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003882 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003883 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003884 return PERMISSION_DENIED;
3885 }
3886 int n;
3887 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003888 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003889 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003890 return NO_ERROR;
3891 case 1002: // SHOW_UPDATES
3892 n = data.readInt32();
3893 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003894 invalidateHwcGeometry();
3895 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003898 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003899 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003901 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003902 setTransactionFlags(
3903 eTransactionNeeded|
3904 eDisplayTransactionNeeded|
3905 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003906 return NO_ERROR;
3907 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003908 case 1006:{ // send empty update
3909 signalRefresh();
3910 return NO_ERROR;
3911 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003912 case 1008: // toggle use of hw composer
3913 n = data.readInt32();
3914 mDebugDisableHWC = n ? 1 : 0;
3915 invalidateHwcGeometry();
3916 repaintEverything();
3917 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003918 case 1009: // toggle use of transform hint
3919 n = data.readInt32();
3920 mDebugDisableTransformHint = n ? 1 : 0;
3921 invalidateHwcGeometry();
3922 repaintEverything();
3923 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003925 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 reply->writeInt32(0);
3927 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003928 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003929 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003930 return NO_ERROR;
3931 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003932 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003933 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003934 return NO_ERROR;
3935 }
3936 case 1014: {
3937 // daltonize
3938 n = data.readInt32();
3939 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003940 case 1:
3941 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3942 break;
3943 case 2:
3944 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3945 break;
3946 case 3:
3947 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3948 break;
3949 default:
3950 mDaltonizer.setType(ColorBlindnessType::None);
3951 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003952 }
3953 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003954 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003955 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003956 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003957 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003958 invalidateHwcGeometry();
3959 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003960 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003961 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003962 case 1015: {
3963 // apply a color matrix
3964 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003965 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003966 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003967 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003968 for (size_t j = 0; j < 4; j++) {
3969 mColorMatrix[i][j] = data.readFloat();
3970 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003971 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003972 } else {
3973 mColorMatrix = mat4();
3974 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003975
3976 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3977 // the division by w in the fragment shader
3978 float4 lastRow(transpose(mColorMatrix)[3]);
3979 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3980 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3981 }
3982
Alan Viverette9c5a3332013-09-12 20:04:35 -07003983 invalidateHwcGeometry();
3984 repaintEverything();
3985 return NO_ERROR;
3986 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003987 // This is an experimental interface
3988 // Needs to be shifted to proper binder interface when we productize
3989 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003990 n = data.readInt32();
3991 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003992 return NO_ERROR;
3993 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003994 case 1017: {
3995 n = data.readInt32();
3996 mForceFullDamage = static_cast<bool>(n);
3997 return NO_ERROR;
3998 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003999 case 1018: { // Modify Choreographer's phase offset
4000 n = data.readInt32();
4001 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4002 return NO_ERROR;
4003 }
4004 case 1019: { // Modify SurfaceFlinger's phase offset
4005 n = data.readInt32();
4006 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4007 return NO_ERROR;
4008 }
Irvel468051e2016-06-13 16:44:44 -07004009 case 1020: { // Layer updates interceptor
4010 n = data.readInt32();
4011 if (n) {
4012 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004013 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004014 }
4015 else{
4016 ALOGV("Interceptor disabled");
4017 mInterceptor.disable();
4018 }
4019 return NO_ERROR;
4020 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004021 case 1021: { // Disable HWC virtual displays
4022 n = data.readInt32();
4023 mUseHwcVirtualDisplays = !n;
4024 return NO_ERROR;
4025 }
Romain Guy0147a172017-06-01 13:53:56 -07004026 case 1022: { // Set saturation boost
4027 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4028
4029 invalidateHwcGeometry();
4030 repaintEverything();
4031 return NO_ERROR;
4032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 }
4034 }
4035 return err;
4036}
4037
Mathias Agopian53331da2011-08-22 21:44:41 -07004038void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004039 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004040 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004041}
4042
Mathias Agopian59119e62010-10-11 12:37:43 -07004043// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004044// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004045// ---------------------------------------------------------------------------
4046
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004047/* The code below is here to handle b/8734824
4048 *
4049 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07004050 * from the surfaceflinger thread to the calling binder thread, where they
4051 * are executed. This allows the calling thread in the calling process to be
4052 * reused and not depend on having "enough" binder threads to handle the
4053 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004054 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004055class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07004056 /* Parts of GraphicProducerWrapper are run on two different threads,
4057 * communicating by sending messages via Looper but also by shared member
4058 * data. Coherence maintenance is subtle and in places implicit (ugh).
4059 *
4060 * Don't rely on Looper's sendMessage/handleMessage providing
4061 * release/acquire semantics for any data not actually in the Message.
4062 * Data going from surfaceflinger to binder threads needs to be
4063 * synchronized explicitly.
4064 *
4065 * Barrier open/wait do provide release/acquire semantics. This provides
4066 * implicit synchronization for data coming back from binder to
4067 * surfaceflinger threads.
4068 */
4069
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004070 sp<IGraphicBufferProducer> impl;
4071 sp<Looper> looper;
4072 status_t result;
4073 bool exitPending;
4074 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07004075 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004076 uint32_t code;
4077 Parcel const* data;
4078 Parcel* reply;
4079
4080 enum {
4081 MSG_API_CALL,
4082 MSG_EXIT
4083 };
4084
4085 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004086 * Called on surfaceflinger thread. This is called by our "fake"
4087 * BpGraphicBufferProducer. We package the data and reply Parcel and
4088 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004089 */
4090 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08004091 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004092 this->code = code;
4093 this->data = &data;
4094 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004095 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07004096 // if we've exited, we run the message synchronously right here.
4097 // note (JH): as far as I can tell from looking at the code, this
4098 // never actually happens. if it does, i'm not sure if it happens
4099 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004100 handleMessage(Message(MSG_API_CALL));
4101 } else {
4102 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004103 // Prevent stores to this->{code, data, reply} from being
4104 // reordered later than the construction of Message.
4105 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004106 looper->sendMessage(this, Message(MSG_API_CALL));
4107 barrier.wait();
4108 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004109 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004110 }
4111
4112 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004113 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004114 * call the real BpGraphicBufferProducer.
4115 */
4116 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004117 int what = message.what;
4118 // Prevent reads below from happening before the read from Message
4119 atomic_thread_fence(memory_order_acquire);
4120 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004121 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004122 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004123 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004124 exitRequested = true;
4125 }
4126 }
4127
4128public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004129 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004130 : impl(impl),
4131 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004132 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004133 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004134 exitRequested(false),
4135 code(0),
4136 data(NULL),
4137 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004138 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004139
Jesse Hallb154c422014-07-13 12:47:02 -07004140 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004141 status_t waitForResponse() {
4142 do {
4143 looper->pollOnce(-1);
4144 } while (!exitRequested);
4145 return result;
4146 }
4147
Jesse Hallb154c422014-07-13 12:47:02 -07004148 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004149 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004150 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004151 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004152 // Ensure this->result is visible to the binder thread before it
4153 // handles the message.
4154 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004155 looper->sendMessage(this, Message(MSG_EXIT));
4156 }
4157};
4158
4159
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004160status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4161 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004162 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004163 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004164 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004165
4166 if (CC_UNLIKELY(display == 0))
4167 return BAD_VALUE;
4168
4169 if (CC_UNLIKELY(producer == 0))
4170 return BAD_VALUE;
4171
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004172 // if we have secure windows on this display, never allow the screen capture
4173 // unless the producer interface is local (i.e.: we can take a screenshot for
4174 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004175 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004176
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004177 // Convert to surfaceflinger's internal rotation type.
4178 Transform::orientation_flags rotationFlags;
4179 switch (rotation) {
4180 case ISurfaceComposer::eRotateNone:
4181 rotationFlags = Transform::ROT_0;
4182 break;
4183 case ISurfaceComposer::eRotate90:
4184 rotationFlags = Transform::ROT_90;
4185 break;
4186 case ISurfaceComposer::eRotate180:
4187 rotationFlags = Transform::ROT_180;
4188 break;
4189 case ISurfaceComposer::eRotate270:
4190 rotationFlags = Transform::ROT_270;
4191 break;
4192 default:
4193 rotationFlags = Transform::ROT_0;
4194 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4195 break;
4196 }
4197
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004198 class MessageCaptureScreen : public MessageBase {
4199 SurfaceFlinger* flinger;
4200 sp<IBinder> display;
4201 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004202 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004203 uint32_t reqWidth, reqHeight;
4204 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004205 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004206 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004207 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004208 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004209 public:
4210 MessageCaptureScreen(SurfaceFlinger* flinger,
4211 const sp<IBinder>& display,
4212 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004213 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004214 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004215 bool useIdentityTransform,
4216 Transform::orientation_flags rotation,
4217 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004218 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004219 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004220 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004221 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004222 rotation(rotation), result(PERMISSION_DENIED),
4223 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004224 {
4225 }
4226 status_t getResult() const {
4227 return result;
4228 }
4229 virtual bool handler() {
4230 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004231 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004232 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004233 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004234 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004235 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004236 return true;
4237 }
4238 };
4239
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004240 // this creates a "fake" BBinder which will serve as a "fake" remote
4241 // binder to receive the marshaled calls and forward them to the
4242 // real remote (a BpGraphicBufferProducer)
4243 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4244
4245 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4246 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004247 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004248 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004249 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004250 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004251
4252 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004253 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004254 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004255 }
4256 return res;
4257}
4258
Mathias Agopian180f10d2013-04-10 22:55:41 -07004259
4260void SurfaceFlinger::renderScreenImplLocked(
4261 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004262 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004263 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004264 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004265{
4266 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004267 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004268
4269 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004270 const int32_t hw_w = hw->getWidth();
4271 const int32_t hw_h = hw->getHeight();
4272 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004273 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004274
Dan Stozac1879002014-05-22 15:59:05 -07004275 // if a default or invalid sourceCrop is passed in, set reasonable values
4276 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4277 !sourceCrop.isValid()) {
4278 sourceCrop.setLeftTop(Point(0, 0));
4279 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4280 }
4281
4282 // ensure that sourceCrop is inside screen
4283 if (sourceCrop.left < 0) {
4284 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4285 }
Dan Stozabe31f442014-06-11 11:20:54 -07004286 if (sourceCrop.right > hw_w) {
4287 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004288 }
4289 if (sourceCrop.top < 0) {
4290 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4291 }
Dan Stozabe31f442014-06-11 11:20:54 -07004292 if (sourceCrop.bottom > hw_h) {
4293 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004294 }
4295
Romain Guy88d37dd2017-05-26 17:57:05 -07004296#ifdef USE_HWC2
4297 engine.setWideColor(hw->getWideColorSupport());
4298 engine.setColorMode(hw->getActiveColorMode());
4299#endif
4300
Mathias Agopian180f10d2013-04-10 22:55:41 -07004301 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004302 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004303
4304 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004305 engine.setViewportAndProjection(
4306 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004307 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004308
4309 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004310 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004311
Robert Carr1f0a16a2016-10-24 16:27:39 -07004312 // We loop through the first level of layers without traversing,
4313 // as we need to interpret min/max layer Z in the top level Z space.
4314 for (const auto& layer : mDrawingState.layersSortedByZ) {
4315 if (layer->getLayerStack() != hw->getLayerStack()) {
4316 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004317 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004318 const Layer::State& state(layer->getDrawingState());
4319 if (state.z < minLayerZ || state.z > maxLayerZ) {
4320 continue;
4321 }
Dan Stoza412903f2017-04-27 13:42:17 -07004322 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004323 if (!layer->isVisible()) {
4324 return;
4325 }
4326 if (filtering) layer->setFiltering(true);
4327 layer->draw(hw, useIdentityTransform);
4328 if (filtering) layer->setFiltering(false);
4329 });
4330 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004331
Mathias Agopian931bda12013-08-28 18:11:46 -07004332 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004333}
4334
4335
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004336status_t SurfaceFlinger::captureScreenImplLocked(
4337 const sp<const DisplayDevice>& hw,
4338 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004339 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004340 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004341 bool useIdentityTransform, Transform::orientation_flags rotation,
4342 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004343{
4344 ATRACE_CALL();
4345
Mathias Agopian180f10d2013-04-10 22:55:41 -07004346 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004347 uint32_t hw_w = hw->getWidth();
4348 uint32_t hw_h = hw->getHeight();
4349
4350 if (rotation & Transform::ROT_90) {
4351 std::swap(hw_w, hw_h);
4352 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004353
Mathias Agopian180f10d2013-04-10 22:55:41 -07004354 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4355 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4356 reqWidth, reqHeight, hw_w, hw_h);
4357 return BAD_VALUE;
4358 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004359
Mathias Agopian180f10d2013-04-10 22:55:41 -07004360 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4361 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4362
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004363 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004364 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004365 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004366 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4367 (state.z < minLayerZ || state.z > maxLayerZ)) {
4368 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004369 }
Dan Stoza412903f2017-04-27 13:42:17 -07004370 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004371 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4372 layer->isSecure());
4373 });
4374 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004375
4376 if (!isLocalScreenshot && secureLayerIsVisible) {
4377 ALOGW("FB is protected: PERMISSION_DENIED");
4378 return PERMISSION_DENIED;
4379 }
4380
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004381 // create a surface (because we're a producer, and we need to
4382 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004383 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004384
4385 // Put the screenshot Surface into async mode so that
4386 // Layer::headFenceHasSignaled will always return true and we'll latch the
4387 // first buffer regardless of whether or not its acquire fence has
4388 // signaled. This is needed to avoid a race condition in the rotation
4389 // animation. See b/30209608
4390 sur->setAsyncMode(true);
4391
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004392 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004393
Michael Lentine5a16a622015-05-21 13:48:24 -07004394 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4395 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004396 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4397 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004398
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004399 int err = 0;
4400 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004401 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004402 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4403 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004404
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004405 if (err == NO_ERROR) {
4406 ANativeWindowBuffer* buffer;
4407 /* TODO: Once we have the sync framework everywhere this can use
4408 * server-side waits on the fence that dequeueBuffer returns.
4409 */
4410 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4411 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004412 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004413 // create an EGLImage from the buffer so we can later
4414 // turn it into a texture
4415 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4416 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4417 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004418 // this binds the given EGLImage as a framebuffer for the
4419 // duration of this scope.
4420 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4421 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004422 // this will in fact render into our dequeued buffer
4423 // via an FBO, which means we didn't have to create
4424 // an EGLSurface and therefore we're not
4425 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004426 renderScreenImplLocked(
4427 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4428 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004429
Romain Guy8ec6ff22017-05-31 19:22:30 -07004430#ifdef USE_HWC2
4431 if (hasWideColorDisplay) {
4432 native_window_set_buffers_data_space(window,
4433 getRenderEngine().usesWideColor() ?
4434 HAL_DATASPACE_DISPLAY_P3 : HAL_DATASPACE_V0_SRGB);
4435 }
4436#endif
4437
Riley Andrews86639902014-08-15 12:27:24 -07004438 // Attempt to create a sync khr object that can produce a sync point. If that
4439 // isn't available, create a non-dupable sync object in the fallback path and
4440 // wait on it directly.
4441 EGLSyncKHR sync;
4442 if (!DEBUG_SCREENSHOTS) {
4443 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004444 // native fence fd will not be populated until flush() is done.
4445 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004446 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004447 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004448 }
Riley Andrews86639902014-08-15 12:27:24 -07004449 if (sync != EGL_NO_SYNC_KHR) {
4450 // get the sync fd
4451 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4452 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4453 ALOGW("captureScreen: failed to dup sync khr object");
4454 syncFd = -1;
4455 }
4456 eglDestroySyncKHR(mEGLDisplay, sync);
4457 } else {
4458 // fallback path
4459 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4460 if (sync != EGL_NO_SYNC_KHR) {
4461 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4462 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4463 EGLint eglErr = eglGetError();
4464 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4465 ALOGW("captureScreen: fence wait timed out");
4466 } else {
4467 ALOGW_IF(eglErr != EGL_SUCCESS,
4468 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4469 }
4470 eglDestroySyncKHR(mEGLDisplay, sync);
4471 } else {
4472 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4473 }
4474 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004475 if (DEBUG_SCREENSHOTS) {
4476 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4477 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4478 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4479 hw, minLayerZ, maxLayerZ);
4480 delete [] pixels;
4481 }
4482
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004483 } else {
4484 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4485 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004486 window->cancelBuffer(window, buffer, syncFd);
4487 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004488 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004489 // destroy our image
4490 eglDestroyImageKHR(mEGLDisplay, image);
4491 } else {
4492 result = BAD_VALUE;
4493 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004494 if (buffer) {
4495 // queueBuffer takes ownership of syncFd
4496 result = window->queueBuffer(window, buffer, syncFd);
4497 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004498 }
4499 } else {
4500 result = BAD_VALUE;
4501 }
4502 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4503 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004504
Mathias Agopian74c40c02010-09-29 13:02:36 -07004505 return result;
4506}
4507
Mathias Agopiand5556842013-09-19 17:08:37 -07004508void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004509 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004510 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004511 for (size_t y=0 ; y<h ; y++) {
4512 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4513 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004514 if (p[x] != 0xFF000000) return;
4515 }
4516 }
4517 ALOGE("*** we just took a black screenshot ***\n"
4518 "requested minz=%d, maxz=%d, layerStack=%d",
4519 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004520
Robert Carr2047fae2016-11-28 14:09:09 -08004521 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004522 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004523 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004524 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4525 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004526 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004527 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4528 layer->isVisible() ? '+' : '-',
4529 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004530 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004531 i++;
4532 });
4533 }
4534 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004535 }
4536}
4537
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004538// ---------------------------------------------------------------------------
4539
Dan Stoza412903f2017-04-27 13:42:17 -07004540void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4541 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004542}
4543
Dan Stoza412903f2017-04-27 13:42:17 -07004544void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4545 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004546}
4547
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004549
4550
4551#if defined(__gl_h_)
4552#error "don't include gl/gl.h in this file"
4553#endif
4554
4555#if defined(__gl2_h_)
4556#error "don't include gl2/gl2.h in this file"
4557#endif