blob: 1bc9cec9322fa9784695561a2de827a1892871f8 [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");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228}
229
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800230void SurfaceFlinger::onFirstRef()
231{
232 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800233}
234
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235SurfaceFlinger::~SurfaceFlinger()
236{
Mathias Agopiana4912602012-07-12 14:25:33 -0700237 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
238 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
239 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800240}
241
Dan Stozac7014012014-02-14 15:03:43 -0800242void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800243{
244 // the window manager died on us. prepare its eulogy.
245
Andy McFadden13a082e2012-08-24 10:16:42 -0700246 // restore initial conditions (default device unblank, etc)
247 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800248
249 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700250 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800251}
252
Robert Carr1db73f62016-12-21 12:58:51 -0800253static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700254 status_t err = client->initCheck();
255 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800256 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 }
Robert Carr1db73f62016-12-21 12:58:51 -0800258 return nullptr;
259}
260
261sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
262 return initClient(new Client(this));
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
266 const sp<IGraphicBufferProducer>& gbp) {
267 if (authenticateSurfaceTexture(gbp) == false) {
268 return nullptr;
269 }
270 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
271 if (layer == nullptr) {
272 return nullptr;
273 }
274
275 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276}
277
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700278sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
279 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700280{
281 class DisplayToken : public BBinder {
282 sp<SurfaceFlinger> flinger;
283 virtual ~DisplayToken() {
284 // no more references, this display must be terminated
285 Mutex::Autolock _l(flinger->mStateLock);
286 flinger->mCurrentState.displays.removeItem(this);
287 flinger->setTransactionFlags(eDisplayTransactionNeeded);
288 }
289 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700290 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700291 : flinger(flinger) {
292 }
293 };
294
295 sp<BBinder> token = new DisplayToken(this);
296
297 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700298 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700299 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700301 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302 return token;
303}
304
Jesse Hall6c913be2013-08-08 12:15:49 -0700305void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
306 Mutex::Autolock _l(mStateLock);
307
308 ssize_t idx = mCurrentState.displays.indexOfKey(display);
309 if (idx < 0) {
310 ALOGW("destroyDisplay: invalid display token");
311 return;
312 }
313
314 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
315 if (!info.isVirtualDisplay()) {
316 ALOGE("destroyDisplay called for non-virtual display");
317 return;
318 }
Irvelffc9efc2016-07-27 15:16:37 -0700319 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700320 mCurrentState.displays.removeItemsAt(idx);
321 setTransactionFlags(eDisplayTransactionNeeded);
322}
323
Jesse Hall692c7232012-11-08 15:41:56 -0800324void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800325 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800326 ALOGW_IF(mBuiltinDisplays[type],
327 "Overwriting display token for display type %d", type);
328 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800329 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700330 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800331 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700332 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800333}
334
Mathias Agopiane57f2922012-08-09 16:29:12 -0700335sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700336 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700337 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
338 return NULL;
339 }
Jesse Hall692c7232012-11-08 15:41:56 -0800340 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341}
342
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800343void SurfaceFlinger::bootFinished()
344{
Wei Wangb254fa32017-01-31 17:43:23 -0800345 if (mStartBootAnimThread->join() != NO_ERROR) {
346 ALOGE("Join StartBootAnimThread failed!");
347 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 const nsecs_t now = systemTime();
349 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000350 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700351 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700352
353 // wait patiently for the window manager death
354 const String16 name("window");
355 sp<IBinder> window(defaultServiceManager()->getService(name));
356 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700357 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700358 }
359
Steven Thomas050b2c82017-03-06 11:45:16 -0800360 if (mVrFlinger) {
361 mVrFlinger->OnBootFinished();
362 }
363
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700364 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700365 // formerly we would just kill the process, but we now ask it to exit so it
366 // can choose where to stop the animation.
367 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700368
369 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
370 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
371 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372}
373
Mathias Agopian3f844832013-08-07 21:24:32 -0700374void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700375 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700376 RenderEngine& engine;
377 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700379 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
380 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700381 }
382 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700383 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700384 return true;
385 }
386 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700388}
389
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700390class DispSyncSource : public VSyncSource, private DispSync::Callback {
391public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700392 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000393 const char* name) :
394 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700395 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700396 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000397 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
398 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700399 mDispSync(dispSync),
400 mCallbackMutex(),
401 mCallback(),
402 mVsyncMutex(),
403 mPhaseOffset(phaseOffset),
404 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700405
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700406 virtual ~DispSyncSource() {}
407
408 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700409 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000411 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error registering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700417 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700418 } else {
419 status_t err = mDispSync->removeEventListener(
420 static_cast<DispSync::Callback*>(this));
421 if (err != NO_ERROR) {
422 ALOGE("error unregistering vsync callback: %s (%d)",
423 strerror(-err), err);
424 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700425 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700427 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700428 }
429
430 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700431 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 mCallback = callback;
433 }
434
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 virtual void setPhaseOffset(nsecs_t phaseOffset) {
436 Mutex::Autolock lock(mVsyncMutex);
437
438 // Normalize phaseOffset to [0, period)
439 auto period = mDispSync->getPeriod();
440 phaseOffset %= period;
441 if (phaseOffset < 0) {
442 // If we're here, then phaseOffset is in (-period, 0). After this
443 // operation, it will be in (0, period)
444 phaseOffset += period;
445 }
446 mPhaseOffset = phaseOffset;
447
448 // If we're not enabled, we don't need to mess with the listeners
449 if (!mEnabled) {
450 return;
451 }
452
453 // Remove the listener with the old offset
454 status_t err = mDispSync->removeEventListener(
455 static_cast<DispSync::Callback*>(this));
456 if (err != NO_ERROR) {
457 ALOGE("error unregistering vsync callback: %s (%d)",
458 strerror(-err), err);
459 }
460
461 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000462 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 static_cast<DispSync::Callback*>(this));
464 if (err != NO_ERROR) {
465 ALOGE("error registering vsync callback: %s (%d)",
466 strerror(-err), err);
467 }
468 }
469
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700470private:
471 virtual void onDispSyncEvent(nsecs_t when) {
472 sp<VSyncSource::Callback> callback;
473 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700474 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700475 callback = mCallback;
476
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700477 if (mTraceVsync) {
478 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700479 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700480 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700481 }
482
483 if (callback != NULL) {
484 callback->onVSyncEvent(when);
485 }
486 }
487
Tim Murray4a4e4a22016-04-19 16:29:23 +0000488 const char* const mName;
489
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700490 int mValue;
491
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700492 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700493 const String8 mVsyncOnLabel;
494 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700497
498 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700499 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500
501 Mutex mVsyncMutex; // Protects the following
502 nsecs_t mPhaseOffset;
503 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700504};
505
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700506class InjectVSyncSource : public VSyncSource {
507public:
508 InjectVSyncSource() {}
509
510 virtual ~InjectVSyncSource() {}
511
512 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
513 std::lock_guard<std::mutex> lock(mCallbackMutex);
514 mCallback = callback;
515 }
516
517 virtual void onInjectSyncEvent(nsecs_t when) {
518 std::lock_guard<std::mutex> lock(mCallbackMutex);
519 mCallback->onVSyncEvent(when);
520 }
521
522 virtual void setVSyncEnabled(bool) {}
523 virtual void setPhaseOffset(nsecs_t) {}
524
525private:
526 std::mutex mCallbackMutex; // Protects the following
527 sp<VSyncSource::Callback> mCallback;
528};
529
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700531 ALOGI( "SurfaceFlinger's main thread ready to run. "
532 "Initializing graphics H/W...");
533
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900534 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
535
Dan Stoza9e56aa02015-11-02 13:00:03 -0800536 { // Autolock scope
537 Mutex::Autolock _l(mStateLock);
538
539 // initialize EGL for the default display
540 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
541 eglInitialize(mEGLDisplay, NULL, NULL);
542
543 // start the EventThread
544 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
545 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700546 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800547 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
548 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700549 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800550 mEventQueue.setEventThread(mSFEventThread);
551
Tim Murray22752852017-05-04 13:38:49 -0700552 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700553 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700554 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700555 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
556 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
557 }
Tim Murray22752852017-05-04 13:38:49 -0700558 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
559 ALOGE("Couldn't set SCHED_FIFO for EventThread");
560 }
Tim Murray41a38532016-06-22 12:42:10 -0700561
Dan Stoza9e56aa02015-11-02 13:00:03 -0800562 // Get a RenderEngine for the given display / config (can't fail)
563 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700564 HAL_PIXEL_FORMAT_RGBA_8888,
565 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800566 }
567
568 // Drop the state lock while we initialize the hardware composer. We drop
569 // the lock because on creation, it will call back into SurfaceFlinger to
570 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800571 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
572 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800573 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800574 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
576
Jesse Hall692c7232012-11-08 15:41:56 -0800577 Mutex::Autolock _l(mStateLock);
578
Ian Elliott5c34de22017-04-10 14:42:30 -0600579 // Inform native graphics APIs whether the present timestamp is supported:
580 if (getHwComposer().hasCapability(
581 HWC2::Capability::PresentFenceIsNotReliable)) {
582 property_set(kTimestampProperty, "0");
583 } else {
584 property_set(kTimestampProperty, "1");
585 }
586
Steven Thomas050b2c82017-03-06 11:45:16 -0800587 if (useVrFlinger) {
588 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700589 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800590 mVrFlingerRequestsDisplay = requestDisplay;
591 signalTransaction();
592 };
593 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
594 vrFlingerRequestDisplayCallback);
595 if (!mVrFlinger) {
596 ALOGE("Failed to start vrflinger");
597 }
598 }
599
Mathias Agopian875d8e12013-06-07 15:35:48 -0700600 // retrieve the EGL context that was selected/created
601 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700602
Mathias Agopianda27af92012-09-13 18:17:13 -0700603 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
604 "couldn't create EGLContext");
605
Dan Stoza9e56aa02015-11-02 13:00:03 -0800606 // make the GLContext current so that we can create textures when creating
607 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700608 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700609
Jamie Gennisd1700752013-10-14 12:22:52 -0700610 mEventControlThread = new EventControlThread(this);
611 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
612
Mathias Agopian92a979a2012-08-02 18:32:23 -0700613 // initialize our drawing state
614 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700615
Andy McFadden13a082e2012-08-24 10:16:42 -0700616 // set initial conditions (e.g. unblank default device)
617 initializeDisplays();
618
Dan Stoza4e637772016-07-28 13:31:51 -0700619 mRenderEngine->primeCache();
620
Wei Wangb254fa32017-01-31 17:43:23 -0800621 mStartBootAnimThread = new StartBootAnimThread();
622 if (mStartBootAnimThread->Start() != NO_ERROR) {
623 ALOGE("Run StartBootAnimThread failed!");
624 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800625
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700627}
628
Mathias Agopiana67e4182012-06-19 17:26:12 -0700629void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800630 // Start boot animation service by setting a property mailbox
631 // if property setting thread is already running, Start() will be just a NOP
632 mStartBootAnimThread->Start();
633 // Wait until property was set
634 if (mStartBootAnimThread->join() != NO_ERROR) {
635 ALOGE("Join StartBootAnimThread failed!");
636 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700637}
638
Mathias Agopian875d8e12013-06-07 15:35:48 -0700639size_t SurfaceFlinger::getMaxTextureSize() const {
640 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700641}
642
Mathias Agopian875d8e12013-06-07 15:35:48 -0700643size_t SurfaceFlinger::getMaxViewportDims() const {
644 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700645}
646
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800647// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800648
Jamie Gennis582270d2011-08-17 18:19:00 -0700649bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800650 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800651 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800652 return authenticateSurfaceTextureLocked(bufferProducer);
653}
654
655bool SurfaceFlinger::authenticateSurfaceTextureLocked(
656 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800657 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700658 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800659}
660
Brian Anderson6b376712017-04-04 10:51:39 -0700661status_t SurfaceFlinger::getSupportedFrameTimestamps(
662 std::vector<FrameEvent>* outSupported) const {
663 *outSupported = {
664 FrameEvent::REQUESTED_PRESENT,
665 FrameEvent::ACQUIRE,
666 FrameEvent::LATCH,
667 FrameEvent::FIRST_REFRESH_START,
668 FrameEvent::LAST_REFRESH_START,
669 FrameEvent::GPU_COMPOSITION_DONE,
670 FrameEvent::DEQUEUE_READY,
671 FrameEvent::RELEASE,
672 };
673 if (!getHwComposer().hasCapability(
674 HWC2::Capability::PresentFenceIsNotReliable)) {
675 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
676 }
677 return NO_ERROR;
678}
679
Dan Stoza7f7da322014-05-02 15:26:25 -0700680status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
681 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700682 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700683 return BAD_VALUE;
684 }
685
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500686 if (!display.get())
687 return NAME_NOT_FOUND;
688
Jesse Hall692c7232012-11-08 15:41:56 -0800689 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700690 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800691 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700692 type = i;
693 break;
694 }
695 }
696
697 if (type < 0) {
698 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700699 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700700
Mathias Agopian8b736f12012-08-13 17:54:26 -0700701 // TODO: Not sure if display density should handled by SF any longer
702 class Density {
703 static int getDensityFromProperty(char const* propName) {
704 char property[PROPERTY_VALUE_MAX];
705 int density = 0;
706 if (property_get(propName, property, NULL) > 0) {
707 density = atoi(property);
708 }
709 return density;
710 }
711 public:
712 static int getEmuDensity() {
713 return getDensityFromProperty("qemu.sf.lcd_density"); }
714 static int getBuildDensity() {
715 return getDensityFromProperty("ro.sf.lcd_density"); }
716 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700717
Dan Stoza7f7da322014-05-02 15:26:25 -0700718 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700719
Dan Stoza9e56aa02015-11-02 13:00:03 -0800720 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700721 DisplayInfo info = DisplayInfo();
722
Dan Stoza9e56aa02015-11-02 13:00:03 -0800723 float xdpi = hwConfig->getDpiX();
724 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700725
726 if (type == DisplayDevice::DISPLAY_PRIMARY) {
727 // The density of the device is provided by a build property
728 float density = Density::getBuildDensity() / 160.0f;
729 if (density == 0) {
730 // the build doesn't provide a density -- this is wrong!
731 // use xdpi instead
732 ALOGE("ro.sf.lcd_density must be defined as a build property");
733 density = xdpi / 160.0f;
734 }
735 if (Density::getEmuDensity()) {
736 // if "qemu.sf.lcd_density" is specified, it overrides everything
737 xdpi = ydpi = density = Density::getEmuDensity();
738 density /= 160.0f;
739 }
740 info.density = density;
741
742 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000743 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
744 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700745 } else {
746 // TODO: where should this value come from?
747 static const int TV_DENSITY = 213;
748 info.density = TV_DENSITY / 160.0f;
749 info.orientation = 0;
750 }
751
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 info.w = hwConfig->getWidth();
753 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700754 info.xdpi = xdpi;
755 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900757 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800758
Andy McFadden91b2ca82014-06-13 14:04:23 -0700759 // This is how far in advance a buffer must be queued for
760 // presentation at a given time. If you want a buffer to appear
761 // on the screen at time N, you must submit the buffer before
762 // (N - presentationDeadline).
763 //
764 // Normally it's one full refresh period (to give SF a chance to
765 // latch the buffer), but this can be reduced by configuring a
766 // DispSync offset. Any additional delays introduced by the hardware
767 // composer or panel must be accounted for here.
768 //
769 // We add an additional 1ms to allow for processing time and
770 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800771 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800772 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700773
774 // All non-virtual displays are currently considered secure.
775 info.secure = true;
776
Michael Wright28f24d02016-07-12 13:30:53 -0700777 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700778 }
779
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 return NO_ERROR;
781}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700782
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800783status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700784 DisplayStatInfo* stats) {
785 if (stats == NULL) {
786 return BAD_VALUE;
787 }
788
789 // FIXME for now we always return stats for the primary display
790 memset(stats, 0, sizeof(*stats));
791 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
792 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
793 return NO_ERROR;
794}
795
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700796int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800797 if (display == NULL) {
798 ALOGE("%s : display is NULL", __func__);
799 return BAD_VALUE;
800 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700801
802 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700803 if (device != NULL) {
804 return device->getActiveConfig();
805 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700806
Dan Stoza24a42e92015-03-09 10:04:11 -0700807 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700808}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700809
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700810void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
811 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
812 this);
813 int32_t type = hw->getDisplayType();
814 int currentMode = hw->getActiveConfig();
815
816 if (mode == currentMode) {
817 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
818 return;
819 }
820
821 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
822 ALOGW("Trying to set config for virtual display");
823 return;
824 }
825
826 hw->setActiveConfig(mode);
827 getHwComposer().setActiveConfig(type, mode);
828}
829
830status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
831 class MessageSetActiveConfig: public MessageBase {
832 SurfaceFlinger& mFlinger;
833 sp<IBinder> mDisplay;
834 int mMode;
835 public:
836 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
837 int mode) :
838 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
839 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700840 Vector<DisplayInfo> configs;
841 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700842 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700843 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700844 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700845 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700846 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700847 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
848 if (hw == NULL) {
849 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700850 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700851 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
852 ALOGW("Attempt to set active config = %d for virtual display",
853 mMode);
854 } else {
855 mFlinger.setActiveConfigInternal(hw, mMode);
856 }
857 return true;
858 }
859 };
860 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
861 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700862 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700863}
Michael Wright28f24d02016-07-12 13:30:53 -0700864status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
865 Vector<android_color_mode_t>* outColorModes) {
866 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
867 return BAD_VALUE;
868 }
869
870 if (!display.get()) {
871 return NAME_NOT_FOUND;
872 }
873
874 int32_t type = NAME_NOT_FOUND;
875 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
876 if (display == mBuiltinDisplays[i]) {
877 type = i;
878 break;
879 }
880 }
881
882 if (type < 0) {
883 return type;
884 }
885
886 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
887 outColorModes->clear();
888 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
889
890 return NO_ERROR;
891}
892
893android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700894 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700895 if (device != nullptr) {
896 return device->getActiveColorMode();
897 }
898 return static_cast<android_color_mode_t>(BAD_VALUE);
899}
900
901void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
902 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700903 int32_t type = hw->getDisplayType();
904 android_color_mode_t currentMode = hw->getActiveColorMode();
905
906 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700907 return;
908 }
909
910 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
911 ALOGW("Trying to set config for virtual display");
912 return;
913 }
914
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600915 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
916 hw->getDisplayType());
917
Michael Wright28f24d02016-07-12 13:30:53 -0700918 hw->setActiveColorMode(mode);
919 getHwComposer().setActiveColorMode(type, mode);
920}
921
922
923status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
924 android_color_mode_t colorMode) {
925 class MessageSetActiveColorMode: public MessageBase {
926 SurfaceFlinger& mFlinger;
927 sp<IBinder> mDisplay;
928 android_color_mode_t mMode;
929 public:
930 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
931 android_color_mode_t mode) :
932 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
933 virtual bool handler() {
934 Vector<android_color_mode_t> modes;
935 mFlinger.getDisplayColorModes(mDisplay, &modes);
936 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
937 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600938 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
939 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700940 return true;
941 }
942 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
943 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600944 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
945 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700946 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600947 ALOGW("Attempt to set active color mode %s %d for virtual display",
948 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700949 } else {
950 mFlinger.setActiveColorModeInternal(hw, mMode);
951 }
952 return true;
953 }
954 };
955 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
956 postMessageSync(msg);
957 return NO_ERROR;
958}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700959
Svetoslavd85084b2014-03-20 10:28:31 -0700960status_t SurfaceFlinger::clearAnimationFrameStats() {
961 Mutex::Autolock _l(mStateLock);
962 mAnimFrameTracker.clearStats();
963 return NO_ERROR;
964}
965
966status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
967 Mutex::Autolock _l(mStateLock);
968 mAnimFrameTracker.getStats(outStats);
969 return NO_ERROR;
970}
971
Dan Stozac4f471e2016-03-24 09:31:08 -0700972status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
973 HdrCapabilities* outCapabilities) const {
974 Mutex::Autolock _l(mStateLock);
975
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700976 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700977 if (displayDevice == nullptr) {
978 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
979 return BAD_VALUE;
980 }
981
982 std::unique_ptr<HdrCapabilities> capabilities =
983 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
984 if (capabilities) {
985 std::swap(*outCapabilities, *capabilities);
986 } else {
987 return BAD_VALUE;
988 }
989
990 return NO_ERROR;
991}
992
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700993status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
994 if (enable == mInjectVSyncs) {
995 return NO_ERROR;
996 }
997
998 if (enable) {
999 mInjectVSyncs = enable;
1000 ALOGV("VSync Injections enabled");
1001 if (mVSyncInjector.get() == nullptr) {
1002 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001003 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001004 }
1005 mEventQueue.setEventThread(mInjectorEventThread);
1006 } else {
1007 mInjectVSyncs = enable;
1008 ALOGV("VSync Injections disabled");
1009 mEventQueue.setEventThread(mSFEventThread);
1010 mVSyncInjector.clear();
1011 }
1012 return NO_ERROR;
1013}
1014
1015status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1016 if (!mInjectVSyncs) {
1017 ALOGE("VSync Injections not enabled");
1018 return BAD_VALUE;
1019 }
1020 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1021 ALOGV("Injecting VSync inside SurfaceFlinger");
1022 mVSyncInjector->onInjectSyncEvent(when);
1023 }
1024 return NO_ERROR;
1025}
1026
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001027// ----------------------------------------------------------------------------
1028
1029sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -08001030 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -07001031}
1032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001033// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001034
1035void SurfaceFlinger::waitForEvent() {
1036 mEventQueue.waitMessage();
1037}
1038
1039void SurfaceFlinger::signalTransaction() {
1040 mEventQueue.invalidate();
1041}
1042
1043void SurfaceFlinger::signalLayerUpdate() {
1044 mEventQueue.invalidate();
1045}
1046
1047void SurfaceFlinger::signalRefresh() {
1048 mEventQueue.refresh();
1049}
1050
1051status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001052 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001053 return mEventQueue.postMessage(msg, reltime);
1054}
1055
1056status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001057 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001058 status_t res = mEventQueue.postMessage(msg, reltime);
1059 if (res == NO_ERROR) {
1060 msg->wait();
1061 }
1062 return res;
1063}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001064
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001065void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001066 do {
1067 waitForEvent();
1068 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001069}
1070
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001071void SurfaceFlinger::enableHardwareVsync() {
1072 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001073 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001074 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001075 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1076 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001078 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001079}
1080
Jesse Hall948fe0c2013-10-14 12:56:09 -07001081void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001082 Mutex::Autolock _l(mHWVsyncLock);
1083
Jesse Hall948fe0c2013-10-14 12:56:09 -07001084 if (makeAvailable) {
1085 mHWVsyncAvailable = true;
1086 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001087 // Hardware vsync is not currently available, so abort the resync
1088 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001089 return;
1090 }
1091
Dan Stoza9e56aa02015-11-02 13:00:03 -08001092 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1093 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001094
1095 mPrimaryDispSync.reset();
1096 mPrimaryDispSync.setPeriod(period);
1097
1098 if (!mPrimaryHWVsyncEnabled) {
1099 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001100 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1101 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001102 mPrimaryHWVsyncEnabled = true;
1103 }
1104}
1105
Jesse Hall948fe0c2013-10-14 12:56:09 -07001106void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001107 Mutex::Autolock _l(mHWVsyncLock);
1108 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001109 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1110 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111 mPrimaryDispSync.endResync();
1112 mPrimaryHWVsyncEnabled = false;
1113 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001114 if (makeUnavailable) {
1115 mHWVsyncAvailable = false;
1116 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001117}
1118
Tim Murray4a4e4a22016-04-19 16:29:23 +00001119void SurfaceFlinger::resyncWithRateLimit() {
1120 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001121
1122 // No explicit locking is needed here since EventThread holds a lock while calling this method
1123 static nsecs_t sLastResyncAttempted = 0;
1124 const nsecs_t now = systemTime();
1125 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001126 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001127 }
Dan Stoza57164302017-05-08 14:03:54 -07001128 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001129}
1130
Steven Thomas3cfac282017-02-06 12:29:30 -08001131void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1132 nsecs_t timestamp) {
1133 Mutex::Autolock lock(mStateLock);
1134 // Ignore any vsyncs from the non-active hardware composer.
1135 if (composer != mHwc) {
1136 return;
1137 }
1138
Jamie Gennisd1700752013-10-14 12:22:52 -07001139 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001140
Jamie Gennisd1700752013-10-14 12:22:52 -07001141 { // Scope for the lock
1142 Mutex::Autolock _l(mHWVsyncLock);
1143 if (type == 0 && mPrimaryHWVsyncEnabled) {
1144 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001145 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001146 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001147
1148 if (needsHwVsync) {
1149 enableHardwareVsync();
1150 } else {
1151 disableHardwareVsync(false);
1152 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001153}
1154
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001155void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001156 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001157 *compositorTiming = mCompositorTiming;
1158}
1159
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001160void SurfaceFlinger::createDefaultDisplayDevice() {
1161 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1162 wp<IBinder> token = mBuiltinDisplays[type];
1163
1164 // All non-virtual displays are currently considered secure.
1165 const bool isSecure = true;
1166
1167 sp<IGraphicBufferProducer> producer;
1168 sp<IGraphicBufferConsumer> consumer;
1169 BufferQueue::createBufferQueue(&producer, &consumer);
1170
1171 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1172
1173 bool hasWideColorModes = false;
1174 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1175 for (android_color_mode_t colorMode : modes) {
1176 switch (colorMode) {
1177 case HAL_COLOR_MODE_DISPLAY_P3:
1178 case HAL_COLOR_MODE_ADOBE_RGB:
1179 case HAL_COLOR_MODE_DCI_P3:
1180 hasWideColorModes = true;
1181 break;
1182 default:
1183 break;
1184 }
1185 }
1186 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1187 token, fbs, producer, mRenderEngine->getEGLConfig(),
1188 hasWideColorModes && hasWideColorDisplay);
1189 mDisplays.add(token, hw);
1190 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1191 if (hasWideColorModes && hasWideColorDisplay) {
1192 defaultColorMode = HAL_COLOR_MODE_SRGB;
1193 }
1194 setActiveColorModeInternal(hw, defaultColorMode);
1195}
1196
1197void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001198 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001199
1200 if (composer->isUsingVrComposer()) {
1201 // We handle initializing the primary display device for the VR
1202 // window manager hwc explicitly at the time of transition.
1203 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1204 ALOGE("External displays are not supported by the vr hardware composer.");
1205 }
1206 return;
1207 }
1208
Dan Stoza9e56aa02015-11-02 13:00:03 -08001209 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1210 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001211 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1212 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001213 } else {
1214 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001215 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001216 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001217 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001218 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001219 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1220 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001221 }
1222 setTransactionFlags(eDisplayTransactionNeeded);
1223
Andy McFadden9e9689c2012-10-10 18:17:51 -07001224 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001225 }
Mathias Agopian86303202012-07-24 22:46:10 -07001226}
1227
Steven Thomas3cfac282017-02-06 12:29:30 -08001228void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1229 Mutex::Autolock lock(mStateLock);
1230 if (composer == mHwc) {
1231 repaintEverything();
1232 } else {
1233 // This isn't from our current hardware composer. If it's a callback
1234 // from the real composer, forward the refresh request to vr
1235 // flinger. Otherwise ignore it.
1236 if (!composer->isUsingVrComposer()) {
1237 mVrFlinger->OnHardwareComposerRefresh();
1238 }
1239 }
1240}
1241
Dan Stoza9e56aa02015-11-02 13:00:03 -08001242void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001243 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001244 getHwComposer().setVsyncEnabled(disp,
1245 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001246}
1247
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001248void SurfaceFlinger::clearHwcLayers(const LayerVector& layers) {
1249 for (size_t i = 0; i < layers.size(); ++i) {
1250 layers[i]->clearHwcLayers();
1251 }
1252}
1253
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001254// Note: it is assumed the caller holds |mStateLock| when this is called
1255void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001256 disableHardwareVsync(true);
1257 clearHwcLayers(mDrawingState.layersSortedByZ);
1258 clearHwcLayers(mCurrentState.layersSortedByZ);
1259 // Clear the drawing state so that the logic inside of
1260 // handleTransactionLocked will fire. It will determine the delta between
1261 // mCurrentState and mDrawingState and re-apply all changes when we make the
1262 // transition.
1263 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001264 // Release virtual display hwcId during vr mode transition.
1265 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1266 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1267 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1268 displayDevice->disconnect(getHwComposer());
1269 }
1270 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001271 mDisplays.clear();
1272}
1273
Steven Thomas050b2c82017-03-06 11:45:16 -08001274void SurfaceFlinger::updateVrFlinger() {
1275 if (!mVrFlinger)
1276 return;
1277 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1278 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001279 return;
1280 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001281
Steven Thomas050b2c82017-03-06 11:45:16 -08001282 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001283 // Construct new HWComposer without holding any locks.
1284 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285
1286 // Set up the event handlers. This step is neccessary to initialize the internal state of
1287 // the hardware composer object properly. Our callbacks are designed such that if they are
1288 // triggered between now and the point where the display is properly re-initialized, they
1289 // will not have any effect, so this is safe to do here, before the lock is aquired.
1290 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001291 ALOGV("Vr HWC created");
1292 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001293
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001294 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001295
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001296 if (vrFlingerRequestsDisplay) {
1297 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001298
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001299 mHwc = mVrHwc;
1300 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001301
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001302 } else {
1303 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001304
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001305 resetHwcLocked();
1306
1307 mHwc = mRealHwc;
1308 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001310
1311 mVisibleRegionsDirty = true;
1312 invalidateHwcGeometry();
1313
1314 // Explicitly re-initialize the primary display. This is because some other
1315 // parts of this class rely on the primary display always being available.
1316 createDefaultDisplayDevice();
1317
Alex Sakhartchouk933ed5c2017-06-05 10:37:57 -04001318 // Re-enable default display.
1319 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1320 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1321 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1322
1323 // Reset the timing values to account for the period of the swapped in HWC
1324 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1325 const nsecs_t period = activeConfig->getVsyncPeriod();
1326 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1327
1328 // Use phase of 0 since phase is not known.
1329 // Use latency of 0, which will snap to the ideal latency.
1330 setCompositorTimingSnapped(0, period, 0);
1331 });
1332 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 android_atomic_or(1, &mRepaintEverything);
1335 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336}
1337
Mathias Agopian4fec8732012-06-29 14:12:52 -07001338void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001339 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001340 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001341 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001342 bool frameMissed = !mHadClientComposition &&
1343 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001344 (mPreviousPresentFence->getSignalTime() ==
1345 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001346 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001347 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001348 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001349 signalLayerUpdate();
1350 break;
1351 }
1352
Steven Thomas050b2c82017-03-06 11:45:16 -08001353 // Now that we're going to make it to the handleMessageTransaction()
1354 // call below it's safe to call updateVrFlinger(), which will
1355 // potentially trigger a display handoff.
1356 updateVrFlinger();
1357
Dan Stoza6b9454d2014-11-07 16:00:59 -08001358 bool refreshNeeded = handleMessageTransaction();
1359 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001360 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001361 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001362 // Signal a refresh if a transaction modified the window state,
1363 // a new buffer was latched, or if HWC has requested a full
1364 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001365 signalRefresh();
1366 }
1367 break;
1368 }
1369 case MessageQueue::REFRESH: {
1370 handleMessageRefresh();
1371 break;
1372 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001373 }
1374}
1375
Dan Stoza6b9454d2014-11-07 16:00:59 -08001376bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001377 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001378 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001379 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001380 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001381 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001382 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001383}
1384
Dan Stoza6b9454d2014-11-07 16:00:59 -08001385bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001386 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001388}
1389
1390void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001391 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001392
Pablo Ceballos40845df2016-01-25 17:41:15 -08001393 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001394
Brian Andersond6927fb2016-07-23 23:37:30 -07001395 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001396 rebuildLayerStacks();
1397 setUpHWComposer();
1398 doDebugFlashRegions();
1399 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001401
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001402 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001403
1404 mHadClientComposition = false;
1405 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1406 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1407 mHadClientComposition = mHadClientComposition ||
1408 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1409 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001410
Dan Stoza9e56aa02015-11-02 13:00:03 -08001411 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001412}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001413
Mathias Agopiancd60f992012-08-16 16:28:27 -07001414void SurfaceFlinger::doDebugFlashRegions()
1415{
1416 // is debugging enabled
1417 if (CC_LIKELY(!mDebugRegion))
1418 return;
1419
1420 const bool repaintEverything = mRepaintEverything;
1421 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1422 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001423 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001424 // transform the dirty region into this screen's coordinate space
1425 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1426 if (!dirtyRegion.isEmpty()) {
1427 // redraw the whole screen
1428 doComposeSurfaces(hw, Region(hw->bounds()));
1429
1430 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001431 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001432 RenderEngine& engine(getRenderEngine());
1433 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1434
Mathias Agopianda27af92012-09-13 18:17:13 -07001435 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436 }
1437 }
1438 }
1439
1440 postFramebuffer();
1441
1442 if (mDebugRegion > 1) {
1443 usleep(mDebugRegion * 1000);
1444 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001445
Dan Stoza9e56aa02015-11-02 13:00:03 -08001446 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001447 auto& displayDevice = mDisplays[displayId];
1448 if (!displayDevice->isDisplayOn()) {
1449 continue;
1450 }
1451
1452 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001453 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1454 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001455 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001456}
1457
Brian Andersond6927fb2016-07-23 23:37:30 -07001458void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001459{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001460 ATRACE_CALL();
1461 ALOGV("preComposition");
1462
Mathias Agopiancd60f992012-08-16 16:28:27 -07001463 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001464 mDrawingState.traverseInZOrder([&](Layer* layer) {
1465 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466 needExtraInvalidate = true;
1467 }
Robert Carr2047fae2016-11-28 14:09:09 -08001468 });
1469
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 if (needExtraInvalidate) {
1471 signalLayerUpdate();
1472 }
1473}
1474
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001475void SurfaceFlinger::updateCompositorTiming(
1476 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1477 std::shared_ptr<FenceTime>& presentFenceTime) {
1478 // Update queue of past composite+present times and determine the
1479 // most recently known composite to present latency.
1480 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1481 nsecs_t compositeToPresentLatency = -1;
1482 while (!mCompositePresentTimes.empty()) {
1483 CompositePresentTime& cpt = mCompositePresentTimes.front();
1484 // Cached values should have been updated before calling this method,
1485 // which helps avoid duplicate syscalls.
1486 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1487 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1488 break;
1489 }
1490 compositeToPresentLatency = displayTime - cpt.composite;
1491 mCompositePresentTimes.pop();
1492 }
1493
1494 // Don't let mCompositePresentTimes grow unbounded, just in case.
1495 while (mCompositePresentTimes.size() > 16) {
1496 mCompositePresentTimes.pop();
1497 }
1498
Brian Andersond0010582017-03-07 13:20:31 -08001499 setCompositorTimingSnapped(
1500 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1501}
1502
1503void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1504 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505 // Integer division and modulo round toward 0 not -inf, so we need to
1506 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001507 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001508 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1509 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1510
Brian Andersond0010582017-03-07 13:20:31 -08001511 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1512 if (idealLatency <= 0) {
1513 idealLatency = vsyncInterval;
1514 }
1515
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001516 // Snap the latency to a value that removes scheduling jitter from the
1517 // composition and present times, which often have >1ms of jitter.
1518 // Reducing jitter is important if an app attempts to extrapolate
1519 // something (such as user input) to an accurate diasplay time.
1520 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1521 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001522 nsecs_t bias = vsyncInterval / 2;
1523 int64_t extraVsyncs =
1524 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1525 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1526 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001527
Brian Andersond0010582017-03-07 13:20:31 -08001528 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001529 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1530 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001531 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532}
1533
1534void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001535{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001536 ATRACE_CALL();
1537 ALOGV("postComposition");
1538
Brian Anderson3546a3f2016-07-14 11:51:14 -07001539 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001540 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001541 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001542 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001543 }
1544
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545 // |mStateLock| not needed as we are on the main thread
1546 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001547
1548 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1549 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1550 glCompositionDoneFenceTime =
1551 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1552 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1553 } else {
1554 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1555 }
1556 mGlCompositionDoneTimeline.updateSignalTimes();
1557
Brian Anderson4e606e32017-03-16 15:34:57 -07001558 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1559 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1560 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001561 mDisplayTimeline.updateSignalTimes();
1562
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001563 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1564 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1565
1566 // We use the refreshStartTime which might be sampled a little later than
1567 // when we started doing work for this frame, but that should be okay
1568 // since updateCompositorTiming has snapping logic.
1569 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001570 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001571 CompositorTiming compositorTiming;
1572 {
1573 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1574 compositorTiming = mCompositorTiming;
1575 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001576
Robert Carr2047fae2016-11-28 14:09:09 -08001577 mDrawingState.traverseInZOrder([&](Layer* layer) {
1578 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001579 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001580 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001581 recordBufferingStats(layer->getName().string(),
1582 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001583 }
Robert Carr2047fae2016-11-28 14:09:09 -08001584 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001585
Brian Anderson4e606e32017-03-16 15:34:57 -07001586 if (presentFence->isValid()) {
1587 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001588 enableHardwareVsync();
1589 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001590 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001591 }
1592 }
1593
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001594 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001595 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001596 enableHardwareVsync();
1597 }
1598 }
1599
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001600 if (mAnimCompositionPending) {
1601 mAnimCompositionPending = false;
1602
Brian Anderson4e606e32017-03-16 15:34:57 -07001603 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001604 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001605 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001606 } else {
1607 // The HWC doesn't support present fences, so use the refresh
1608 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001609 nsecs_t presentTime =
1610 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001611 mAnimFrameTracker.setActualPresentTime(presentTime);
1612 }
1613 mAnimFrameTracker.advanceFrame();
1614 }
Dan Stozab90cf072015-03-05 11:05:59 -08001615
1616 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1617 return;
1618 }
1619
1620 nsecs_t currentTime = systemTime();
1621 if (mHasPoweredOff) {
1622 mHasPoweredOff = false;
1623 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001624 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001625 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001626 if (numPeriods < NUM_BUCKETS - 1) {
1627 mFrameBuckets[numPeriods] += elapsedTime;
1628 } else {
1629 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1630 }
1631 mTotalTime += elapsedTime;
1632 }
1633 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634}
1635
1636void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001637 ATRACE_CALL();
1638 ALOGV("rebuildLayerStacks");
1639
Mathias Agopiancd60f992012-08-16 16:28:27 -07001640 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001641 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1642 ATRACE_CALL();
1643 mVisibleRegionsDirty = false;
1644 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001645
Jeff Sharkey76488112017-02-27 14:15:18 -07001646 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1647 Region opaqueRegion;
1648 Region dirtyRegion;
1649 Vector<sp<Layer>> layersSortedByZ;
1650 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1651 const Transform& tr(displayDevice->getTransform());
1652 const Rect bounds(displayDevice->getBounds());
1653 if (displayDevice->isDisplayOn()) {
1654 computeVisibleRegions(
1655 displayDevice->getLayerStack(), dirtyRegion,
1656 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001657
Jeff Sharkey76488112017-02-27 14:15:18 -07001658 mDrawingState.traverseInZOrder([&](Layer* layer) {
1659 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1660 Region drawRegion(tr.transform(
1661 layer->visibleNonTransparentRegion));
1662 drawRegion.andSelf(bounds);
1663 if (!drawRegion.isEmpty()) {
1664 layersSortedByZ.add(layer);
1665 } else {
1666 // Clear out the HWC layer if this layer was
1667 // previously visible, but no longer is
1668 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1669 nullptr);
1670 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001671 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001672 // WM changes displayDevice->layerStack upon sleep/awake.
1673 // Here we make sure we delete the HWC layers even if
1674 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001675 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1676 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001677 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001678 });
1679 }
1680 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1681 displayDevice->undefinedRegion.set(bounds);
1682 displayDevice->undefinedRegion.subtractSelf(
1683 tr.transform(opaqueRegion));
1684 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001685 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001686 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001688
Romain Guy0147a172017-06-01 13:53:56 -07001689mat4 SurfaceFlinger::computeSaturationMatrix() const {
1690 if (mSaturation == 1.0f) {
1691 return mat4();
1692 }
1693
1694 // Rec.709 luma coefficients
1695 float3 luminance{0.213f, 0.715f, 0.072f};
1696 luminance *= 1.0f - mSaturation;
1697 return mat4(
1698 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1699 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1700 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1701 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1702 );
1703}
1704
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001705// pickColorMode translates a given dataspace into the best available color mode.
1706// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001707android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001708 switch (dataSpace) {
1709 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1710 // system expects.
1711 case HAL_DATASPACE_UNKNOWN:
1712 case HAL_DATASPACE_SRGB:
1713 case HAL_DATASPACE_V0_SRGB:
1714 return HAL_COLOR_MODE_SRGB;
1715 break;
1716
1717 case HAL_DATASPACE_DISPLAY_P3:
1718 return HAL_COLOR_MODE_DISPLAY_P3;
1719 break;
1720
1721 default:
1722 // TODO (courtneygo): Do we want to assert an error here?
1723 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1724 dataSpace);
1725 return HAL_COLOR_MODE_SRGB;
1726 break;
1727 }
1728}
1729
Romain Guy0147a172017-06-01 13:53:56 -07001730android_dataspace SurfaceFlinger::bestTargetDataSpace(
1731 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001732 // Only support sRGB and Display-P3 right now.
1733 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1734 return HAL_DATASPACE_DISPLAY_P3;
1735 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001736 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1737 return HAL_DATASPACE_DISPLAY_P3;
1738 }
1739 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1740 return HAL_DATASPACE_DISPLAY_P3;
1741 }
1742
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001743 return HAL_DATASPACE_V0_SRGB;
1744}
1745
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001747 ATRACE_CALL();
1748 ALOGV("setUpHWComposer");
1749
Jesse Hall028dc8f2013-08-20 16:35:32 -07001750 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001751 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1752 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1753 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1754
1755 // If nothing has changed (!dirty), don't recompose.
1756 // If something changed, but we don't currently have any visible layers,
1757 // and didn't when we last did a composition, then skip it this time.
1758 // The second rule does two things:
1759 // - When all layers are removed from a display, we'll emit one black
1760 // frame, then nothing more until we get new layers.
1761 // - When a display is created with a private layer stack, we won't
1762 // emit any black frames until a layer is added to the layer stack.
1763 bool mustRecompose = dirty && !(empty && wasEmpty);
1764
1765 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1766 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1767 mustRecompose ? "doing" : "skipping",
1768 dirty ? "+" : "-",
1769 empty ? "+" : "-",
1770 wasEmpty ? "+" : "-");
1771
Dan Stoza71433162014-02-04 16:22:36 -08001772 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001773
1774 if (mustRecompose) {
1775 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1776 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001777 }
1778
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 // build the h/w work list
1780 if (CC_UNLIKELY(mGeometryInvalid)) {
1781 mGeometryInvalid = false;
1782 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1783 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1784 const auto hwcId = displayDevice->getHwcDisplayId();
1785 if (hwcId >= 0) {
1786 const Vector<sp<Layer>>& currentLayers(
1787 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001788 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001789 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001790 if (!layer->hasHwcLayer(hwcId)) {
1791 auto hwcLayer = mHwc->createLayer(hwcId);
1792 if (hwcLayer) {
1793 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1794 } else {
1795 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001797 }
1798 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001799
Robert Carrae060832016-11-28 10:51:00 -08001800 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001801 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001802 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001803 }
1804 }
1805 }
1806 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001807 }
Riley Andrews03414a12014-07-01 14:22:59 -07001808
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001809
Romain Guy0147a172017-06-01 13:53:56 -07001810 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001811
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 // Set the per-frame data
1813 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1814 auto& displayDevice = mDisplays[displayId];
1815 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001816
Dan Stoza9e56aa02015-11-02 13:00:03 -08001817 if (hwcId < 0) {
1818 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001819 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001820 if (colorMatrix != mPreviousColorMatrix) {
1821 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1822 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1823 "display %zd: %d", displayId, result);
1824 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1826 layer->setPerFrameData(displayDevice);
1827 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001828
1829 if (hasWideColorDisplay) {
1830 android_color_mode newColorMode;
1831 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1832
1833 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1834 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1835 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1836 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1837 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1838 }
1839 newColorMode = pickColorMode(newDataSpace);
1840
1841 setActiveColorModeInternal(displayDevice, newColorMode);
1842 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 }
1844
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001845 mPreviousColorMatrix = colorMatrix;
1846
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001848 auto& displayDevice = mDisplays[displayId];
1849 if (!displayDevice->isDisplayOn()) {
1850 continue;
1851 }
1852
1853 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1855 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001856 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001857}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001858
Mathias Agopiancd60f992012-08-16 16:28:27 -07001859void SurfaceFlinger::doComposition() {
1860 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 ALOGV("doComposition");
1862
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001863 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001864 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001865 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001866 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867 // transform the dirty region into this screen's coordinate space
1868 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001869
1870 // repaint the framebuffer (if needed)
1871 doDisplayComposition(hw, dirtyRegion);
1872
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 hw->dirtyRegion.clear();
1874 hw->flip(hw->swapRegion);
1875 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001876 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001877 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001878 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001879}
1880
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001881void SurfaceFlinger::postFramebuffer()
1882{
Mathias Agopian841cde52012-03-01 15:44:37 -08001883 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001885
Mathias Agopiana44b0412011-10-16 18:46:35 -07001886 const nsecs_t now = systemTime();
1887 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001888
Dan Stoza9e56aa02015-11-02 13:00:03 -08001889 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1890 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001891 if (!displayDevice->isDisplayOn()) {
1892 continue;
1893 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001894 const auto hwcId = displayDevice->getHwcDisplayId();
1895 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001896 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001897 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001898 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001899 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001900 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1901 sp<Fence> releaseFence = Fence::NO_FENCE;
1902 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1903 releaseFence = displayDevice->getClientTargetAcquireFence();
1904 } else {
1905 auto hwcLayer = layer->getHwcLayer(hwcId);
1906 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001907 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001908 layer->onLayerDisplayed(releaseFence);
1909 }
1910 if (hwcId >= 0) {
1911 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001912 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001913 }
1914
Mathias Agopiana44b0412011-10-16 18:46:35 -07001915 mLastSwapBufferTime = systemTime() - now;
1916 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001917
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001918 // |mStateLock| not needed as we are on the main thread
1919 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001920 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1921 logFrameStats();
1922 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001923}
1924
Mathias Agopian87baae12012-07-31 12:38:26 -07001925void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001926{
Mathias Agopian841cde52012-03-01 15:44:37 -08001927 ATRACE_CALL();
1928
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001929 // here we keep a copy of the drawing state (that is the state that's
1930 // going to be overwritten by handleTransactionLocked()) outside of
1931 // mStateLock so that the side-effects of the State assignment
1932 // don't happen with mStateLock held (which can cause deadlocks).
1933 State drawingState(mDrawingState);
1934
Mathias Agopianca4d3602011-05-19 15:38:14 -07001935 Mutex::Autolock _l(mStateLock);
1936 const nsecs_t now = systemTime();
1937 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938
Mathias Agopianca4d3602011-05-19 15:38:14 -07001939 // Here we're guaranteed that some transaction flags are set
1940 // so we can call handleTransactionLocked() unconditionally.
1941 // We call getTransactionFlags(), which will also clear the flags,
1942 // with mStateLock held to guarantee that mCurrentState won't change
1943 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001944
Mathias Agopiane57f2922012-08-09 16:29:12 -07001945 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001946 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001947
Mathias Agopianca4d3602011-05-19 15:38:14 -07001948 mLastTransactionTime = systemTime() - now;
1949 mDebugInTransaction = 0;
1950 invalidateHwcGeometry();
1951 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001952}
1953
Mathias Agopian87baae12012-07-31 12:38:26 -07001954void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001955{
Dan Stoza7dde5992015-05-22 09:51:44 -07001956 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001957 mCurrentState.traverseInZOrder([](Layer* layer) {
1958 layer->notifyAvailableFrames();
1959 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001960
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001961 /*
1962 * Traversal of the children
1963 * (perform the transaction for each of them if needed)
1964 */
1965
Mathias Agopian3559b072012-08-15 13:46:03 -07001966 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001967 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001968 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001969 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970
1971 const uint32_t flags = layer->doTransaction(0);
1972 if (flags & Layer::eVisibleRegion)
1973 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001974 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975 }
1976
1977 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001978 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001979 */
1980
Mathias Agopiane57f2922012-08-09 16:29:12 -07001981 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001982 // here we take advantage of Vector's copy-on-write semantics to
1983 // improve performance by skipping the transaction entirely when
1984 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001985 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1986 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001987 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001989 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001990 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001991
1992 // find the displays that were removed
1993 // (ie: in drawing state but not in current state)
1994 // also handle displays that changed
1995 // (ie: displays that are in both lists)
1996 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001997 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1998 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001999 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002000 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002001 // Call makeCurrent() on the primary display so we can
2002 // be sure that nothing associated with this display
2003 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002004 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002005 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002006 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002007 if (hw != NULL)
2008 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002009 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002010 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002011 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002012 } else {
2013 ALOGW("trying to remove the main display");
2014 }
2015 } else {
2016 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002017 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002018 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002019 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2020 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002021 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002022 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002023 // recreating the DisplayDevice, so we just remove it
2024 // from the drawing state, so that it get re-added
2025 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002026 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002027 if (hw != NULL)
2028 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002029 mDisplays.removeItem(display);
2030 mDrawingState.displays.removeItemsAt(i);
2031 dc--; i--;
2032 // at this point we must loop to the next item
2033 continue;
2034 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002035
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002036 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002037 if (disp != NULL) {
2038 if (state.layerStack != draw[i].layerStack) {
2039 disp->setLayerStack(state.layerStack);
2040 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002041 if ((state.orientation != draw[i].orientation)
2042 || (state.viewport != draw[i].viewport)
2043 || (state.frame != draw[i].frame))
2044 {
2045 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002046 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002047 }
Michael Lentine47e45402014-07-18 15:34:25 -07002048 if (state.width != draw[i].width || state.height != draw[i].height) {
2049 disp->setDisplaySize(state.width, state.height);
2050 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002051 }
2052 }
2053 }
2054
2055 // find displays that were added
2056 // (ie: in current state but not in drawing state)
2057 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002058 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002059 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002060
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002061 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002062 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002063 sp<IGraphicBufferProducer> bqProducer;
2064 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002065 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002066
Dan Stoza9e56aa02015-11-02 13:00:03 -08002067 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002068 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002069 // Virtual displays without a surface are dormant:
2070 // they have external state (layer stack, projection,
2071 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002072 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002073
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002074 // Allow VR composer to use virtual displays.
2075 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002076 int width = 0;
2077 int status = state.surface->query(
2078 NATIVE_WINDOW_WIDTH, &width);
2079 ALOGE_IF(status != NO_ERROR,
2080 "Unable to query width (%d)", status);
2081 int height = 0;
2082 status = state.surface->query(
2083 NATIVE_WINDOW_HEIGHT, &height);
2084 ALOGE_IF(status != NO_ERROR,
2085 "Unable to query height (%d)", status);
2086 int intFormat = 0;
2087 status = state.surface->query(
2088 NATIVE_WINDOW_FORMAT, &intFormat);
2089 ALOGE_IF(status != NO_ERROR,
2090 "Unable to query format (%d)", status);
2091 auto format = static_cast<android_pixel_format_t>(
2092 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002093
Dan Stoza8cf150a2016-08-02 10:27:31 -07002094 mHwc->allocateVirtualDisplay(width, height, &format,
2095 &hwcId);
2096 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097
Dan Stoza5cf424b2016-05-20 14:02:39 -07002098 // TODO: Plumb requested format back up to consumer
2099
Dan Stoza9e56aa02015-11-02 13:00:03 -08002100 sp<VirtualDisplaySurface> vds =
2101 new VirtualDisplaySurface(*mHwc,
2102 hwcId, state.surface, bqProducer,
2103 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002104
2105 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002106 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002107 }
2108 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002109 ALOGE_IF(state.surface!=NULL,
2110 "adding a supported display, but rendering "
2111 "surface is provided (%p), ignoring it",
2112 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002113
2114 hwcId = state.type;
2115 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2116 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002117 }
2118
2119 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002120 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002121 sp<DisplayDevice> hw =
2122 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2123 dispSurface, producer,
2124 mRenderEngine->getEGLConfig(),
2125 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002126 hw->setLayerStack(state.layerStack);
2127 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002128 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002129 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002130 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002131 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002132 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002133 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002134 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002135 }
2136 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002138 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002139
Mathias Agopian84300952012-11-21 16:02:13 -08002140 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2141 // The transform hint might have changed for some layers
2142 // (either because a display has changed, or because a layer
2143 // as changed).
2144 //
2145 // Walk through all the layers in currentLayers,
2146 // and update their transform hint.
2147 //
2148 // If a layer is visible only on a single display, then that
2149 // display is used to calculate the hint, otherwise we use the
2150 // default display.
2151 //
2152 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2153 // the hint is set before we acquire a buffer from the surface texture.
2154 //
2155 // NOTE: layer transactions have taken place already, so we use their
2156 // drawing state. However, SurfaceFlinger's own transaction has not
2157 // happened yet, so we must use the current state layer list
2158 // (soon to become the drawing state list).
2159 //
2160 sp<const DisplayDevice> disp;
2161 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002162 bool first = true;
2163 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002164 // NOTE: we rely on the fact that layers are sorted by
2165 // layerStack first (so we don't have to traverse the list
2166 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002167 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002168 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002169 currentlayerStack = layerStack;
2170 // figure out if this layerstack is mirrored
2171 // (more than one display) if so, pick the default display,
2172 // if not, pick the only display it's on.
2173 disp.clear();
2174 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2175 sp<const DisplayDevice> hw(mDisplays[dpy]);
2176 if (hw->getLayerStack() == currentlayerStack) {
2177 if (disp == NULL) {
2178 disp = hw;
2179 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002180 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002181 break;
2182 }
2183 }
2184 }
2185 }
Chet Haase91d25932013-04-11 15:24:55 -07002186 if (disp == NULL) {
2187 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2188 // redraw after transform hint changes. See bug 8508397.
2189
2190 // could be null when this layer is using a layerStack
2191 // that is not visible on any display. Also can occur at
2192 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002193 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002194 }
Chet Haase91d25932013-04-11 15:24:55 -07002195 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002196
2197 first = false;
2198 });
Mathias Agopian84300952012-11-21 16:02:13 -08002199 }
2200
2201
Mathias Agopian3559b072012-08-15 13:46:03 -07002202 /*
2203 * Perform our own transaction if needed
2204 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002205
2206 if (mLayersAdded) {
2207 mLayersAdded = false;
2208 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002209 mVisibleRegionsDirty = true;
2210 }
2211
2212 // some layers might have been removed, so
2213 // we need to update the regions they're exposing.
2214 if (mLayersRemoved) {
2215 mLayersRemoved = false;
2216 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002217 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002218 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002219 // this layer is not visible anymore
2220 // TODO: we could traverse the tree from front to back and
2221 // compute the actual visible region
2222 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002223 Region visibleReg;
2224 visibleReg.set(layer->computeScreenBounds());
2225 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002226 }
Robert Carr2047fae2016-11-28 14:09:09 -08002227 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002228 }
2229
2230 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002231
2232 updateCursorAsync();
2233}
2234
2235void SurfaceFlinger::updateCursorAsync()
2236{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2238 auto& displayDevice = mDisplays[displayId];
2239 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002240 continue;
2241 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002242
2243 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2244 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002245 }
2246 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002247}
2248
2249void SurfaceFlinger::commitTransaction()
2250{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002251 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002252 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002253 for (const auto& l : mLayersPendingRemoval) {
2254 recordBufferingStats(l->getName().string(),
2255 l->getOccupancyHistory(true));
2256 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002257 }
2258 mLayersPendingRemoval.clear();
2259 }
2260
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002261 // If this transaction is part of a window animation then the next frame
2262 // we composite should be considered an animation as well.
2263 mAnimCompositionPending = mAnimTransactionPending;
2264
Mathias Agopian4fec8732012-06-29 14:12:52 -07002265 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002266 mDrawingState.traverseInZOrder([](Layer* layer) {
2267 layer->commitChildList();
2268 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002269 mTransactionPending = false;
2270 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002271 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002272}
2273
Robert Carr2047fae2016-11-28 14:09:09 -08002274void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002275 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276{
Mathias Agopian841cde52012-03-01 15:44:37 -08002277 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002279
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002280 Region aboveOpaqueLayers;
2281 Region aboveCoveredLayers;
2282 Region dirty;
2283
Mathias Agopian87baae12012-07-31 12:38:26 -07002284 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285
Robert Carr2047fae2016-11-28 14:09:09 -08002286 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002288 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289
Jesse Hall01e29052013-02-19 16:13:35 -08002290 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002291 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002292 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002293
Mathias Agopianab028732010-03-16 16:41:46 -07002294 /*
2295 * opaqueRegion: area of a surface that is fully opaque.
2296 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002298
2299 /*
2300 * visibleRegion: area of a surface that is visible on screen
2301 * and not fully transparent. This is essentially the layer's
2302 * footprint minus the opaque regions above it.
2303 * Areas covered by a translucent surface are considered visible.
2304 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002305 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002306
2307 /*
2308 * coveredRegion: area of a surface that is covered by all
2309 * visible regions above it (which includes the translucent areas).
2310 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002311 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002312
Jesse Halla8026d22012-09-25 13:25:04 -07002313 /*
2314 * transparentRegion: area of a surface that is hinted to be completely
2315 * transparent. This is only used to tell when the layer has no visible
2316 * non-transparent regions and can be removed from the layer list. It
2317 * does not affect the visibleRegion of this layer or any layers
2318 * beneath it. The hint may not be correct if apps don't respect the
2319 * SurfaceView restrictions (which, sadly, some don't).
2320 */
2321 Region transparentRegion;
2322
Mathias Agopianab028732010-03-16 16:41:46 -07002323
2324 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002325 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002326 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002327 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002329 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002330 if (!visibleRegion.isEmpty()) {
2331 // Remove the transparent area from the visible region
2332 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002333 if (tr.preserveRects()) {
2334 // transform the transparent region
2335 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002336 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002337 // transformation too complex, can't do the
2338 // transparent region optimization.
2339 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002340 }
Mathias Agopianab028732010-03-16 16:41:46 -07002341 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342
Mathias Agopianab028732010-03-16 16:41:46 -07002343 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002344 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002345 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002346 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2347 // the opaque region is the layer's footprint
2348 opaqueRegion = visibleRegion;
2349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350 }
2351 }
2352
Mathias Agopianab028732010-03-16 16:41:46 -07002353 // Clip the covered region to the visible region
2354 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2355
2356 // Update aboveCoveredLayers for next (lower) layer
2357 aboveCoveredLayers.orSelf(visibleRegion);
2358
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 // subtract the opaque region covered by the layers above us
2360 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361
2362 // compute this layer's dirty region
2363 if (layer->contentDirty) {
2364 // we need to invalidate the whole region
2365 dirty = visibleRegion;
2366 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002367 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002368 layer->contentDirty = false;
2369 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002370 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002371 * the exposed region consists of two components:
2372 * 1) what's VISIBLE now and was COVERED before
2373 * 2) what's EXPOSED now less what was EXPOSED before
2374 *
2375 * note that (1) is conservative, we start with the whole
2376 * visible region but only keep what used to be covered by
2377 * something -- which mean it may have been exposed.
2378 *
2379 * (2) handles areas that were not covered by anything but got
2380 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002381 */
Mathias Agopianab028732010-03-16 16:41:46 -07002382 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002383 const Region oldVisibleRegion = layer->visibleRegion;
2384 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002385 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2386 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 }
2388 dirty.subtractSelf(aboveOpaqueLayers);
2389
2390 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002391 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392
Mathias Agopianab028732010-03-16 16:41:46 -07002393 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002394 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002395
Jesse Halla8026d22012-09-25 13:25:04 -07002396 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002397 layer->setVisibleRegion(visibleRegion);
2398 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002399 layer->setVisibleNonTransparentRegion(
2400 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002401 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402
Mathias Agopian87baae12012-07-31 12:38:26 -07002403 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404}
2405
Mathias Agopian87baae12012-07-31 12:38:26 -07002406void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2407 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002408 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002409 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2410 if (hw->getLayerStack() == layerStack) {
2411 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002412 }
2413 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002414}
2415
Dan Stoza6b9454d2014-11-07 16:00:59 -08002416bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002418 ALOGV("handlePageFlip");
2419
Brian Andersond6927fb2016-07-23 23:37:30 -07002420 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002421
Mathias Agopian4fec8732012-06-29 14:12:52 -07002422 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002423 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002424 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002425
2426 // Store the set of layers that need updates. This set must not change as
2427 // buffers are being latched, as this could result in a deadlock.
2428 // Example: Two producers share the same command stream and:
2429 // 1.) Layer 0 is latched
2430 // 2.) Layer 0 gets a new frame
2431 // 2.) Layer 1 gets a new frame
2432 // 3.) Layer 1 is latched.
2433 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2434 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002435 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002436 if (layer->hasQueuedFrame()) {
2437 frameQueued = true;
2438 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002439 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002440 } else {
2441 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002442 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002443 } else {
2444 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002445 }
Robert Carr2047fae2016-11-28 14:09:09 -08002446 });
2447
Dan Stoza9e56aa02015-11-02 13:00:03 -08002448 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002449 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002450 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002451 invalidateLayerStack(layer->getLayerStack(), dirty);
Mike Stroyan0cd76192017-04-20 12:10:48 -06002452 if (!dirty.isEmpty()) {
2453 newDataLatched = true;
2454 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002455 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002456
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002457 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002458
2459 // If we will need to wake up at some time in the future to deal with a
2460 // queued frame that shouldn't be displayed during this vsync period, wake
2461 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002462 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002463 signalLayerUpdate();
2464 }
2465
2466 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002467 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468}
2469
Mathias Agopianad456f92011-01-13 17:53:01 -08002470void SurfaceFlinger::invalidateHwcGeometry()
2471{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002472 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002473}
2474
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002475
Fabien Sanglard830b8472016-11-30 16:35:58 -08002476void SurfaceFlinger::doDisplayComposition(
2477 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002478 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479{
Dan Stoza71433162014-02-04 16:22:36 -08002480 // We only need to actually compose the display if:
2481 // 1) It is being handled by hardware composer, which may need this to
2482 // keep its virtual display state machine in sync, or
2483 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002484 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002485 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002486 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002487 return;
2488 }
2489
Dan Stoza9e56aa02015-11-02 13:00:03 -08002490 ALOGV("doDisplayComposition");
2491
Mathias Agopian87baae12012-07-31 12:38:26 -07002492 Region dirtyRegion(inDirtyRegion);
2493
Mathias Agopianb8a55602009-06-26 19:06:36 -07002494 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002495 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496
Fabien Sanglard830b8472016-11-30 16:35:58 -08002497 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002498 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002499 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2500 // takes a rectangle, we must make sure to update that whole
2501 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002502 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002503 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002504 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002505 // We need to redraw the rectangle that will be updated
2506 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002507 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002508 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002509 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002510 } else {
2511 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002512 dirtyRegion.set(displayDevice->bounds());
2513 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514 }
2515 }
2516
Fabien Sanglard830b8472016-11-30 16:35:58 -08002517 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002519 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002520 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002521
2522 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002523 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524}
2525
Dan Stoza9e56aa02015-11-02 13:00:03 -08002526bool SurfaceFlinger::doComposeSurfaces(
2527 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002528{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002529 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002530
Dan Stoza9e56aa02015-11-02 13:00:03 -08002531 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002532
2533 mat4 oldColorMatrix;
2534 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2535 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2536 if (applyColorMatrix) {
2537 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2538 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2539 }
2540
Dan Stoza9e56aa02015-11-02 13:00:03 -08002541 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2542 if (hasClientComposition) {
2543 ALOGV("hasClientComposition");
2544
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002545#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002546 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002547 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002548#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002549 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002550 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002552 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002553
2554 // |mStateLock| not needed as we are on the main thread
2555 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002556 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2557 }
2558 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002559 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002560
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002561 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002562 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2563 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002564 // when using overlays, we assume a fully transparent framebuffer
2565 // NOTE: we could reduce how much we need to clear, for instance
2566 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002567 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002568 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002570 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002571 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002572 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002573
2574 // we remove the scissor part
2575 // we're left with the letterbox region
2576 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002577 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002578
2579 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002581
2582 // but limit it to the dirty region
2583 region.andSelf(dirty);
2584
Mathias Agopianb9494d52012-04-18 02:28:45 -07002585 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002586 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002587 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002588 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002589 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002590 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002591
Dan Stoza9e56aa02015-11-02 13:00:03 -08002592 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002593 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002594 // scissor on the main display. It should never be needed
2595 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 const Rect& bounds(displayDevice->getBounds());
2597 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002598 if (scissor != bounds) {
2599 // scissor doesn't match the screen's dimensions, so we
2600 // need to clear everything outside of it and enable
2601 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002602
Mathias Agopianf45c5102012-10-24 16:29:17 -07002603 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002604 const uint32_t height = displayDevice->getHeight();
2605 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002606 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002607 }
2608 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002609 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002610
Mathias Agopian85d751c2012-08-29 16:59:24 -07002611 /*
2612 * and then, render the layers targeted at the framebuffer
2613 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002614
Dan Stoza9e56aa02015-11-02 13:00:03 -08002615 ALOGV("Rendering client layers");
2616 const Transform& displayTransform = displayDevice->getTransform();
2617 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002618 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 bool firstLayer = true;
2620 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2621 const Region clip(dirty.intersect(
2622 displayTransform.transform(layer->visibleRegion)));
2623 ALOGV("Layer: %s", layer->getName().string());
2624 ALOGV(" Composition type: %s",
2625 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002626 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 switch (layer->getCompositionType(hwcId)) {
2628 case HWC2::Composition::Cursor:
2629 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002630 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002631 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002632 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2634 layer->isOpaque(state) && (state.alpha == 1.0f)
2635 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002636 // never clear the very first layer since we're
2637 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002638 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002639 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002640 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002641 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002642 case HWC2::Composition::Client: {
2643 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002644 break;
2645 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002646 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002647 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002648 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002649 } else {
2650 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002651 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002653 }
2654 } else {
2655 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002657 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002659 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002661 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002662 }
2663 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002664
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002665 if (applyColorMatrix) {
2666 getRenderEngine().setupColorTransform(oldColorMatrix);
2667 }
2668
Mathias Agopianf45c5102012-10-24 16:29:17 -07002669 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002671 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002672}
2673
Fabien Sanglard830b8472016-11-30 16:35:58 -08002674void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2675 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002676 RenderEngine& engine(getRenderEngine());
2677 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002678}
2679
Dan Stoza7d89d062015-04-30 13:29:25 -07002680status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002681 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002682 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683 const sp<Layer>& lbc,
2684 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002685{
Dan Stoza7d89d062015-04-30 13:29:25 -07002686 // add this layer to the current state list
2687 {
2688 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002689 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002690 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2691 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002692 return NO_MEMORY;
2693 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002694 if (parent == nullptr) {
2695 mCurrentState.layersSortedByZ.add(lbc);
2696 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002697 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2698 ALOGE("addClientLayer called with a removed parent");
2699 return NAME_NOT_FOUND;
2700 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002701 parent->addChild(lbc);
2702 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002703
Dan Stoza7d89d062015-04-30 13:29:25 -07002704 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002705 mLayersAdded = true;
2706 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002707 }
2708
Mathias Agopian96f08192010-06-02 23:28:45 -07002709 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002710 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002711
Dan Stoza7d89d062015-04-30 13:29:25 -07002712 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002713}
2714
Robert Carr9524cb32017-02-13 11:32:32 -08002715status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002716 Mutex::Autolock _l(mStateLock);
2717
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 const auto& p = layer->getParent();
2719 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2720 mCurrentState.layersSortedByZ.remove(layer);
2721
Chia-I Wu98f1c102017-05-30 14:54:08 -07002722 if (p != nullptr) {
2723 sp<Layer> ancestor = p;
2724 while (ancestor->getParent() != nullptr) {
2725 ancestor = ancestor->getParent();
2726 }
2727 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2728 ALOGE("removeLayer called with a layer whose parent has been removed");
2729 return NAME_NOT_FOUND;
2730 }
2731 }
2732
Robert Carr136e2f62017-02-08 17:54:29 -08002733 // As a matter of normal operation, the LayerCleaner will produce a second
2734 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2735 // so we will succeed in promoting it, but it's already been removed
2736 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2737 // otherwise something has gone wrong and we are leaking the layer.
2738 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2740 layer->getName().string(),
2741 (p != nullptr) ? p->getName().string() : "no-parent");
2742 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002743 } else if (index < 0) {
2744 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002745 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746
2747 mLayersPendingRemoval.add(layer);
2748 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002749 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 setTransactionFlags(eTransactionNeeded);
2751 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752}
2753
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002754uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002755 return android_atomic_release_load(&mTransactionFlags);
2756}
2757
Mathias Agopian3f844832013-08-07 21:24:32 -07002758uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2760}
2761
Mathias Agopian3f844832013-08-07 21:24:32 -07002762uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2764 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002765 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766 }
2767 return old;
2768}
2769
Mathias Agopian8b33f032012-07-24 20:43:54 -07002770void SurfaceFlinger::setTransactionState(
2771 const Vector<ComposerState>& state,
2772 const Vector<DisplayState>& displays,
2773 uint32_t flags)
2774{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002775 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002776 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002777 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002778
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002779 if (flags & eAnimation) {
2780 // For window updates that are part of an animation we must wait for
2781 // previous animation "frames" to be handled.
2782 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002783 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002784 if (CC_UNLIKELY(err != NO_ERROR)) {
2785 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002786 // caller after a few seconds.
2787 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2788 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002789 mAnimTransactionPending = false;
2790 break;
2791 }
2792 }
2793 }
2794
Mathias Agopiane57f2922012-08-09 16:29:12 -07002795 size_t count = displays.size();
2796 for (size_t i=0 ; i<count ; i++) {
2797 const DisplayState& s(displays[i]);
2798 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002799 }
2800
Mathias Agopiane57f2922012-08-09 16:29:12 -07002801 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002802 for (size_t i=0 ; i<count ; i++) {
2803 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002804 // Here we need to check that the interface we're given is indeed
2805 // one of our own. A malicious client could give us a NULL
2806 // IInterface, or one of its own or even one of our own but a
2807 // different type. All these situations would cause us to crash.
2808 //
2809 // NOTE: it would be better to use RTTI as we could directly check
2810 // that we have a Client*. however, RTTI is disabled in Android.
2811 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002812 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002813 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002814 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002815 sp<Client> client( static_cast<Client *>(s.client.get()) );
2816 transactionFlags |= setClientStateLocked(client, s.state);
2817 }
2818 }
2819 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002820 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002821
Robert Carr2a7dbb42016-05-24 11:41:28 -07002822 // If a synchronous transaction is explicitly requested without any changes,
2823 // force a transaction anyway. This can be used as a flush mechanism for
2824 // previous async transactions.
2825 if (transactionFlags == 0 && (flags & eSynchronous)) {
2826 transactionFlags = eTransactionNeeded;
2827 }
2828
Mathias Agopian386aa982011-11-07 21:58:03 -08002829 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002830 if (mInterceptor.isEnabled()) {
2831 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2832 }
Irvel468051e2016-06-13 16:44:44 -07002833
Mathias Agopian386aa982011-11-07 21:58:03 -08002834 // this triggers the transaction
2835 setTransactionFlags(transactionFlags);
2836
2837 // if this is a synchronous transaction, wait for it to take effect
2838 // before returning.
2839 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002840 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002841 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002842 if (flags & eAnimation) {
2843 mAnimTransactionPending = true;
2844 }
2845 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002846 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2847 if (CC_UNLIKELY(err != NO_ERROR)) {
2848 // just in case something goes wrong in SF, return to the
2849 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002850 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2851 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002852 break;
2853 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002854 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 }
2856}
2857
Mathias Agopiane57f2922012-08-09 16:29:12 -07002858uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2859{
Jesse Hall9a143922012-10-04 16:29:19 -07002860 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2861 if (dpyIdx < 0)
2862 return 0;
2863
Mathias Agopiane57f2922012-08-09 16:29:12 -07002864 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002865 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002866 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002867 const uint32_t what = s.what;
2868 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002869 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002870 disp.surface = s.surface;
2871 flags |= eDisplayTransactionNeeded;
2872 }
2873 }
2874 if (what & DisplayState::eLayerStackChanged) {
2875 if (disp.layerStack != s.layerStack) {
2876 disp.layerStack = s.layerStack;
2877 flags |= eDisplayTransactionNeeded;
2878 }
2879 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002880 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002881 if (disp.orientation != s.orientation) {
2882 disp.orientation = s.orientation;
2883 flags |= eDisplayTransactionNeeded;
2884 }
2885 if (disp.frame != s.frame) {
2886 disp.frame = s.frame;
2887 flags |= eDisplayTransactionNeeded;
2888 }
2889 if (disp.viewport != s.viewport) {
2890 disp.viewport = s.viewport;
2891 flags |= eDisplayTransactionNeeded;
2892 }
2893 }
Michael Lentine47e45402014-07-18 15:34:25 -07002894 if (what & DisplayState::eDisplaySizeChanged) {
2895 if (disp.width != s.width) {
2896 disp.width = s.width;
2897 flags |= eDisplayTransactionNeeded;
2898 }
2899 if (disp.height != s.height) {
2900 disp.height = s.height;
2901 flags |= eDisplayTransactionNeeded;
2902 }
2903 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002904 }
2905 return flags;
2906}
2907
2908uint32_t SurfaceFlinger::setClientStateLocked(
2909 const sp<Client>& client,
2910 const layer_state_t& s)
2911{
2912 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002913 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002914 if (layer != 0) {
2915 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002916 bool geometryAppliesWithResize =
2917 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002918 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002919 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002921 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002922 }
2923 if (what & layer_state_t::eLayerChanged) {
2924 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 const auto& p = layer->getParent();
2926 if (p == nullptr) {
2927 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2928 if (layer->setLayer(s.z) && idx >= 0) {
2929 mCurrentState.layersSortedByZ.removeAt(idx);
2930 mCurrentState.layersSortedByZ.add(layer);
2931 // we need traversal (state changed)
2932 // AND transaction (list changed)
2933 flags |= eTransactionNeeded|eTraversalNeeded;
2934 }
2935 } else {
2936 if (p->setChildLayer(layer, s.z)) {
2937 flags |= eTransactionNeeded|eTraversalNeeded;
2938 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002939 }
2940 }
Robert Carrdb66e622017-04-10 16:55:57 -07002941 if (what & layer_state_t::eRelativeLayerChanged) {
2942 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2943 flags |= eTransactionNeeded|eTraversalNeeded;
2944 }
2945 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002946 if (what & layer_state_t::eSizeChanged) {
2947 if (layer->setSize(s.w, s.h)) {
2948 flags |= eTraversalNeeded;
2949 }
2950 }
2951 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002952 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002953 flags |= eTraversalNeeded;
2954 }
2955 if (what & layer_state_t::eMatrixChanged) {
2956 if (layer->setMatrix(s.matrix))
2957 flags |= eTraversalNeeded;
2958 }
2959 if (what & layer_state_t::eTransparentRegionChanged) {
2960 if (layer->setTransparentRegionHint(s.transparentRegion))
2961 flags |= eTraversalNeeded;
2962 }
Dan Stoza23116082015-06-18 14:58:39 -07002963 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002964 if (layer->setFlags(s.flags, s.mask))
2965 flags |= eTraversalNeeded;
2966 }
2967 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002968 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 flags |= eTraversalNeeded;
2970 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002971 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002972 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002973 flags |= eTraversalNeeded;
2974 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002975 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002976 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002977 // We only allow setting layer stacks for top level layers,
2978 // everything else inherits layer stack from its parent.
2979 if (layer->hasParent()) {
2980 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2981 layer->getName().string());
2982 } else if (idx < 0) {
2983 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2984 "that also does not appear in the top level layer list. Something"
2985 " has gone wrong.", layer->getName().string());
2986 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002987 mCurrentState.layersSortedByZ.removeAt(idx);
2988 mCurrentState.layersSortedByZ.add(layer);
2989 // we need traversal (state changed)
2990 // AND transaction (list changed)
2991 flags |= eTransactionNeeded|eTraversalNeeded;
2992 }
2993 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002994 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08002995 if (s.barrierHandle != nullptr) {
2996 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
2997 } else if (s.barrierGbp != nullptr) {
2998 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
2999 if (authenticateSurfaceTextureLocked(gbp)) {
3000 const auto& otherLayer =
3001 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3002 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3003 } else {
3004 ALOGE("Attempt to defer transaction to to an"
3005 " unrecognized GraphicBufferProducer");
3006 }
3007 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003008 // We don't trigger a traversal here because if no other state is
3009 // changed, we don't want this to cause any more work
3010 }
Robert Carr1db73f62016-12-21 12:58:51 -08003011 if (what & layer_state_t::eReparentChildren) {
3012 if (layer->reparentChildren(s.reparentHandle)) {
3013 flags |= eTransactionNeeded|eTraversalNeeded;
3014 }
3015 }
Robert Carr9524cb32017-02-13 11:32:32 -08003016 if (what & layer_state_t::eDetachChildren) {
3017 layer->detachChildren();
3018 }
Robert Carrc3574f72016-03-24 12:19:32 -07003019 if (what & layer_state_t::eOverrideScalingModeChanged) {
3020 layer->setOverrideScalingMode(s.overrideScalingMode);
3021 // We don't trigger a traversal here because if no other state is
3022 // changed, we don't want this to cause any more work
3023 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003024 }
3025 return flags;
3026}
3027
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003028status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003029 const String8& name,
3030 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003031 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003032 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3033 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003035 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003036 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003037 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003038 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003039 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003040
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003041 status_t result = NO_ERROR;
3042
3043 sp<Layer> layer;
3044
Cody Northropbc755282017-03-31 12:00:08 -06003045 String8 uniqueName = getUniqueLayerName(name);
3046
Mathias Agopian3165cc22012-08-08 19:42:09 -07003047 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3048 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003049 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003050 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003051 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003052 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003053 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003054 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003055 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003056 handle, gbp, &layer);
3057 break;
3058 default:
3059 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 break;
3061 }
3062
Dan Stoza7d89d062015-04-30 13:29:25 -07003063 if (result != NO_ERROR) {
3064 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003065 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003066
Albert Chaulk479c60c2017-01-27 14:21:34 -05003067 layer->setInfo(windowType, ownerUid);
3068
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003070 if (result != NO_ERROR) {
3071 return result;
3072 }
Irvelffc9efc2016-07-27 15:16:37 -07003073 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003074
3075 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003076 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003077}
3078
Cody Northropbc755282017-03-31 12:00:08 -06003079String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3080{
3081 bool matchFound = true;
3082 uint32_t dupeCounter = 0;
3083
3084 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3085 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3086
3087 // Loop over layers until we're sure there is no matching name
3088 while (matchFound) {
3089 matchFound = false;
3090 mDrawingState.traverseInZOrder([&](Layer* layer) {
3091 if (layer->getName() == uniqueName) {
3092 matchFound = true;
3093 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3094 }
3095 });
3096 }
3097
3098 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3099
3100 return uniqueName;
3101}
3102
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003103status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3104 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3105 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106{
3107 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003108 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 case PIXEL_FORMAT_TRANSPARENT:
3110 case PIXEL_FORMAT_TRANSLUCENT:
3111 format = PIXEL_FORMAT_RGBA_8888;
3112 break;
3113 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003114 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003115 break;
3116 }
3117
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003118 *outLayer = new Layer(this, client, name, w, h, flags);
3119 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3120 if (err == NO_ERROR) {
3121 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003122 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003124
3125 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3126 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003127}
3128
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003129status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3130 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3131 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003132{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003133 *outLayer = new LayerDim(this, client, name, w, h, flags);
3134 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003135 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003136 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003137}
3138
Mathias Agopianac9fa422013-02-11 16:40:36 -08003139status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140{
Robert Carr9524cb32017-02-13 11:32:32 -08003141 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003142 status_t err = NO_ERROR;
3143 sp<Layer> l(client->getLayerUser(handle));
3144 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003145 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003146 err = removeLayer(l);
3147 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3148 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003149 }
3150 return err;
3151}
3152
Mathias Agopian13127d82013-03-05 17:47:11 -08003153status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003154{
Mathias Agopian67106042013-03-14 19:18:13 -07003155 // called by ~LayerCleaner() when all references to the IBinder (handle)
3156 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003157 sp<Layer> l = layer.promote();
3158 if (l == nullptr) {
3159 // The layer has already been removed, carry on
3160 return NO_ERROR;
3161 } if (l->getParent() != nullptr) {
3162 // If we have a parent, then we can continue to live as long as it does.
3163 return NO_ERROR;
3164 }
3165 return removeLayer(l);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166}
3167
Mathias Agopianb60314a2012-04-10 22:09:54 -07003168// ---------------------------------------------------------------------------
3169
Andy McFadden13a082e2012-08-24 10:16:42 -07003170void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003171 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003172 Vector<ComposerState> state;
3173 Vector<DisplayState> displays;
3174 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003175 d.what = DisplayState::eDisplayProjectionChanged |
3176 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003177 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003178 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003179 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003180 d.frame.makeInvalid();
3181 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003182 d.width = 0;
3183 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003184 displays.add(d);
3185 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003186 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003187
Dan Stoza9e56aa02015-11-02 13:00:03 -08003188 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3189 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003190 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003191
Brian Andersond0010582017-03-07 13:20:31 -08003192 // Use phase of 0 since phase is not known.
3193 // Use latency of 0, which will snap to the ideal latency.
3194 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003195}
3196
3197void SurfaceFlinger::initializeDisplays() {
3198 class MessageScreenInitialized : public MessageBase {
3199 SurfaceFlinger* flinger;
3200 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003201 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003202 virtual bool handler() {
3203 flinger->onInitializeDisplays();
3204 return true;
3205 }
3206 };
3207 sp<MessageBase> msg = new MessageScreenInitialized(this);
3208 postMessageAsync(msg); // we may be called from main thread, use async message
3209}
3210
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003211void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3212 int mode) {
3213 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3214 this);
3215 int32_t type = hw->getDisplayType();
3216 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003217
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003218 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003219 return;
3220 }
3221
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003222 hw->setPowerMode(mode);
3223 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3224 ALOGW("Trying to set power mode for virtual display");
3225 return;
3226 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003227
Irvelffc9efc2016-07-27 15:16:37 -07003228 if (mInterceptor.isEnabled()) {
3229 Mutex::Autolock _l(mStateLock);
3230 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3231 if (idx < 0) {
3232 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3233 return;
3234 }
3235 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3236 }
3237
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003238 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003239 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003240 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003241 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3242 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003243 // FIXME: eventthread only knows about the main display right now
3244 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003245 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003246 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003248 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003249 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003250 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003251
3252 struct sched_param param = {0};
3253 param.sched_priority = 1;
3254 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3255 ALOGW("Couldn't set SCHED_FIFO on display on");
3256 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003257 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003258 // Turn off the display
3259 struct sched_param param = {0};
3260 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3261 ALOGW("Couldn't set SCHED_OTHER on display off");
3262 }
3263
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003264 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003265 disableHardwareVsync(true); // also cancels any in-progress resync
3266
Mathias Agopiancde87a32012-09-13 14:09:01 -07003267 // FIXME: eventthread only knows about the main display right now
3268 mEventThread->onScreenReleased();
3269 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003270
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003271 getHwComposer().setPowerMode(type, mode);
3272 mVisibleRegionsDirty = true;
3273 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003274 } else if (mode == HWC_POWER_MODE_DOZE ||
3275 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003276 // Update display while dozing
3277 getHwComposer().setPowerMode(type, mode);
3278 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3279 // FIXME: eventthread only knows about the main display right now
3280 mEventThread->onScreenAcquired();
3281 resyncToHardwareVsync(true);
3282 }
3283 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3284 // Leave display going to doze
3285 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3286 disableHardwareVsync(true); // also cancels any in-progress resync
3287 // FIXME: eventthread only knows about the main display right now
3288 mEventThread->onScreenReleased();
3289 }
3290 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003291 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003292 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003293 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003294 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003295}
3296
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003297void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3298 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003299 SurfaceFlinger& mFlinger;
3300 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003301 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003302 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003303 MessageSetPowerMode(SurfaceFlinger& flinger,
3304 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3305 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003306 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003307 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003308 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003309 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003310 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003311 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003312 ALOGW("Attempt to set power mode = %d for virtual display",
3313 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003314 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003315 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003316 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003317 return true;
3318 }
3319 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003320 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003321 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003322}
3323
3324// ---------------------------------------------------------------------------
3325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003326status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3327{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003329
Mathias Agopianbd115332013-04-18 16:41:04 -07003330 IPCThreadState* ipc = IPCThreadState::self();
3331 const int pid = ipc->getCallingPid();
3332 const int uid = ipc->getCallingUid();
3333 if ((uid != AID_SHELL) &&
3334 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003335 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003336 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003337 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003338 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003339 // (this would indicate SF is stuck, but we want to be able to
3340 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003341 status_t err = mStateLock.timedLock(s2ns(1));
3342 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003343 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003344 result.appendFormat(
3345 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3346 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003347 }
3348
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003349 bool dumpAll = true;
3350 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003351 size_t numArgs = args.size();
3352 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003353 if ((index < numArgs) &&
3354 (args[index] == String16("--list"))) {
3355 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003356 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003357 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003358 }
3359
3360 if ((index < numArgs) &&
3361 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003362 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003363 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003364 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003365 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003366
3367 if ((index < numArgs) &&
3368 (args[index] == String16("--latency-clear"))) {
3369 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003370 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003371 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003372 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003373
3374 if ((index < numArgs) &&
3375 (args[index] == String16("--dispsync"))) {
3376 index++;
3377 mPrimaryDispSync.dump(result);
3378 dumpAll = false;
3379 }
Dan Stozab90cf072015-03-05 11:05:59 -08003380
3381 if ((index < numArgs) &&
3382 (args[index] == String16("--static-screen"))) {
3383 index++;
3384 dumpStaticScreenStats(result);
3385 dumpAll = false;
3386 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003387
3388 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003389 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003390 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003391 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003392 dumpAll = false;
3393 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003394
3395 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3396 index++;
3397 dumpWideColorInfo(result);
3398 dumpAll = false;
3399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003400 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003401
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003402 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003403 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003404 }
3405
Mathias Agopian9795c422009-08-26 16:36:26 -07003406 if (locked) {
3407 mStateLock.unlock();
3408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003409 }
3410 write(fd, result.string(), result.size());
3411 return NO_ERROR;
3412}
3413
Dan Stozac7014012014-02-14 15:03:43 -08003414void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3415 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003416{
Robert Carr2047fae2016-11-28 14:09:09 -08003417 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003418 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003419 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003420}
3421
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003422void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003423 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003424{
3425 String8 name;
3426 if (index < args.size()) {
3427 name = String8(args[index]);
3428 index++;
3429 }
3430
Dan Stoza9e56aa02015-11-02 13:00:03 -08003431 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3432 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003433 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003434
3435 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003436 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003437 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003438 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003439 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003440 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003441 }
Robert Carr2047fae2016-11-28 14:09:09 -08003442 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003443 }
3444}
3445
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003446void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003447 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003448{
3449 String8 name;
3450 if (index < args.size()) {
3451 name = String8(args[index]);
3452 index++;
3453 }
3454
Robert Carr2047fae2016-11-28 14:09:09 -08003455 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003456 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003457 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003458 }
Robert Carr2047fae2016-11-28 14:09:09 -08003459 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003460
Svetoslavd85084b2014-03-20 10:28:31 -07003461 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003462}
3463
Jamie Gennis6547ff42013-07-16 20:12:42 -07003464// This should only be called from the main thread. Otherwise it would need
3465// the lock and should use mCurrentState rather than mDrawingState.
3466void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003467 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003468 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003469 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003470
3471 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3472}
3473
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003474void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003475{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003476 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003477 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3478
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003479 if (isLayerTripleBufferingDisabled())
3480 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003481
3482 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003483 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003484 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003485 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003486 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3487 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003488 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003489}
3490
Dan Stozab90cf072015-03-05 11:05:59 -08003491void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3492{
3493 result.appendFormat("Static screen stats:\n");
3494 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3495 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3496 float percent = 100.0f *
3497 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3498 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3499 b + 1, bucketTimeSec, percent);
3500 }
3501 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3502 float percent = 100.0f *
3503 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3504 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3505 NUM_BUCKETS - 1, bucketTimeSec, percent);
3506}
3507
Dan Stozae77c7662016-05-13 11:37:28 -07003508void SurfaceFlinger::recordBufferingStats(const char* layerName,
3509 std::vector<OccupancyTracker::Segment>&& history) {
3510 Mutex::Autolock lock(mBufferingStatsMutex);
3511 auto& stats = mBufferingStats[layerName];
3512 for (const auto& segment : history) {
3513 if (!segment.usedThirdBuffer) {
3514 stats.twoBufferTime += segment.totalTime;
3515 }
3516 if (segment.occupancyAverage < 1.0f) {
3517 stats.doubleBufferedTime += segment.totalTime;
3518 } else if (segment.occupancyAverage < 2.0f) {
3519 stats.tripleBufferedTime += segment.totalTime;
3520 }
3521 ++stats.numSegments;
3522 stats.totalTime += segment.totalTime;
3523 }
3524}
3525
Brian Andersond6927fb2016-07-23 23:37:30 -07003526void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3527 result.appendFormat("Layer frame timestamps:\n");
3528
3529 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3530 const size_t count = currentLayers.size();
3531 for (size_t i=0 ; i<count ; i++) {
3532 currentLayers[i]->dumpFrameEvents(result);
3533 }
3534}
3535
Dan Stozae77c7662016-05-13 11:37:28 -07003536void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3537 result.append("Buffering stats:\n");
3538 result.append(" [Layer name] <Active time> <Two buffer> "
3539 "<Double buffered> <Triple buffered>\n");
3540 Mutex::Autolock lock(mBufferingStatsMutex);
3541 typedef std::tuple<std::string, float, float, float> BufferTuple;
3542 std::map<float, BufferTuple, std::greater<float>> sorted;
3543 for (const auto& statsPair : mBufferingStats) {
3544 const char* name = statsPair.first.c_str();
3545 const BufferingStats& stats = statsPair.second;
3546 if (stats.numSegments == 0) {
3547 continue;
3548 }
3549 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3550 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3551 stats.totalTime;
3552 float doubleBufferRatio = static_cast<float>(
3553 stats.doubleBufferedTime) / stats.totalTime;
3554 float tripleBufferRatio = static_cast<float>(
3555 stats.tripleBufferedTime) / stats.totalTime;
3556 sorted.insert({activeTime, {name, twoBufferRatio,
3557 doubleBufferRatio, tripleBufferRatio}});
3558 }
3559 for (const auto& sortedPair : sorted) {
3560 float activeTime = sortedPair.first;
3561 const BufferTuple& values = sortedPair.second;
3562 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3563 std::get<0>(values).c_str(), activeTime,
3564 std::get<1>(values), std::get<2>(values),
3565 std::get<3>(values));
3566 }
3567 result.append("\n");
3568}
3569
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003570void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3571 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3572
3573 // TODO: print out if wide-color mode is active or not
3574
3575 for (size_t d = 0; d < mDisplays.size(); d++) {
3576 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3577 int32_t hwcId = displayDevice->getHwcDisplayId();
3578 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3579 continue;
3580 }
3581
3582 result.appendFormat("Display %d color modes:\n", hwcId);
3583 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3584 for (auto&& mode : modes) {
3585 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3586 }
3587
3588 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3589 result.appendFormat(" Current color mode: %s (%d)\n",
3590 decodeColorMode(currentMode).c_str(), currentMode);
3591 }
3592 result.append("\n");
3593}
3594
Mathias Agopian74d211a2013-04-22 16:55:35 +02003595void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3596 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003597{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003598 bool colorize = false;
3599 if (index < args.size()
3600 && (args[index] == String16("--color"))) {
3601 colorize = true;
3602 index++;
3603 }
3604
3605 Colorizer colorizer(colorize);
3606
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003607 // figure out if we're stuck somewhere
3608 const nsecs_t now = systemTime();
3609 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3610 const nsecs_t inTransaction(mDebugInTransaction);
3611 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3612 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3613
3614 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003615 * Dump library configuration.
3616 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003617
3618 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003619 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003620 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003621 appendSfConfigString(result);
3622 appendUiConfigString(result);
3623 appendGuiConfigString(result);
3624 result.append("\n");
3625
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003626 result.append("\nWide-Color information:\n");
3627 dumpWideColorInfo(result);
3628
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003629 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003630 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003631 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003632 result.append(SyncFeatures::getInstance().toString());
3633 result.append("\n");
3634
Dan Stoza9e56aa02015-11-02 13:00:03 -08003635 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3636
Andy McFadden41d67d72014-04-25 16:58:34 -07003637 colorizer.bold(result);
3638 result.append("DispSync configuration: ");
3639 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003640 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003641 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003642 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003643 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003644 result.append("\n");
3645
Dan Stozab90cf072015-03-05 11:05:59 -08003646 // Dump static screen stats
3647 result.append("\n");
3648 dumpStaticScreenStats(result);
3649 result.append("\n");
3650
Dan Stozae77c7662016-05-13 11:37:28 -07003651 dumpBufferingStats(result);
3652
Andy McFadden4803b742012-09-24 19:07:20 -07003653 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003654 * Dump the visible layer list
3655 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003656 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003657 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003658 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003659 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003660 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003661 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003662
3663 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003664 * Dump Display state
3665 */
3666
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003667 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003668 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003669 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003670 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3671 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003672 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003673 }
3674
3675 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003676 * Dump SurfaceFlinger global state
3677 */
3678
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003679 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003680 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003681 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003682
Mathias Agopian888c8222012-08-04 21:10:38 -07003683 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003684 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003685
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003686 colorizer.bold(result);
3687 result.appendFormat("EGL implementation : %s\n",
3688 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3689 colorizer.reset(result);
3690 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003691 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003692
Mathias Agopian875d8e12013-06-07 15:35:48 -07003693 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003694
Mathias Agopian42977342012-08-05 00:40:46 -07003695 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003696 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3697 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003698 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003699 " last eglSwapBuffers() time: %f us\n"
3700 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003701 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003702 " refresh-rate : %f fps\n"
3703 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003704 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003705 " gpu_to_cpu_unsupported : %d\n"
3706 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003707 mLastSwapBufferTime/1000.0,
3708 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003709 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003710 1e9 / activeConfig->getVsyncPeriod(),
3711 activeConfig->getDpiX(),
3712 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003713 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003714
Mathias Agopian74d211a2013-04-22 16:55:35 +02003715 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003716 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003717
Mathias Agopian74d211a2013-04-22 16:55:35 +02003718 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003719 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003720
3721 /*
3722 * VSYNC state
3723 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003724 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003725 result.append("\n");
3726
3727 /*
3728 * HWC layer minidump
3729 */
3730 for (size_t d = 0; d < mDisplays.size(); d++) {
3731 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3732 int32_t hwcId = displayDevice->getHwcDisplayId();
3733 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3734 continue;
3735 }
3736
3737 result.appendFormat("Display %d HWC layers:\n", hwcId);
3738 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003739 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003740 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003741 });
Dan Stozae22aec72016-08-01 13:20:59 -07003742 result.append("\n");
3743 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003744
3745 /*
3746 * Dump HWComposer state
3747 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003748 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003749 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003750 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003751 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003752 result.appendFormat(" h/w composer %s\n",
3753 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003754 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003755
3756 /*
3757 * Dump gralloc state
3758 */
3759 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3760 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003761}
3762
Mathias Agopian13127d82013-03-05 17:47:11 -08003763const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003764SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003765 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003766 wp<IBinder> dpy;
3767 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3768 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3769 dpy = mDisplays.keyAt(i);
3770 break;
3771 }
3772 }
3773 if (dpy == NULL) {
3774 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3775 // Just use the primary display so we have something to return
3776 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3777 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003778 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003779}
3780
Keun young Park63f165f2012-08-31 10:53:36 -07003781bool SurfaceFlinger::startDdmConnection()
3782{
3783 void* libddmconnection_dso =
3784 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3785 if (!libddmconnection_dso) {
3786 return false;
3787 }
3788 void (*DdmConnection_start)(const char* name);
3789 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003790 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003791 if (!DdmConnection_start) {
3792 dlclose(libddmconnection_dso);
3793 return false;
3794 }
3795 (*DdmConnection_start)(getServiceName());
3796 return true;
3797}
3798
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003799status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003800 switch (code) {
3801 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003802 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003803 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003804 case CLEAR_ANIMATION_FRAME_STATS:
3805 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003806 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003807 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003808 {
3809 // codes that require permission check
3810 IPCThreadState* ipc = IPCThreadState::self();
3811 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003812 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003813 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003814 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003815 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003816 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003818 break;
3819 }
Robert Carr1db73f62016-12-21 12:58:51 -08003820 /*
3821 * Calling setTransactionState is safe, because you need to have been
3822 * granted a reference to Client* and Handle* to do anything with it.
3823 *
3824 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3825 */
3826 case SET_TRANSACTION_STATE:
3827 case CREATE_SCOPED_CONNECTION:
3828 {
3829 return OK;
3830 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003831 case CAPTURE_SCREEN:
3832 {
3833 // codes that require permission check
3834 IPCThreadState* ipc = IPCThreadState::self();
3835 const int pid = ipc->getCallingPid();
3836 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003837 if ((uid != AID_GRAPHICS) &&
3838 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003839 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003840 return PERMISSION_DENIED;
3841 }
3842 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843 }
3844 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003845 return OK;
3846}
3847
3848status_t SurfaceFlinger::onTransact(
3849 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3850{
3851 status_t credentialCheck = CheckTransactCodeCredentials(code);
3852 if (credentialCheck != OK) {
3853 return credentialCheck;
3854 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003855
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003856 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3857 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003858 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003859 IPCThreadState* ipc = IPCThreadState::self();
3860 const int uid = ipc->getCallingUid();
3861 if (CC_UNLIKELY(uid != AID_SYSTEM
3862 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003863 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003864 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003865 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003866 return PERMISSION_DENIED;
3867 }
3868 int n;
3869 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003870 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003871 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 return NO_ERROR;
3873 case 1002: // SHOW_UPDATES
3874 n = data.readInt32();
3875 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003876 invalidateHwcGeometry();
3877 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003880 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003881 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003883 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003884 setTransactionFlags(
3885 eTransactionNeeded|
3886 eDisplayTransactionNeeded|
3887 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003888 return NO_ERROR;
3889 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003890 case 1006:{ // send empty update
3891 signalRefresh();
3892 return NO_ERROR;
3893 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003894 case 1008: // toggle use of hw composer
3895 n = data.readInt32();
3896 mDebugDisableHWC = n ? 1 : 0;
3897 invalidateHwcGeometry();
3898 repaintEverything();
3899 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003900 case 1009: // toggle use of transform hint
3901 n = data.readInt32();
3902 mDebugDisableTransformHint = n ? 1 : 0;
3903 invalidateHwcGeometry();
3904 repaintEverything();
3905 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003907 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908 reply->writeInt32(0);
3909 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003910 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003911 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 return NO_ERROR;
3913 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003914 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003915 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003916 return NO_ERROR;
3917 }
3918 case 1014: {
3919 // daltonize
3920 n = data.readInt32();
3921 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003922 case 1:
3923 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3924 break;
3925 case 2:
3926 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3927 break;
3928 case 3:
3929 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3930 break;
3931 default:
3932 mDaltonizer.setType(ColorBlindnessType::None);
3933 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003934 }
3935 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003936 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003937 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003938 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003939 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003940 invalidateHwcGeometry();
3941 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003942 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003943 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003944 case 1015: {
3945 // apply a color matrix
3946 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003947 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003948 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003949 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003950 for (size_t j = 0; j < 4; j++) {
3951 mColorMatrix[i][j] = data.readFloat();
3952 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003953 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003954 } else {
3955 mColorMatrix = mat4();
3956 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003957
3958 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3959 // the division by w in the fragment shader
3960 float4 lastRow(transpose(mColorMatrix)[3]);
3961 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3962 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3963 }
3964
Alan Viverette9c5a3332013-09-12 20:04:35 -07003965 invalidateHwcGeometry();
3966 repaintEverything();
3967 return NO_ERROR;
3968 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003969 // This is an experimental interface
3970 // Needs to be shifted to proper binder interface when we productize
3971 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003972 n = data.readInt32();
3973 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003974 return NO_ERROR;
3975 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003976 case 1017: {
3977 n = data.readInt32();
3978 mForceFullDamage = static_cast<bool>(n);
3979 return NO_ERROR;
3980 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003981 case 1018: { // Modify Choreographer's phase offset
3982 n = data.readInt32();
3983 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3984 return NO_ERROR;
3985 }
3986 case 1019: { // Modify SurfaceFlinger's phase offset
3987 n = data.readInt32();
3988 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3989 return NO_ERROR;
3990 }
Irvel468051e2016-06-13 16:44:44 -07003991 case 1020: { // Layer updates interceptor
3992 n = data.readInt32();
3993 if (n) {
3994 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003995 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003996 }
3997 else{
3998 ALOGV("Interceptor disabled");
3999 mInterceptor.disable();
4000 }
4001 return NO_ERROR;
4002 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004003 case 1021: { // Disable HWC virtual displays
4004 n = data.readInt32();
4005 mUseHwcVirtualDisplays = !n;
4006 return NO_ERROR;
4007 }
Romain Guy0147a172017-06-01 13:53:56 -07004008 case 1022: { // Set saturation boost
4009 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4010
4011 invalidateHwcGeometry();
4012 repaintEverything();
4013 return NO_ERROR;
4014 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 }
4016 }
4017 return err;
4018}
4019
Mathias Agopian53331da2011-08-22 21:44:41 -07004020void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004021 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004022 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004023}
4024
Mathias Agopian59119e62010-10-11 12:37:43 -07004025// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004026// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004027// ---------------------------------------------------------------------------
4028
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004029/* The code below is here to handle b/8734824
4030 *
4031 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07004032 * from the surfaceflinger thread to the calling binder thread, where they
4033 * are executed. This allows the calling thread in the calling process to be
4034 * reused and not depend on having "enough" binder threads to handle the
4035 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004036 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004037class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07004038 /* Parts of GraphicProducerWrapper are run on two different threads,
4039 * communicating by sending messages via Looper but also by shared member
4040 * data. Coherence maintenance is subtle and in places implicit (ugh).
4041 *
4042 * Don't rely on Looper's sendMessage/handleMessage providing
4043 * release/acquire semantics for any data not actually in the Message.
4044 * Data going from surfaceflinger to binder threads needs to be
4045 * synchronized explicitly.
4046 *
4047 * Barrier open/wait do provide release/acquire semantics. This provides
4048 * implicit synchronization for data coming back from binder to
4049 * surfaceflinger threads.
4050 */
4051
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004052 sp<IGraphicBufferProducer> impl;
4053 sp<Looper> looper;
4054 status_t result;
4055 bool exitPending;
4056 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07004057 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004058 uint32_t code;
4059 Parcel const* data;
4060 Parcel* reply;
4061
4062 enum {
4063 MSG_API_CALL,
4064 MSG_EXIT
4065 };
4066
4067 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004068 * Called on surfaceflinger thread. This is called by our "fake"
4069 * BpGraphicBufferProducer. We package the data and reply Parcel and
4070 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004071 */
4072 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08004073 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004074 this->code = code;
4075 this->data = &data;
4076 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004077 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07004078 // if we've exited, we run the message synchronously right here.
4079 // note (JH): as far as I can tell from looking at the code, this
4080 // never actually happens. if it does, i'm not sure if it happens
4081 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004082 handleMessage(Message(MSG_API_CALL));
4083 } else {
4084 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07004085 // Prevent stores to this->{code, data, reply} from being
4086 // reordered later than the construction of Message.
4087 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004088 looper->sendMessage(this, Message(MSG_API_CALL));
4089 barrier.wait();
4090 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08004091 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004092 }
4093
4094 /*
Jesse Hallb154c422014-07-13 12:47:02 -07004095 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004096 * call the real BpGraphicBufferProducer.
4097 */
4098 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07004099 int what = message.what;
4100 // Prevent reads below from happening before the read from Message
4101 atomic_thread_fence(memory_order_acquire);
4102 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08004103 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004104 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07004105 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004106 exitRequested = true;
4107 }
4108 }
4109
4110public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07004111 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07004112 : impl(impl),
4113 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004114 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07004115 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07004116 exitRequested(false),
4117 code(0),
4118 data(NULL),
4119 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07004120 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004121
Jesse Hallb154c422014-07-13 12:47:02 -07004122 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004123 status_t waitForResponse() {
4124 do {
4125 looper->pollOnce(-1);
4126 } while (!exitRequested);
4127 return result;
4128 }
4129
Jesse Hallb154c422014-07-13 12:47:02 -07004130 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004131 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07004132 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004133 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07004134 // Ensure this->result is visible to the binder thread before it
4135 // handles the message.
4136 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004137 looper->sendMessage(this, Message(MSG_EXIT));
4138 }
4139};
4140
4141
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004142status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4143 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004144 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004145 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004146 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004147
4148 if (CC_UNLIKELY(display == 0))
4149 return BAD_VALUE;
4150
4151 if (CC_UNLIKELY(producer == 0))
4152 return BAD_VALUE;
4153
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004154 // if we have secure windows on this display, never allow the screen capture
4155 // unless the producer interface is local (i.e.: we can take a screenshot for
4156 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004157 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004158
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004159 // Convert to surfaceflinger's internal rotation type.
4160 Transform::orientation_flags rotationFlags;
4161 switch (rotation) {
4162 case ISurfaceComposer::eRotateNone:
4163 rotationFlags = Transform::ROT_0;
4164 break;
4165 case ISurfaceComposer::eRotate90:
4166 rotationFlags = Transform::ROT_90;
4167 break;
4168 case ISurfaceComposer::eRotate180:
4169 rotationFlags = Transform::ROT_180;
4170 break;
4171 case ISurfaceComposer::eRotate270:
4172 rotationFlags = Transform::ROT_270;
4173 break;
4174 default:
4175 rotationFlags = Transform::ROT_0;
4176 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4177 break;
4178 }
4179
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004180 class MessageCaptureScreen : public MessageBase {
4181 SurfaceFlinger* flinger;
4182 sp<IBinder> display;
4183 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07004184 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004185 uint32_t reqWidth, reqHeight;
4186 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08004187 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004188 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004189 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004190 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004191 public:
4192 MessageCaptureScreen(SurfaceFlinger* flinger,
4193 const sp<IBinder>& display,
4194 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004195 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004196 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004197 bool useIdentityTransform,
4198 Transform::orientation_flags rotation,
4199 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004200 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07004201 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004202 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08004203 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004204 rotation(rotation), result(PERMISSION_DENIED),
4205 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004206 {
4207 }
4208 status_t getResult() const {
4209 return result;
4210 }
4211 virtual bool handler() {
4212 Mutex::Autolock _l(flinger->mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004213 sp<const DisplayDevice> hw(flinger->getDisplayDeviceLocked(display));
Dan Stozac7014012014-02-14 15:03:43 -08004214 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07004215 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004216 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08004217 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004218 return true;
4219 }
4220 };
4221
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004222 // this creates a "fake" BBinder which will serve as a "fake" remote
4223 // binder to receive the marshaled calls and forward them to the
4224 // real remote (a BpGraphicBufferProducer)
4225 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
4226
4227 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
4228 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004229 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004230 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07004231 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004232 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004233
4234 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004235 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004236 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004237 }
4238 return res;
4239}
4240
Mathias Agopian180f10d2013-04-10 22:55:41 -07004241
4242void SurfaceFlinger::renderScreenImplLocked(
4243 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004244 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004245 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004246 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004247{
4248 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004249 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004250
4251 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004252 const int32_t hw_w = hw->getWidth();
4253 const int32_t hw_h = hw->getHeight();
4254 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004255 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004256
Dan Stozac1879002014-05-22 15:59:05 -07004257 // if a default or invalid sourceCrop is passed in, set reasonable values
4258 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4259 !sourceCrop.isValid()) {
4260 sourceCrop.setLeftTop(Point(0, 0));
4261 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4262 }
4263
4264 // ensure that sourceCrop is inside screen
4265 if (sourceCrop.left < 0) {
4266 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4267 }
Dan Stozabe31f442014-06-11 11:20:54 -07004268 if (sourceCrop.right > hw_w) {
4269 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004270 }
4271 if (sourceCrop.top < 0) {
4272 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4273 }
Dan Stozabe31f442014-06-11 11:20:54 -07004274 if (sourceCrop.bottom > hw_h) {
4275 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004276 }
4277
Romain Guy88d37dd2017-05-26 17:57:05 -07004278#ifdef USE_HWC2
4279 engine.setWideColor(hw->getWideColorSupport());
4280 engine.setColorMode(hw->getActiveColorMode());
4281#endif
4282
Mathias Agopian180f10d2013-04-10 22:55:41 -07004283 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004284 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004285
4286 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004287 engine.setViewportAndProjection(
4288 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004289 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004290
4291 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004292 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004293
Robert Carr1f0a16a2016-10-24 16:27:39 -07004294 // We loop through the first level of layers without traversing,
4295 // as we need to interpret min/max layer Z in the top level Z space.
4296 for (const auto& layer : mDrawingState.layersSortedByZ) {
4297 if (layer->getLayerStack() != hw->getLayerStack()) {
4298 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004299 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004300 const Layer::State& state(layer->getDrawingState());
4301 if (state.z < minLayerZ || state.z > maxLayerZ) {
4302 continue;
4303 }
Dan Stoza412903f2017-04-27 13:42:17 -07004304 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004305 if (!layer->isVisible()) {
4306 return;
4307 }
4308 if (filtering) layer->setFiltering(true);
4309 layer->draw(hw, useIdentityTransform);
4310 if (filtering) layer->setFiltering(false);
4311 });
4312 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004313
Mathias Agopian931bda12013-08-28 18:11:46 -07004314 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004315}
4316
4317
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004318status_t SurfaceFlinger::captureScreenImplLocked(
4319 const sp<const DisplayDevice>& hw,
4320 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004321 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004322 int32_t minLayerZ, int32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004323 bool useIdentityTransform, Transform::orientation_flags rotation,
4324 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004325{
4326 ATRACE_CALL();
4327
Mathias Agopian180f10d2013-04-10 22:55:41 -07004328 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07004329 uint32_t hw_w = hw->getWidth();
4330 uint32_t hw_h = hw->getHeight();
4331
4332 if (rotation & Transform::ROT_90) {
4333 std::swap(hw_w, hw_h);
4334 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004335
Mathias Agopian180f10d2013-04-10 22:55:41 -07004336 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
4337 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4338 reqWidth, reqHeight, hw_w, hw_h);
4339 return BAD_VALUE;
4340 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08004341
Mathias Agopian180f10d2013-04-10 22:55:41 -07004342 reqWidth = (!reqWidth) ? hw_w : reqWidth;
4343 reqHeight = (!reqHeight) ? hw_h : reqHeight;
4344
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004345 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004346 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004347 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004348 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4349 (state.z < minLayerZ || state.z > maxLayerZ)) {
4350 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004351 }
Dan Stoza412903f2017-04-27 13:42:17 -07004352 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004353 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4354 layer->isSecure());
4355 });
4356 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004357
4358 if (!isLocalScreenshot && secureLayerIsVisible) {
4359 ALOGW("FB is protected: PERMISSION_DENIED");
4360 return PERMISSION_DENIED;
4361 }
4362
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004363 // create a surface (because we're a producer, and we need to
4364 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07004365 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07004366
4367 // Put the screenshot Surface into async mode so that
4368 // Layer::headFenceHasSignaled will always return true and we'll latch the
4369 // first buffer regardless of whether or not its acquire fence has
4370 // signaled. This is needed to avoid a race condition in the rotation
4371 // animation. See b/30209608
4372 sur->setAsyncMode(true);
4373
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004374 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004375
Michael Lentine5a16a622015-05-21 13:48:24 -07004376 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4377 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07004378 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4379 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004380
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004381 int err = 0;
4382 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07004383 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004384 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4385 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004386
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004387 if (err == NO_ERROR) {
4388 ANativeWindowBuffer* buffer;
4389 /* TODO: Once we have the sync framework everywhere this can use
4390 * server-side waits on the fence that dequeueBuffer returns.
4391 */
4392 result = native_window_dequeue_buffer_and_wait(window, &buffer);
4393 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07004394 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004395 // create an EGLImage from the buffer so we can later
4396 // turn it into a texture
4397 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4398 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4399 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07004400 // this binds the given EGLImage as a framebuffer for the
4401 // duration of this scope.
4402 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4403 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004404 // this will in fact render into our dequeued buffer
4405 // via an FBO, which means we didn't have to create
4406 // an EGLSurface and therefore we're not
4407 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004408 renderScreenImplLocked(
4409 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4410 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07004411
Romain Guy8ec6ff22017-05-31 19:22:30 -07004412#ifdef USE_HWC2
4413 if (hasWideColorDisplay) {
4414 native_window_set_buffers_data_space(window,
4415 getRenderEngine().usesWideColor() ?
4416 HAL_DATASPACE_DISPLAY_P3 : HAL_DATASPACE_V0_SRGB);
4417 }
4418#endif
4419
Riley Andrews86639902014-08-15 12:27:24 -07004420 // Attempt to create a sync khr object that can produce a sync point. If that
4421 // isn't available, create a non-dupable sync object in the fallback path and
4422 // wait on it directly.
4423 EGLSyncKHR sync;
4424 if (!DEBUG_SCREENSHOTS) {
4425 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07004426 // native fence fd will not be populated until flush() is done.
4427 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07004428 } else {
Riley Andrews86639902014-08-15 12:27:24 -07004429 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07004430 }
Riley Andrews86639902014-08-15 12:27:24 -07004431 if (sync != EGL_NO_SYNC_KHR) {
4432 // get the sync fd
4433 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4434 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4435 ALOGW("captureScreen: failed to dup sync khr object");
4436 syncFd = -1;
4437 }
4438 eglDestroySyncKHR(mEGLDisplay, sync);
4439 } else {
4440 // fallback path
4441 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4442 if (sync != EGL_NO_SYNC_KHR) {
4443 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4444 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4445 EGLint eglErr = eglGetError();
4446 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4447 ALOGW("captureScreen: fence wait timed out");
4448 } else {
4449 ALOGW_IF(eglErr != EGL_SUCCESS,
4450 "captureScreen: error waiting on EGL fence: %#x", eglErr);
4451 }
4452 eglDestroySyncKHR(mEGLDisplay, sync);
4453 } else {
4454 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4455 }
4456 }
Mathias Agopiand5556842013-09-19 17:08:37 -07004457 if (DEBUG_SCREENSHOTS) {
4458 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4459 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4460 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4461 hw, minLayerZ, maxLayerZ);
4462 delete [] pixels;
4463 }
4464
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004465 } else {
4466 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4467 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004468 window->cancelBuffer(window, buffer, syncFd);
4469 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004470 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004471 // destroy our image
4472 eglDestroyImageKHR(mEGLDisplay, image);
4473 } else {
4474 result = BAD_VALUE;
4475 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08004476 if (buffer) {
4477 // queueBuffer takes ownership of syncFd
4478 result = window->queueBuffer(window, buffer, syncFd);
4479 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004480 }
4481 } else {
4482 result = BAD_VALUE;
4483 }
4484 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
4485 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004486
Mathias Agopian74c40c02010-09-29 13:02:36 -07004487 return result;
4488}
4489
Mathias Agopiand5556842013-09-19 17:08:37 -07004490void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004491 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004492 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004493 for (size_t y=0 ; y<h ; y++) {
4494 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4495 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004496 if (p[x] != 0xFF000000) return;
4497 }
4498 }
4499 ALOGE("*** we just took a black screenshot ***\n"
4500 "requested minz=%d, maxz=%d, layerStack=%d",
4501 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004502
Robert Carr2047fae2016-11-28 14:09:09 -08004503 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004504 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004505 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004506 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4507 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004508 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004509 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4510 layer->isVisible() ? '+' : '-',
4511 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004512 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004513 i++;
4514 });
4515 }
4516 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004517 }
4518}
4519
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004520// ---------------------------------------------------------------------------
4521
Dan Stoza412903f2017-04-27 13:42:17 -07004522void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4523 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004524}
4525
Dan Stoza412903f2017-04-27 13:42:17 -07004526void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4527 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004528}
4529
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004530}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004531
4532
4533#if defined(__gl_h_)
4534#error "don't include gl/gl.h in this file"
4535#endif
4536
4537#if defined(__gl2_h_)
4538#error "don't include gl2/gl2.h in this file"
4539#endif