blob: bd2441f6b156b26f881917227af3d9e11e5acbd8 [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>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopiana4912602012-07-12 14:25:33 -070079#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070080#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070081#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Mathias Agopianff2ed702013-09-01 21:36:12 -070083#include "Effects/Daltonizer.h"
84
Mathias Agopian875d8e12013-06-07 15:35:48 -070085#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070086#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070087
Jiyong Park4b20c2e2017-01-14 19:45:11 +090088#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090089#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#define DISPLAY_COUNT 1
92
Mathias Agopianfee2b462013-07-03 12:34:01 -070093/*
94 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
95 * black pixels.
96 */
97#define DEBUG_SCREENSHOTS false
98
Mathias Agopianca088332013-03-28 17:44:13 -070099EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700102
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107// ---------------------------------------------------------------------------
108
Mathias Agopian99b49842011-06-27 16:05:52 -0700109const String16 sHardwareTest("android.permission.HARDWARE_TEST");
110const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
111const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
112const String16 sDump("android.permission.DUMP");
113
114// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800115int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
116int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700117bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700118int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700119bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800120uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800121bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800122bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800123int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600124bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700125
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800126SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700127 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800128 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700129 mTransactionPending(false),
130 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700131 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700132 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700133 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800134 mHwc(nullptr),
135 mRealHwc(nullptr),
136 mVrHwc(nullptr),
137 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800138 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800139 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800140 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800141 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800142 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700144 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700145 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700146 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700147 mDebugInSwapBuffers(0),
148 mLastSwapBufferTime(0),
149 mDebugInTransaction(0),
150 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700151 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700152 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800153 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000154 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700155 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700156 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700157 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800158 mHasPoweredOff(false),
159 mFrameBuckets(),
160 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700161 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800162 mNumLayers(0),
163 mVrFlingerRequestsDisplay(false)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800164{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800165 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800166
167 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
168 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
169
170 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
171 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
172
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
174 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700176 useContextPriority = getBool< ISurfaceFlingerConfigs,
177 &ISurfaceFlingerConfigs::useContextPriority>(false);
178
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700179 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
180 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
181
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700182 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
183 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
184
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
186 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
187
Steven Thomas050b2c82017-03-06 11:45:16 -0800188 // Vr flinger is only enabled on Daydream ready devices.
189 useVrFlinger = getBool< ISurfaceFlingerConfigs,
190 &ISurfaceFlingerConfigs::useVrFlinger>(false);
191
Fabien Sanglard1971b632017-03-10 14:50:03 -0800192 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
193 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
194
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600195 hasWideColorDisplay =
196 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
197
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800198 // debugging stuff...
199 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700200
Mathias Agopianb4b17302013-03-20 18:36:41 -0700201 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700202 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800204 property_get("debug.sf.showupdates", value, "0");
205 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700206
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700207 property_get("debug.sf.ddms", value, "0");
208 mDebugDDMS = atoi(value);
209 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700210 if (!startDdmConnection()) {
211 // start failed, and DDMS debugging not enabled
212 mDebugDDMS = 0;
213 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700214 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700215 ALOGI_IF(mDebugRegion, "showupdates enabled");
216 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700217
218 property_get("debug.sf.disable_backpressure", value, "0");
219 mPropagateBackpressure = !atoi(value);
220 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700221
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800222 property_get("debug.sf.enable_hwc_vds", value, "0");
223 mUseHwcVirtualDisplays = atoi(value);
224 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800225
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800226 property_get("ro.sf.disable_triple_buffer", value, "1");
227 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800228 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700229
230 property_get("persist.sys.sf.color_saturation", value, "1.0");
231 mSaturation = atof(value);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800232}
233
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800234void SurfaceFlinger::onFirstRef()
235{
236 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800237}
238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800239SurfaceFlinger::~SurfaceFlinger()
240{
Mathias Agopiana4912602012-07-12 14:25:33 -0700241 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
242 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
243 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800244}
245
Dan Stozac7014012014-02-14 15:03:43 -0800246void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800247{
248 // the window manager died on us. prepare its eulogy.
249
Andy McFadden13a082e2012-08-24 10:16:42 -0700250 // restore initial conditions (default device unblank, etc)
251 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252
253 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700254 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800255}
256
Robert Carr1db73f62016-12-21 12:58:51 -0800257static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700258 status_t err = client->initCheck();
259 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800260 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800261 }
Robert Carr1db73f62016-12-21 12:58:51 -0800262 return nullptr;
263}
264
265sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
266 return initClient(new Client(this));
267}
268
269sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
270 const sp<IGraphicBufferProducer>& gbp) {
271 if (authenticateSurfaceTexture(gbp) == false) {
272 return nullptr;
273 }
274 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
275 if (layer == nullptr) {
276 return nullptr;
277 }
278
279 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800280}
281
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700282sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
283 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700284{
285 class DisplayToken : public BBinder {
286 sp<SurfaceFlinger> flinger;
287 virtual ~DisplayToken() {
288 // no more references, this display must be terminated
289 Mutex::Autolock _l(flinger->mStateLock);
290 flinger->mCurrentState.displays.removeItem(this);
291 flinger->setTransactionFlags(eDisplayTransactionNeeded);
292 }
293 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700294 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295 : flinger(flinger) {
296 }
297 };
298
299 sp<BBinder> token = new DisplayToken(this);
300
301 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700302 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700303 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700304 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700305 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700306 return token;
307}
308
Jesse Hall6c913be2013-08-08 12:15:49 -0700309void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
310 Mutex::Autolock _l(mStateLock);
311
312 ssize_t idx = mCurrentState.displays.indexOfKey(display);
313 if (idx < 0) {
314 ALOGW("destroyDisplay: invalid display token");
315 return;
316 }
317
318 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
319 if (!info.isVirtualDisplay()) {
320 ALOGE("destroyDisplay called for non-virtual display");
321 return;
322 }
Irvelffc9efc2016-07-27 15:16:37 -0700323 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700324 mCurrentState.displays.removeItemsAt(idx);
325 setTransactionFlags(eDisplayTransactionNeeded);
326}
327
Jesse Hall692c7232012-11-08 15:41:56 -0800328void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800329 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800330 ALOGW_IF(mBuiltinDisplays[type],
331 "Overwriting display token for display type %d", type);
332 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800333 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700334 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800335 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700336 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800337}
338
Mathias Agopiane57f2922012-08-09 16:29:12 -0700339sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700340 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700341 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
342 return NULL;
343 }
Jesse Hall692c7232012-11-08 15:41:56 -0800344 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700345}
346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347void SurfaceFlinger::bootFinished()
348{
Wei Wangb254fa32017-01-31 17:43:23 -0800349 if (mStartBootAnimThread->join() != NO_ERROR) {
350 ALOGE("Join StartBootAnimThread failed!");
351 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 const nsecs_t now = systemTime();
353 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000354 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700355 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700356
357 // wait patiently for the window manager death
358 const String16 name("window");
359 sp<IBinder> window(defaultServiceManager()->getService(name));
360 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700361 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700362 }
363
Steven Thomas050b2c82017-03-06 11:45:16 -0800364 if (mVrFlinger) {
365 mVrFlinger->OnBootFinished();
366 }
367
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700368 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700369 // formerly we would just kill the process, but we now ask it to exit so it
370 // can choose where to stop the animation.
371 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700372
373 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
374 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
375 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376}
377
Mathias Agopian3f844832013-08-07 21:24:32 -0700378void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700379 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700380 RenderEngine& engine;
381 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700382 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700383 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
384 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700385 }
386 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700387 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700388 return true;
389 }
390 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700391 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700392}
393
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394class DispSyncSource : public VSyncSource, private DispSync::Callback {
395public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700396 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000397 const char* name) :
398 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700399 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700400 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000401 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
402 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700403 mDispSync(dispSync),
404 mCallbackMutex(),
405 mCallback(),
406 mVsyncMutex(),
407 mPhaseOffset(phaseOffset),
408 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700409
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700410 virtual ~DispSyncSource() {}
411
412 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700413 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700414 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000415 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error registering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700421 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700422 } else {
423 status_t err = mDispSync->removeEventListener(
424 static_cast<DispSync::Callback*>(this));
425 if (err != NO_ERROR) {
426 ALOGE("error unregistering vsync callback: %s (%d)",
427 strerror(-err), err);
428 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700429 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700430 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700431 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
433
434 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 mCallback = callback;
437 }
438
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700439 virtual void setPhaseOffset(nsecs_t phaseOffset) {
440 Mutex::Autolock lock(mVsyncMutex);
441
442 // Normalize phaseOffset to [0, period)
443 auto period = mDispSync->getPeriod();
444 phaseOffset %= period;
445 if (phaseOffset < 0) {
446 // If we're here, then phaseOffset is in (-period, 0). After this
447 // operation, it will be in (0, period)
448 phaseOffset += period;
449 }
450 mPhaseOffset = phaseOffset;
451
452 // If we're not enabled, we don't need to mess with the listeners
453 if (!mEnabled) {
454 return;
455 }
456
457 // Remove the listener with the old offset
458 status_t err = mDispSync->removeEventListener(
459 static_cast<DispSync::Callback*>(this));
460 if (err != NO_ERROR) {
461 ALOGE("error unregistering vsync callback: %s (%d)",
462 strerror(-err), err);
463 }
464
465 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000466 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 static_cast<DispSync::Callback*>(this));
468 if (err != NO_ERROR) {
469 ALOGE("error registering vsync callback: %s (%d)",
470 strerror(-err), err);
471 }
472 }
473
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700474private:
475 virtual void onDispSyncEvent(nsecs_t when) {
476 sp<VSyncSource::Callback> callback;
477 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700478 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700479 callback = mCallback;
480
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700481 if (mTraceVsync) {
482 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700483 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700484 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700485 }
486
487 if (callback != NULL) {
488 callback->onVSyncEvent(when);
489 }
490 }
491
Tim Murray4a4e4a22016-04-19 16:29:23 +0000492 const char* const mName;
493
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700494 int mValue;
495
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700496 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700497 const String8 mVsyncOnLabel;
498 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700499
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700500 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700501
502 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700503 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700504
505 Mutex mVsyncMutex; // Protects the following
506 nsecs_t mPhaseOffset;
507 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700508};
509
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700510class InjectVSyncSource : public VSyncSource {
511public:
512 InjectVSyncSource() {}
513
514 virtual ~InjectVSyncSource() {}
515
516 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
517 std::lock_guard<std::mutex> lock(mCallbackMutex);
518 mCallback = callback;
519 }
520
521 virtual void onInjectSyncEvent(nsecs_t when) {
522 std::lock_guard<std::mutex> lock(mCallbackMutex);
523 mCallback->onVSyncEvent(when);
524 }
525
526 virtual void setVSyncEnabled(bool) {}
527 virtual void setPhaseOffset(nsecs_t) {}
528
529private:
530 std::mutex mCallbackMutex; // Protects the following
531 sp<VSyncSource::Callback> mCallback;
532};
533
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700534void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700535 ALOGI( "SurfaceFlinger's main thread ready to run. "
536 "Initializing graphics H/W...");
537
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900538 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
539
Dan Stoza9e56aa02015-11-02 13:00:03 -0800540 { // Autolock scope
541 Mutex::Autolock _l(mStateLock);
542
543 // initialize EGL for the default display
544 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
545 eglInitialize(mEGLDisplay, NULL, NULL);
546
547 // start the EventThread
548 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
549 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700550 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800551 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
552 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700553 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800554 mEventQueue.setEventThread(mSFEventThread);
555
Tim Murray22752852017-05-04 13:38:49 -0700556 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700557 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700558 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700559 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
560 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
561 }
Tim Murray22752852017-05-04 13:38:49 -0700562 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
563 ALOGE("Couldn't set SCHED_FIFO for EventThread");
564 }
Tim Murray41a38532016-06-22 12:42:10 -0700565
Dan Stoza9e56aa02015-11-02 13:00:03 -0800566 // Get a RenderEngine for the given display / config (can't fail)
567 mRenderEngine = RenderEngine::create(mEGLDisplay,
Kalle Raitabbdcf1f2017-05-22 15:47:46 -0700568 HAL_PIXEL_FORMAT_RGBA_8888,
569 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800570 }
571
572 // Drop the state lock while we initialize the hardware composer. We drop
573 // the lock because on creation, it will call back into SurfaceFlinger to
574 // initialize the primary display.
Steven Thomas050b2c82017-03-06 11:45:16 -0800575 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
576 "Starting with vr flinger active is not currently supported.");
Steven Thomas3cfac282017-02-06 12:29:30 -0800577 mRealHwc = new HWComposer(false);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800578 mHwc = mRealHwc;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800579 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
580
Jesse Hall692c7232012-11-08 15:41:56 -0800581 Mutex::Autolock _l(mStateLock);
582
Ian Elliott5c34de22017-04-10 14:42:30 -0600583 // Inform native graphics APIs whether the present timestamp is supported:
584 if (getHwComposer().hasCapability(
585 HWC2::Capability::PresentFenceIsNotReliable)) {
586 property_set(kTimestampProperty, "0");
587 } else {
588 property_set(kTimestampProperty, "1");
589 }
590
Steven Thomas050b2c82017-03-06 11:45:16 -0800591 if (useVrFlinger) {
592 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700593 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800594 mVrFlingerRequestsDisplay = requestDisplay;
595 signalTransaction();
596 };
597 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
598 vrFlingerRequestDisplayCallback);
599 if (!mVrFlinger) {
600 ALOGE("Failed to start vrflinger");
601 }
602 }
603
Mathias Agopian875d8e12013-06-07 15:35:48 -0700604 // retrieve the EGL context that was selected/created
605 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700606
Mathias Agopianda27af92012-09-13 18:17:13 -0700607 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
608 "couldn't create EGLContext");
609
Dan Stoza9e56aa02015-11-02 13:00:03 -0800610 // make the GLContext current so that we can create textures when creating
611 // Layers (which may happens before we render something)
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700612 getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext);
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700613
Jamie Gennisd1700752013-10-14 12:22:52 -0700614 mEventControlThread = new EventControlThread(this);
615 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
616
Mathias Agopian92a979a2012-08-02 18:32:23 -0700617 // initialize our drawing state
618 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700619
Andy McFadden13a082e2012-08-24 10:16:42 -0700620 // set initial conditions (e.g. unblank default device)
621 initializeDisplays();
622
Dan Stoza4e637772016-07-28 13:31:51 -0700623 mRenderEngine->primeCache();
624
Wei Wangb254fa32017-01-31 17:43:23 -0800625 mStartBootAnimThread = new StartBootAnimThread();
626 if (mStartBootAnimThread->Start() != NO_ERROR) {
627 ALOGE("Run StartBootAnimThread failed!");
628 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800629
Dan Stoza9e56aa02015-11-02 13:00:03 -0800630 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700631}
632
Mathias Agopiana67e4182012-06-19 17:26:12 -0700633void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800634 // Start boot animation service by setting a property mailbox
635 // if property setting thread is already running, Start() will be just a NOP
636 mStartBootAnimThread->Start();
637 // Wait until property was set
638 if (mStartBootAnimThread->join() != NO_ERROR) {
639 ALOGE("Join StartBootAnimThread failed!");
640 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700641}
642
Mathias Agopian875d8e12013-06-07 15:35:48 -0700643size_t SurfaceFlinger::getMaxTextureSize() const {
644 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700645}
646
Mathias Agopian875d8e12013-06-07 15:35:48 -0700647size_t SurfaceFlinger::getMaxViewportDims() const {
648 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700649}
650
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800651// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800652
Jamie Gennis582270d2011-08-17 18:19:00 -0700653bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800654 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800655 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800656 return authenticateSurfaceTextureLocked(bufferProducer);
657}
658
659bool SurfaceFlinger::authenticateSurfaceTextureLocked(
660 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800661 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700662 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800663}
664
Brian Anderson6b376712017-04-04 10:51:39 -0700665status_t SurfaceFlinger::getSupportedFrameTimestamps(
666 std::vector<FrameEvent>* outSupported) const {
667 *outSupported = {
668 FrameEvent::REQUESTED_PRESENT,
669 FrameEvent::ACQUIRE,
670 FrameEvent::LATCH,
671 FrameEvent::FIRST_REFRESH_START,
672 FrameEvent::LAST_REFRESH_START,
673 FrameEvent::GPU_COMPOSITION_DONE,
674 FrameEvent::DEQUEUE_READY,
675 FrameEvent::RELEASE,
676 };
677 if (!getHwComposer().hasCapability(
678 HWC2::Capability::PresentFenceIsNotReliable)) {
679 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
680 }
681 return NO_ERROR;
682}
683
Dan Stoza7f7da322014-05-02 15:26:25 -0700684status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
685 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700686 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700687 return BAD_VALUE;
688 }
689
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500690 if (!display.get())
691 return NAME_NOT_FOUND;
692
Jesse Hall692c7232012-11-08 15:41:56 -0800693 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700694 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800695 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700696 type = i;
697 break;
698 }
699 }
700
701 if (type < 0) {
702 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700703 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700704
Mathias Agopian8b736f12012-08-13 17:54:26 -0700705 // TODO: Not sure if display density should handled by SF any longer
706 class Density {
707 static int getDensityFromProperty(char const* propName) {
708 char property[PROPERTY_VALUE_MAX];
709 int density = 0;
710 if (property_get(propName, property, NULL) > 0) {
711 density = atoi(property);
712 }
713 return density;
714 }
715 public:
716 static int getEmuDensity() {
717 return getDensityFromProperty("qemu.sf.lcd_density"); }
718 static int getBuildDensity() {
719 return getDensityFromProperty("ro.sf.lcd_density"); }
720 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700721
Dan Stoza7f7da322014-05-02 15:26:25 -0700722 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700723
Dan Stoza9e56aa02015-11-02 13:00:03 -0800724 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700725 DisplayInfo info = DisplayInfo();
726
Dan Stoza9e56aa02015-11-02 13:00:03 -0800727 float xdpi = hwConfig->getDpiX();
728 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700729
730 if (type == DisplayDevice::DISPLAY_PRIMARY) {
731 // The density of the device is provided by a build property
732 float density = Density::getBuildDensity() / 160.0f;
733 if (density == 0) {
734 // the build doesn't provide a density -- this is wrong!
735 // use xdpi instead
736 ALOGE("ro.sf.lcd_density must be defined as a build property");
737 density = xdpi / 160.0f;
738 }
739 if (Density::getEmuDensity()) {
740 // if "qemu.sf.lcd_density" is specified, it overrides everything
741 xdpi = ydpi = density = Density::getEmuDensity();
742 density /= 160.0f;
743 }
744 info.density = density;
745
746 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000747 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
748 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 } else {
750 // TODO: where should this value come from?
751 static const int TV_DENSITY = 213;
752 info.density = TV_DENSITY / 160.0f;
753 info.orientation = 0;
754 }
755
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756 info.w = hwConfig->getWidth();
757 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700758 info.xdpi = xdpi;
759 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800760 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900761 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800762
Andy McFadden91b2ca82014-06-13 14:04:23 -0700763 // This is how far in advance a buffer must be queued for
764 // presentation at a given time. If you want a buffer to appear
765 // on the screen at time N, you must submit the buffer before
766 // (N - presentationDeadline).
767 //
768 // Normally it's one full refresh period (to give SF a chance to
769 // latch the buffer), but this can be reduced by configuring a
770 // DispSync offset. Any additional delays introduced by the hardware
771 // composer or panel must be accounted for here.
772 //
773 // We add an additional 1ms to allow for processing time and
774 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800776 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700777
778 // All non-virtual displays are currently considered secure.
779 info.secure = true;
780
Michael Wright28f24d02016-07-12 13:30:53 -0700781 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700782 }
783
Dan Stoza7f7da322014-05-02 15:26:25 -0700784 return NO_ERROR;
785}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700786
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800787status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700788 DisplayStatInfo* stats) {
789 if (stats == NULL) {
790 return BAD_VALUE;
791 }
792
793 // FIXME for now we always return stats for the primary display
794 memset(stats, 0, sizeof(*stats));
795 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
796 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
797 return NO_ERROR;
798}
799
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700800int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800801 if (display == NULL) {
802 ALOGE("%s : display is NULL", __func__);
803 return BAD_VALUE;
804 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700805
806 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700807 if (device != NULL) {
808 return device->getActiveConfig();
809 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700810
Dan Stoza24a42e92015-03-09 10:04:11 -0700811 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700812}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700813
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700814void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
815 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
816 this);
817 int32_t type = hw->getDisplayType();
818 int currentMode = hw->getActiveConfig();
819
820 if (mode == currentMode) {
821 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
822 return;
823 }
824
825 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
826 ALOGW("Trying to set config for virtual display");
827 return;
828 }
829
830 hw->setActiveConfig(mode);
831 getHwComposer().setActiveConfig(type, mode);
832}
833
834status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
835 class MessageSetActiveConfig: public MessageBase {
836 SurfaceFlinger& mFlinger;
837 sp<IBinder> mDisplay;
838 int mMode;
839 public:
840 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
841 int mode) :
842 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
843 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700844 Vector<DisplayInfo> configs;
845 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700846 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700847 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700848 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700849 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700850 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700851 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
852 if (hw == NULL) {
853 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700854 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700855 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
856 ALOGW("Attempt to set active config = %d for virtual display",
857 mMode);
858 } else {
859 mFlinger.setActiveConfigInternal(hw, mMode);
860 }
861 return true;
862 }
863 };
864 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
865 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700866 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700867}
Michael Wright28f24d02016-07-12 13:30:53 -0700868status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
869 Vector<android_color_mode_t>* outColorModes) {
870 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
871 return BAD_VALUE;
872 }
873
874 if (!display.get()) {
875 return NAME_NOT_FOUND;
876 }
877
878 int32_t type = NAME_NOT_FOUND;
879 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
880 if (display == mBuiltinDisplays[i]) {
881 type = i;
882 break;
883 }
884 }
885
886 if (type < 0) {
887 return type;
888 }
889
890 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
891 outColorModes->clear();
892 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
893
894 return NO_ERROR;
895}
896
897android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700898 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700899 if (device != nullptr) {
900 return device->getActiveColorMode();
901 }
902 return static_cast<android_color_mode_t>(BAD_VALUE);
903}
904
905void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
906 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700907 int32_t type = hw->getDisplayType();
908 android_color_mode_t currentMode = hw->getActiveColorMode();
909
910 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700911 return;
912 }
913
914 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
915 ALOGW("Trying to set config for virtual display");
916 return;
917 }
918
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600919 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
920 hw->getDisplayType());
921
Michael Wright28f24d02016-07-12 13:30:53 -0700922 hw->setActiveColorMode(mode);
923 getHwComposer().setActiveColorMode(type, mode);
924}
925
926
927status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
928 android_color_mode_t colorMode) {
929 class MessageSetActiveColorMode: public MessageBase {
930 SurfaceFlinger& mFlinger;
931 sp<IBinder> mDisplay;
932 android_color_mode_t mMode;
933 public:
934 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
935 android_color_mode_t mode) :
936 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
937 virtual bool handler() {
938 Vector<android_color_mode_t> modes;
939 mFlinger.getDisplayColorModes(mDisplay, &modes);
940 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
941 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600942 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
943 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700944 return true;
945 }
946 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
947 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600948 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
949 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700950 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600951 ALOGW("Attempt to set active color mode %s %d for virtual display",
952 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700953 } else {
954 mFlinger.setActiveColorModeInternal(hw, mMode);
955 }
956 return true;
957 }
958 };
959 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
960 postMessageSync(msg);
961 return NO_ERROR;
962}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700963
Svetoslavd85084b2014-03-20 10:28:31 -0700964status_t SurfaceFlinger::clearAnimationFrameStats() {
965 Mutex::Autolock _l(mStateLock);
966 mAnimFrameTracker.clearStats();
967 return NO_ERROR;
968}
969
970status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
971 Mutex::Autolock _l(mStateLock);
972 mAnimFrameTracker.getStats(outStats);
973 return NO_ERROR;
974}
975
Dan Stozac4f471e2016-03-24 09:31:08 -0700976status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
977 HdrCapabilities* outCapabilities) const {
978 Mutex::Autolock _l(mStateLock);
979
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700980 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -0700981 if (displayDevice == nullptr) {
982 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
983 return BAD_VALUE;
984 }
985
986 std::unique_ptr<HdrCapabilities> capabilities =
987 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
988 if (capabilities) {
989 std::swap(*outCapabilities, *capabilities);
990 } else {
991 return BAD_VALUE;
992 }
993
994 return NO_ERROR;
995}
996
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700997status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
998 if (enable == mInjectVSyncs) {
999 return NO_ERROR;
1000 }
1001
1002 if (enable) {
1003 mInjectVSyncs = enable;
1004 ALOGV("VSync Injections enabled");
1005 if (mVSyncInjector.get() == nullptr) {
1006 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001007 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001008 }
1009 mEventQueue.setEventThread(mInjectorEventThread);
1010 } else {
1011 mInjectVSyncs = enable;
1012 ALOGV("VSync Injections disabled");
1013 mEventQueue.setEventThread(mSFEventThread);
1014 mVSyncInjector.clear();
1015 }
1016 return NO_ERROR;
1017}
1018
1019status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1020 if (!mInjectVSyncs) {
1021 ALOGE("VSync Injections not enabled");
1022 return BAD_VALUE;
1023 }
1024 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1025 ALOGV("Injecting VSync inside SurfaceFlinger");
1026 mVSyncInjector->onInjectSyncEvent(when);
1027 }
1028 return NO_ERROR;
1029}
1030
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001031// ----------------------------------------------------------------------------
1032
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001033sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1034 ISurfaceComposer::VsyncSource vsyncSource) {
1035 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1036 return mSFEventThread->createEventConnection();
1037 } else {
1038 return mEventThread->createEventConnection();
1039 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001040}
1041
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001042// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001043
1044void SurfaceFlinger::waitForEvent() {
1045 mEventQueue.waitMessage();
1046}
1047
1048void SurfaceFlinger::signalTransaction() {
1049 mEventQueue.invalidate();
1050}
1051
1052void SurfaceFlinger::signalLayerUpdate() {
1053 mEventQueue.invalidate();
1054}
1055
1056void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001057 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001058 mEventQueue.refresh();
1059}
1060
1061status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001062 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001063 return mEventQueue.postMessage(msg, reltime);
1064}
1065
1066status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001067 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001068 status_t res = mEventQueue.postMessage(msg, reltime);
1069 if (res == NO_ERROR) {
1070 msg->wait();
1071 }
1072 return res;
1073}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001074
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001075void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001076 do {
1077 waitForEvent();
1078 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001079}
1080
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001081void SurfaceFlinger::enableHardwareVsync() {
1082 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001083 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001084 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001085 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1086 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001087 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001088 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001089}
1090
Jesse Hall948fe0c2013-10-14 12:56:09 -07001091void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001092 Mutex::Autolock _l(mHWVsyncLock);
1093
Jesse Hall948fe0c2013-10-14 12:56:09 -07001094 if (makeAvailable) {
1095 mHWVsyncAvailable = true;
1096 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001097 // Hardware vsync is not currently available, so abort the resync
1098 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001099 return;
1100 }
1101
Dan Stoza9e56aa02015-11-02 13:00:03 -08001102 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1103 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001104
1105 mPrimaryDispSync.reset();
1106 mPrimaryDispSync.setPeriod(period);
1107
1108 if (!mPrimaryHWVsyncEnabled) {
1109 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001110 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1111 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001112 mPrimaryHWVsyncEnabled = true;
1113 }
1114}
1115
Jesse Hall948fe0c2013-10-14 12:56:09 -07001116void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001117 Mutex::Autolock _l(mHWVsyncLock);
1118 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001119 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1120 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001121 mPrimaryDispSync.endResync();
1122 mPrimaryHWVsyncEnabled = false;
1123 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001124 if (makeUnavailable) {
1125 mHWVsyncAvailable = false;
1126 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001127}
1128
Tim Murray4a4e4a22016-04-19 16:29:23 +00001129void SurfaceFlinger::resyncWithRateLimit() {
1130 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001131
1132 // No explicit locking is needed here since EventThread holds a lock while calling this method
1133 static nsecs_t sLastResyncAttempted = 0;
1134 const nsecs_t now = systemTime();
1135 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001136 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001137 }
Dan Stoza57164302017-05-08 14:03:54 -07001138 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001139}
1140
Steven Thomas3cfac282017-02-06 12:29:30 -08001141void SurfaceFlinger::onVSyncReceived(HWComposer* composer, int32_t type,
1142 nsecs_t timestamp) {
1143 Mutex::Autolock lock(mStateLock);
1144 // Ignore any vsyncs from the non-active hardware composer.
1145 if (composer != mHwc) {
1146 return;
1147 }
1148
Jamie Gennisd1700752013-10-14 12:22:52 -07001149 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001150
Jamie Gennisd1700752013-10-14 12:22:52 -07001151 { // Scope for the lock
1152 Mutex::Autolock _l(mHWVsyncLock);
1153 if (type == 0 && mPrimaryHWVsyncEnabled) {
1154 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001155 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001156 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001157
1158 if (needsHwVsync) {
1159 enableHardwareVsync();
1160 } else {
1161 disableHardwareVsync(false);
1162 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001163}
1164
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001165void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001166 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001167 *compositorTiming = mCompositorTiming;
1168}
1169
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001170void SurfaceFlinger::createDefaultDisplayDevice() {
1171 const int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1172 wp<IBinder> token = mBuiltinDisplays[type];
1173
1174 // All non-virtual displays are currently considered secure.
1175 const bool isSecure = true;
1176
1177 sp<IGraphicBufferProducer> producer;
1178 sp<IGraphicBufferConsumer> consumer;
1179 BufferQueue::createBufferQueue(&producer, &consumer);
1180
1181 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1182
1183 bool hasWideColorModes = false;
1184 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1185 for (android_color_mode_t colorMode : modes) {
1186 switch (colorMode) {
1187 case HAL_COLOR_MODE_DISPLAY_P3:
1188 case HAL_COLOR_MODE_ADOBE_RGB:
1189 case HAL_COLOR_MODE_DCI_P3:
1190 hasWideColorModes = true;
1191 break;
1192 default:
1193 break;
1194 }
1195 }
1196 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1197 token, fbs, producer, mRenderEngine->getEGLConfig(),
1198 hasWideColorModes && hasWideColorDisplay);
1199 mDisplays.add(token, hw);
1200 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1201 if (hasWideColorModes && hasWideColorDisplay) {
1202 defaultColorMode = HAL_COLOR_MODE_SRGB;
1203 }
1204 setActiveColorModeInternal(hw, defaultColorMode);
1205}
1206
1207void SurfaceFlinger::onHotplugReceived(HWComposer* composer, int32_t disp, bool connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001208 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001209
1210 if (composer->isUsingVrComposer()) {
1211 // We handle initializing the primary display device for the VR
1212 // window manager hwc explicitly at the time of transition.
1213 if (disp != DisplayDevice::DISPLAY_PRIMARY) {
1214 ALOGE("External displays are not supported by the vr hardware composer.");
1215 }
1216 return;
1217 }
1218
Dan Stoza9e56aa02015-11-02 13:00:03 -08001219 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1220 Mutex::Autolock lock(mStateLock);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001221 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1222 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001223 } else {
1224 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001225 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001226 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001227 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001228 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001229 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1230 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001231 }
1232 setTransactionFlags(eDisplayTransactionNeeded);
1233
Andy McFadden9e9689c2012-10-10 18:17:51 -07001234 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001235 }
Mathias Agopian86303202012-07-24 22:46:10 -07001236}
1237
Steven Thomas3cfac282017-02-06 12:29:30 -08001238void SurfaceFlinger::onInvalidateReceived(HWComposer* composer) {
1239 Mutex::Autolock lock(mStateLock);
1240 if (composer == mHwc) {
1241 repaintEverything();
1242 } else {
1243 // This isn't from our current hardware composer. If it's a callback
1244 // from the real composer, forward the refresh request to vr
1245 // flinger. Otherwise ignore it.
1246 if (!composer->isUsingVrComposer()) {
1247 mVrFlinger->OnHardwareComposerRefresh();
1248 }
1249 }
1250}
1251
Dan Stoza9e56aa02015-11-02 13:00:03 -08001252void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001254 getHwComposer().setVsyncEnabled(disp,
1255 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001256}
1257
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001258// Note: it is assumed the caller holds |mStateLock| when this is called
1259void SurfaceFlinger::resetHwcLocked() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001260 disableHardwareVsync(true);
1261 clearHwcLayers(mDrawingState.layersSortedByZ);
1262 clearHwcLayers(mCurrentState.layersSortedByZ);
Steven Thomasf5a5f6e2017-07-17 13:59:23 -07001263 for (size_t disp = 0; disp < mDisplays.size(); ++disp) {
1264 clearHwcLayers(mDisplays[disp]->getVisibleLayersSortedByZ());
1265 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001266 // Clear the drawing state so that the logic inside of
1267 // handleTransactionLocked will fire. It will determine the delta between
1268 // mCurrentState and mDrawingState and re-apply all changes when we make the
1269 // transition.
1270 mDrawingState.displays.clear();
Alex Sakhartchoukda8490d2017-04-12 17:09:42 -04001271 // Release virtual display hwcId during vr mode transition.
1272 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1273 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1274 if (displayDevice->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL) {
1275 displayDevice->disconnect(getHwComposer());
1276 }
1277 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001278 mDisplays.clear();
1279}
1280
Steven Thomas050b2c82017-03-06 11:45:16 -08001281void SurfaceFlinger::updateVrFlinger() {
1282 if (!mVrFlinger)
1283 return;
1284 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1285 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001286 return;
1287 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001288
Steven Thomas050b2c82017-03-06 11:45:16 -08001289 if (vrFlingerRequestsDisplay && !mVrHwc) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001290 // Construct new HWComposer without holding any locks.
1291 mVrHwc = new HWComposer(true);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001292
1293 // Set up the event handlers. This step is neccessary to initialize the internal state of
1294 // the hardware composer object properly. Our callbacks are designed such that if they are
1295 // triggered between now and the point where the display is properly re-initialized, they
1296 // will not have any effect, so this is safe to do here, before the lock is aquired.
1297 mVrHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
Mark Urbanus209beca2017-02-23 11:16:04 -08001298 ALOGV("Vr HWC created");
1299 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001300
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001301 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001302
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001303 if (vrFlingerRequestsDisplay) {
1304 resetHwcLocked();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001305
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306 mHwc = mVrHwc;
1307 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001309 } else {
1310 mVrFlinger->SeizeDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001311
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001312 resetHwcLocked();
1313
1314 mHwc = mRealHwc;
1315 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001316 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001317
1318 mVisibleRegionsDirty = true;
1319 invalidateHwcGeometry();
1320
1321 // Explicitly re-initialize the primary display. This is because some other
1322 // parts of this class rely on the primary display always being available.
1323 createDefaultDisplayDevice();
1324
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001325 // Re-enable default display.
1326 sp<LambdaMessage> requestMessage = new LambdaMessage([&]() {
1327 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1328 setPowerModeInternal(hw, HWC_POWER_MODE_NORMAL);
1329
1330 // Reset the timing values to account for the period of the swapped in HWC
1331 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1332 const nsecs_t period = activeConfig->getVsyncPeriod();
1333 mAnimFrameTracker.setDisplayRefreshPeriod(period);
1334
1335 // Use phase of 0 since phase is not known.
1336 // Use latency of 0, which will snap to the ideal latency.
1337 setCompositorTimingSnapped(0, period, 0);
1338 });
1339 postMessageAsync(requestMessage);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001340
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341 android_atomic_or(1, &mRepaintEverything);
1342 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343}
1344
Mathias Agopian4fec8732012-06-29 14:12:52 -07001345void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001346 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001348 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001349 bool frameMissed = !mHadClientComposition &&
1350 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001351 (mPreviousPresentFence->getSignalTime() ==
1352 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001353 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001354 if (mPropagateBackpressure && frameMissed) {
Fabien Sanglardaf5b6b82017-02-23 11:17:11 -08001355 ALOGD("Backpressure trigger, skipping transaction & refresh!");
Dan Stoza50182882016-07-08 12:02:20 -07001356 signalLayerUpdate();
1357 break;
1358 }
1359
Steven Thomas050b2c82017-03-06 11:45:16 -08001360 // Now that we're going to make it to the handleMessageTransaction()
1361 // call below it's safe to call updateVrFlinger(), which will
1362 // potentially trigger a display handoff.
1363 updateVrFlinger();
1364
Dan Stoza6b9454d2014-11-07 16:00:59 -08001365 bool refreshNeeded = handleMessageTransaction();
1366 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001367 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001368 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001369 // Signal a refresh if a transaction modified the window state,
1370 // a new buffer was latched, or if HWC has requested a full
1371 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001372 signalRefresh();
1373 }
1374 break;
1375 }
1376 case MessageQueue::REFRESH: {
1377 handleMessageRefresh();
1378 break;
1379 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001380 }
1381}
1382
Dan Stoza6b9454d2014-11-07 16:00:59 -08001383bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001384 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001385 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001386 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001387 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001388 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001389 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001390}
1391
Dan Stoza6b9454d2014-11-07 16:00:59 -08001392bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001393 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001395}
1396
1397void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001398 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001399
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001400 mRefreshPending = false;
1401
Pablo Ceballos40845df2016-01-25 17:41:15 -08001402 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001403
Brian Andersond6927fb2016-07-23 23:37:30 -07001404 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001405 rebuildLayerStacks();
1406 setUpHWComposer();
1407 doDebugFlashRegions();
1408 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001409 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001410
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001411 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001412
1413 mHadClientComposition = false;
1414 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1415 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1416 mHadClientComposition = mHadClientComposition ||
1417 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1418 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001419
Dan Stoza9e56aa02015-11-02 13:00:03 -08001420 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001421}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001422
Mathias Agopiancd60f992012-08-16 16:28:27 -07001423void SurfaceFlinger::doDebugFlashRegions()
1424{
1425 // is debugging enabled
1426 if (CC_LIKELY(!mDebugRegion))
1427 return;
1428
1429 const bool repaintEverything = mRepaintEverything;
1430 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1431 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001432 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001433 // transform the dirty region into this screen's coordinate space
1434 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1435 if (!dirtyRegion.isEmpty()) {
1436 // redraw the whole screen
1437 doComposeSurfaces(hw, Region(hw->bounds()));
1438
1439 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001440 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001441 RenderEngine& engine(getRenderEngine());
1442 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1443
Mathias Agopianda27af92012-09-13 18:17:13 -07001444 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001445 }
1446 }
1447 }
1448
1449 postFramebuffer();
1450
1451 if (mDebugRegion > 1) {
1452 usleep(mDebugRegion * 1000);
1453 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001454
Dan Stoza9e56aa02015-11-02 13:00:03 -08001455 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001456 auto& displayDevice = mDisplays[displayId];
1457 if (!displayDevice->isDisplayOn()) {
1458 continue;
1459 }
1460
1461 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001462 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1463 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001464 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465}
1466
Brian Andersond6927fb2016-07-23 23:37:30 -07001467void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001468{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001469 ATRACE_CALL();
1470 ALOGV("preComposition");
1471
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001473 mDrawingState.traverseInZOrder([&](Layer* layer) {
1474 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001475 needExtraInvalidate = true;
1476 }
Robert Carr2047fae2016-11-28 14:09:09 -08001477 });
1478
Mathias Agopiancd60f992012-08-16 16:28:27 -07001479 if (needExtraInvalidate) {
1480 signalLayerUpdate();
1481 }
1482}
1483
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001484void SurfaceFlinger::updateCompositorTiming(
1485 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1486 std::shared_ptr<FenceTime>& presentFenceTime) {
1487 // Update queue of past composite+present times and determine the
1488 // most recently known composite to present latency.
1489 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1490 nsecs_t compositeToPresentLatency = -1;
1491 while (!mCompositePresentTimes.empty()) {
1492 CompositePresentTime& cpt = mCompositePresentTimes.front();
1493 // Cached values should have been updated before calling this method,
1494 // which helps avoid duplicate syscalls.
1495 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1496 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1497 break;
1498 }
1499 compositeToPresentLatency = displayTime - cpt.composite;
1500 mCompositePresentTimes.pop();
1501 }
1502
1503 // Don't let mCompositePresentTimes grow unbounded, just in case.
1504 while (mCompositePresentTimes.size() > 16) {
1505 mCompositePresentTimes.pop();
1506 }
1507
Brian Andersond0010582017-03-07 13:20:31 -08001508 setCompositorTimingSnapped(
1509 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1510}
1511
1512void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1513 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001514 // Integer division and modulo round toward 0 not -inf, so we need to
1515 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001516 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001517 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1518 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1519
Brian Andersond0010582017-03-07 13:20:31 -08001520 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1521 if (idealLatency <= 0) {
1522 idealLatency = vsyncInterval;
1523 }
1524
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001525 // Snap the latency to a value that removes scheduling jitter from the
1526 // composition and present times, which often have >1ms of jitter.
1527 // Reducing jitter is important if an app attempts to extrapolate
1528 // something (such as user input) to an accurate diasplay time.
1529 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1530 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001531 nsecs_t bias = vsyncInterval / 2;
1532 int64_t extraVsyncs =
1533 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1534 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1535 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536
Brian Andersond0010582017-03-07 13:20:31 -08001537 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001538 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1539 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001540 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001541}
1542
1543void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001544{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001545 ATRACE_CALL();
1546 ALOGV("postComposition");
1547
Brian Anderson3546a3f2016-07-14 11:51:14 -07001548 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001549 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001550 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001551 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001552 }
1553
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001554 // |mStateLock| not needed as we are on the main thread
1555 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001556
1557 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1558 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1559 glCompositionDoneFenceTime =
1560 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1561 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1562 } else {
1563 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1564 }
1565 mGlCompositionDoneTimeline.updateSignalTimes();
1566
Brian Anderson4e606e32017-03-16 15:34:57 -07001567 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1568 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1569 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001570 mDisplayTimeline.updateSignalTimes();
1571
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001572 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1573 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1574
1575 // We use the refreshStartTime which might be sampled a little later than
1576 // when we started doing work for this frame, but that should be okay
1577 // since updateCompositorTiming has snapping logic.
1578 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001579 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001580 CompositorTiming compositorTiming;
1581 {
1582 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1583 compositorTiming = mCompositorTiming;
1584 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585
Robert Carr2047fae2016-11-28 14:09:09 -08001586 mDrawingState.traverseInZOrder([&](Layer* layer) {
1587 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001588 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001589 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001590 recordBufferingStats(layer->getName().string(),
1591 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001592 }
Robert Carr2047fae2016-11-28 14:09:09 -08001593 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001594
Brian Anderson4e606e32017-03-16 15:34:57 -07001595 if (presentFence->isValid()) {
1596 if (mPrimaryDispSync.addPresentFence(presentFence)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001597 enableHardwareVsync();
1598 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001599 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001600 }
1601 }
1602
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001603 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001604 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001605 enableHardwareVsync();
1606 }
1607 }
1608
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001609 if (mAnimCompositionPending) {
1610 mAnimCompositionPending = false;
1611
Brian Anderson4e606e32017-03-16 15:34:57 -07001612 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001613 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001614 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001615 } else {
1616 // The HWC doesn't support present fences, so use the refresh
1617 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001618 nsecs_t presentTime =
1619 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001620 mAnimFrameTracker.setActualPresentTime(presentTime);
1621 }
1622 mAnimFrameTracker.advanceFrame();
1623 }
Dan Stozab90cf072015-03-05 11:05:59 -08001624
1625 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1626 return;
1627 }
1628
1629 nsecs_t currentTime = systemTime();
1630 if (mHasPoweredOff) {
1631 mHasPoweredOff = false;
1632 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001633 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001634 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001635 if (numPeriods < NUM_BUCKETS - 1) {
1636 mFrameBuckets[numPeriods] += elapsedTime;
1637 } else {
1638 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1639 }
1640 mTotalTime += elapsedTime;
1641 }
1642 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001643}
1644
1645void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001646 ATRACE_CALL();
1647 ALOGV("rebuildLayerStacks");
1648
Mathias Agopiancd60f992012-08-16 16:28:27 -07001649 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001650 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1651 ATRACE_CALL();
1652 mVisibleRegionsDirty = false;
1653 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001654
Jeff Sharkey76488112017-02-27 14:15:18 -07001655 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1656 Region opaqueRegion;
1657 Region dirtyRegion;
1658 Vector<sp<Layer>> layersSortedByZ;
1659 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1660 const Transform& tr(displayDevice->getTransform());
1661 const Rect bounds(displayDevice->getBounds());
1662 if (displayDevice->isDisplayOn()) {
1663 computeVisibleRegions(
1664 displayDevice->getLayerStack(), dirtyRegion,
1665 opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001666
Jeff Sharkey76488112017-02-27 14:15:18 -07001667 mDrawingState.traverseInZOrder([&](Layer* layer) {
1668 if (layer->getLayerStack() == displayDevice->getLayerStack()) {
1669 Region drawRegion(tr.transform(
1670 layer->visibleNonTransparentRegion));
1671 drawRegion.andSelf(bounds);
1672 if (!drawRegion.isEmpty()) {
1673 layersSortedByZ.add(layer);
1674 } else {
1675 // Clear out the HWC layer if this layer was
1676 // previously visible, but no longer is
1677 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1678 nullptr);
1679 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001680 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001681 // WM changes displayDevice->layerStack upon sleep/awake.
1682 // Here we make sure we delete the HWC layers even if
1683 // WM changed their layer stack.
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001684 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1685 nullptr);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001686 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001687 });
1688 }
1689 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1690 displayDevice->undefinedRegion.set(bounds);
1691 displayDevice->undefinedRegion.subtractSelf(
1692 tr.transform(opaqueRegion));
1693 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001694 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001695 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001697
Romain Guy0147a172017-06-01 13:53:56 -07001698mat4 SurfaceFlinger::computeSaturationMatrix() const {
1699 if (mSaturation == 1.0f) {
1700 return mat4();
1701 }
1702
1703 // Rec.709 luma coefficients
1704 float3 luminance{0.213f, 0.715f, 0.072f};
1705 luminance *= 1.0f - mSaturation;
1706 return mat4(
1707 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1708 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1709 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1710 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1711 );
1712}
1713
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001714// pickColorMode translates a given dataspace into the best available color mode.
1715// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001716android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001717 switch (dataSpace) {
1718 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1719 // system expects.
1720 case HAL_DATASPACE_UNKNOWN:
1721 case HAL_DATASPACE_SRGB:
1722 case HAL_DATASPACE_V0_SRGB:
1723 return HAL_COLOR_MODE_SRGB;
1724 break;
1725
1726 case HAL_DATASPACE_DISPLAY_P3:
1727 return HAL_COLOR_MODE_DISPLAY_P3;
1728 break;
1729
1730 default:
1731 // TODO (courtneygo): Do we want to assert an error here?
1732 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1733 dataSpace);
1734 return HAL_COLOR_MODE_SRGB;
1735 break;
1736 }
1737}
1738
Romain Guy0147a172017-06-01 13:53:56 -07001739android_dataspace SurfaceFlinger::bestTargetDataSpace(
1740 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001741 // Only support sRGB and Display-P3 right now.
1742 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1743 return HAL_DATASPACE_DISPLAY_P3;
1744 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001745 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1746 return HAL_DATASPACE_DISPLAY_P3;
1747 }
1748 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1749 return HAL_DATASPACE_DISPLAY_P3;
1750 }
1751
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001752 return HAL_DATASPACE_V0_SRGB;
1753}
1754
Mathias Agopiancd60f992012-08-16 16:28:27 -07001755void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001756 ATRACE_CALL();
1757 ALOGV("setUpHWComposer");
1758
Jesse Hall028dc8f2013-08-20 16:35:32 -07001759 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001760 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1761 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1762 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1763
1764 // If nothing has changed (!dirty), don't recompose.
1765 // If something changed, but we don't currently have any visible layers,
1766 // and didn't when we last did a composition, then skip it this time.
1767 // The second rule does two things:
1768 // - When all layers are removed from a display, we'll emit one black
1769 // frame, then nothing more until we get new layers.
1770 // - When a display is created with a private layer stack, we won't
1771 // emit any black frames until a layer is added to the layer stack.
1772 bool mustRecompose = dirty && !(empty && wasEmpty);
1773
1774 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1775 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1776 mustRecompose ? "doing" : "skipping",
1777 dirty ? "+" : "-",
1778 empty ? "+" : "-",
1779 wasEmpty ? "+" : "-");
1780
Dan Stoza71433162014-02-04 16:22:36 -08001781 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001782
1783 if (mustRecompose) {
1784 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1785 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001786 }
1787
Dan Stoza9e56aa02015-11-02 13:00:03 -08001788 // build the h/w work list
1789 if (CC_UNLIKELY(mGeometryInvalid)) {
1790 mGeometryInvalid = false;
1791 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1792 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1793 const auto hwcId = displayDevice->getHwcDisplayId();
1794 if (hwcId >= 0) {
1795 const Vector<sp<Layer>>& currentLayers(
1796 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001797 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001798 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001799 if (!layer->hasHwcLayer(hwcId)) {
1800 auto hwcLayer = mHwc->createLayer(hwcId);
1801 if (hwcLayer) {
1802 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1803 } else {
1804 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001805 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001806 }
1807 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001808
Robert Carrae060832016-11-28 10:51:00 -08001809 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001810 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001811 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001812 }
1813 }
1814 }
1815 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001816 }
Riley Andrews03414a12014-07-01 14:22:59 -07001817
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001818
Romain Guy0147a172017-06-01 13:53:56 -07001819 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001820
Dan Stoza9e56aa02015-11-02 13:00:03 -08001821 // Set the per-frame data
1822 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1823 auto& displayDevice = mDisplays[displayId];
1824 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001825
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 if (hwcId < 0) {
1827 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001828 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001829 if (colorMatrix != mPreviousColorMatrix) {
1830 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1831 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1832 "display %zd: %d", displayId, result);
1833 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1835 layer->setPerFrameData(displayDevice);
1836 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001837
1838 if (hasWideColorDisplay) {
1839 android_color_mode newColorMode;
1840 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1841
1842 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1843 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1844 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1845 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1846 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1847 }
1848 newColorMode = pickColorMode(newDataSpace);
1849
1850 setActiveColorModeInternal(displayDevice, newColorMode);
1851 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001852 }
1853
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001854 mPreviousColorMatrix = colorMatrix;
1855
Dan Stoza9e56aa02015-11-02 13:00:03 -08001856 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001857 auto& displayDevice = mDisplays[displayId];
1858 if (!displayDevice->isDisplayOn()) {
1859 continue;
1860 }
1861
1862 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1864 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001865 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001866}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001867
Mathias Agopiancd60f992012-08-16 16:28:27 -07001868void SurfaceFlinger::doComposition() {
1869 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001870 ALOGV("doComposition");
1871
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001872 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001873 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001874 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001875 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001876 // transform the dirty region into this screen's coordinate space
1877 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001878
1879 // repaint the framebuffer (if needed)
1880 doDisplayComposition(hw, dirtyRegion);
1881
Mathias Agopiancd60f992012-08-16 16:28:27 -07001882 hw->dirtyRegion.clear();
1883 hw->flip(hw->swapRegion);
1884 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001885 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001886 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001887 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001888}
1889
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001890void SurfaceFlinger::postFramebuffer()
1891{
Mathias Agopian841cde52012-03-01 15:44:37 -08001892 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001893 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001894
Mathias Agopiana44b0412011-10-16 18:46:35 -07001895 const nsecs_t now = systemTime();
1896 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001897
Dan Stoza9e56aa02015-11-02 13:00:03 -08001898 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1899 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001900 if (!displayDevice->isDisplayOn()) {
1901 continue;
1902 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001903 const auto hwcId = displayDevice->getHwcDisplayId();
1904 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001905 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001906 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001907 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001908 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1910 sp<Fence> releaseFence = Fence::NO_FENCE;
1911 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1912 releaseFence = displayDevice->getClientTargetAcquireFence();
1913 } else {
1914 auto hwcLayer = layer->getHwcLayer(hwcId);
1915 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001916 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001917 layer->onLayerDisplayed(releaseFence);
1918 }
1919 if (hwcId >= 0) {
1920 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001921 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001922 }
1923
Mathias Agopiana44b0412011-10-16 18:46:35 -07001924 mLastSwapBufferTime = systemTime() - now;
1925 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001926
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001927 // |mStateLock| not needed as we are on the main thread
1928 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001929 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1930 logFrameStats();
1931 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001932}
1933
Mathias Agopian87baae12012-07-31 12:38:26 -07001934void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001935{
Mathias Agopian841cde52012-03-01 15:44:37 -08001936 ATRACE_CALL();
1937
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001938 // here we keep a copy of the drawing state (that is the state that's
1939 // going to be overwritten by handleTransactionLocked()) outside of
1940 // mStateLock so that the side-effects of the State assignment
1941 // don't happen with mStateLock held (which can cause deadlocks).
1942 State drawingState(mDrawingState);
1943
Mathias Agopianca4d3602011-05-19 15:38:14 -07001944 Mutex::Autolock _l(mStateLock);
1945 const nsecs_t now = systemTime();
1946 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947
Mathias Agopianca4d3602011-05-19 15:38:14 -07001948 // Here we're guaranteed that some transaction flags are set
1949 // so we can call handleTransactionLocked() unconditionally.
1950 // We call getTransactionFlags(), which will also clear the flags,
1951 // with mStateLock held to guarantee that mCurrentState won't change
1952 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001953
Mathias Agopiane57f2922012-08-09 16:29:12 -07001954 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001955 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001956
Mathias Agopianca4d3602011-05-19 15:38:14 -07001957 mLastTransactionTime = systemTime() - now;
1958 mDebugInTransaction = 0;
1959 invalidateHwcGeometry();
1960 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001961}
1962
Mathias Agopian87baae12012-07-31 12:38:26 -07001963void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001964{
Dan Stoza7dde5992015-05-22 09:51:44 -07001965 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001966 mCurrentState.traverseInZOrder([](Layer* layer) {
1967 layer->notifyAvailableFrames();
1968 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001969
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001970 /*
1971 * Traversal of the children
1972 * (perform the transaction for each of them if needed)
1973 */
1974
Mathias Agopian3559b072012-08-15 13:46:03 -07001975 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001976 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001977 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001978 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001979
1980 const uint32_t flags = layer->doTransaction(0);
1981 if (flags & Layer::eVisibleRegion)
1982 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001983 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001984 }
1985
1986 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001987 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001988 */
1989
Mathias Agopiane57f2922012-08-09 16:29:12 -07001990 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001991 // here we take advantage of Vector's copy-on-write semantics to
1992 // improve performance by skipping the transaction entirely when
1993 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001994 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1995 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001996 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001998 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001999 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002000
2001 // find the displays that were removed
2002 // (ie: in drawing state but not in current state)
2003 // also handle displays that changed
2004 // (ie: displays that are in both lists)
2005 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002006 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2007 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002008 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002009 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002010 // Call makeCurrent() on the primary display so we can
2011 // be sure that nothing associated with this display
2012 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002013 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002014 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002015 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002016 if (hw != NULL)
2017 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002018 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002019 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002020 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002021 } else {
2022 ALOGW("trying to remove the main display");
2023 }
2024 } else {
2025 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002026 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002027 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002028 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2029 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002030 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002031 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002032 // recreating the DisplayDevice, so we just remove it
2033 // from the drawing state, so that it get re-added
2034 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002035 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002036 if (hw != NULL)
2037 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002038 mDisplays.removeItem(display);
2039 mDrawingState.displays.removeItemsAt(i);
2040 dc--; i--;
2041 // at this point we must loop to the next item
2042 continue;
2043 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002044
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002045 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002046 if (disp != NULL) {
2047 if (state.layerStack != draw[i].layerStack) {
2048 disp->setLayerStack(state.layerStack);
2049 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002050 if ((state.orientation != draw[i].orientation)
2051 || (state.viewport != draw[i].viewport)
2052 || (state.frame != draw[i].frame))
2053 {
2054 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002055 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002056 }
Michael Lentine47e45402014-07-18 15:34:25 -07002057 if (state.width != draw[i].width || state.height != draw[i].height) {
2058 disp->setDisplaySize(state.width, state.height);
2059 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002060 }
2061 }
2062 }
2063
2064 // find displays that were added
2065 // (ie: in current state but not in drawing state)
2066 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002067 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002068 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002069
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002070 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002071 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002072 sp<IGraphicBufferProducer> bqProducer;
2073 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002074 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002075
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002077 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002078 // Virtual displays without a surface are dormant:
2079 // they have external state (layer stack, projection,
2080 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002081 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002082
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002083 // Allow VR composer to use virtual displays.
2084 if (mUseHwcVirtualDisplays || mHwc == mVrHwc) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002085 int width = 0;
2086 int status = state.surface->query(
2087 NATIVE_WINDOW_WIDTH, &width);
2088 ALOGE_IF(status != NO_ERROR,
2089 "Unable to query width (%d)", status);
2090 int height = 0;
2091 status = state.surface->query(
2092 NATIVE_WINDOW_HEIGHT, &height);
2093 ALOGE_IF(status != NO_ERROR,
2094 "Unable to query height (%d)", status);
2095 int intFormat = 0;
2096 status = state.surface->query(
2097 NATIVE_WINDOW_FORMAT, &intFormat);
2098 ALOGE_IF(status != NO_ERROR,
2099 "Unable to query format (%d)", status);
2100 auto format = static_cast<android_pixel_format_t>(
2101 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002102
Dan Stoza8cf150a2016-08-02 10:27:31 -07002103 mHwc->allocateVirtualDisplay(width, height, &format,
2104 &hwcId);
2105 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106
Dan Stoza5cf424b2016-05-20 14:02:39 -07002107 // TODO: Plumb requested format back up to consumer
2108
Dan Stoza9e56aa02015-11-02 13:00:03 -08002109 sp<VirtualDisplaySurface> vds =
2110 new VirtualDisplaySurface(*mHwc,
2111 hwcId, state.surface, bqProducer,
2112 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002113
2114 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002115 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002116 }
2117 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002118 ALOGE_IF(state.surface!=NULL,
2119 "adding a supported display, but rendering "
2120 "surface is provided (%p), ignoring it",
2121 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002122
2123 hwcId = state.type;
2124 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2125 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002126 }
2127
2128 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002129 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002130 sp<DisplayDevice> hw =
2131 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2132 dispSurface, producer,
2133 mRenderEngine->getEGLConfig(),
2134 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002135 hw->setLayerStack(state.layerStack);
2136 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002137 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002138 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002139 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002141 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002142 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002143 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002144 }
2145 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002146 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002147 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148
Mathias Agopian84300952012-11-21 16:02:13 -08002149 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2150 // The transform hint might have changed for some layers
2151 // (either because a display has changed, or because a layer
2152 // as changed).
2153 //
2154 // Walk through all the layers in currentLayers,
2155 // and update their transform hint.
2156 //
2157 // If a layer is visible only on a single display, then that
2158 // display is used to calculate the hint, otherwise we use the
2159 // default display.
2160 //
2161 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2162 // the hint is set before we acquire a buffer from the surface texture.
2163 //
2164 // NOTE: layer transactions have taken place already, so we use their
2165 // drawing state. However, SurfaceFlinger's own transaction has not
2166 // happened yet, so we must use the current state layer list
2167 // (soon to become the drawing state list).
2168 //
2169 sp<const DisplayDevice> disp;
2170 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002171 bool first = true;
2172 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002173 // NOTE: we rely on the fact that layers are sorted by
2174 // layerStack first (so we don't have to traverse the list
2175 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002176 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002177 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002178 currentlayerStack = layerStack;
2179 // figure out if this layerstack is mirrored
2180 // (more than one display) if so, pick the default display,
2181 // if not, pick the only display it's on.
2182 disp.clear();
2183 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2184 sp<const DisplayDevice> hw(mDisplays[dpy]);
2185 if (hw->getLayerStack() == currentlayerStack) {
2186 if (disp == NULL) {
2187 disp = hw;
2188 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002189 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002190 break;
2191 }
2192 }
2193 }
2194 }
Chet Haase91d25932013-04-11 15:24:55 -07002195 if (disp == NULL) {
2196 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2197 // redraw after transform hint changes. See bug 8508397.
2198
2199 // could be null when this layer is using a layerStack
2200 // that is not visible on any display. Also can occur at
2201 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002202 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002203 }
Chet Haase91d25932013-04-11 15:24:55 -07002204 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002205
2206 first = false;
2207 });
Mathias Agopian84300952012-11-21 16:02:13 -08002208 }
2209
2210
Mathias Agopian3559b072012-08-15 13:46:03 -07002211 /*
2212 * Perform our own transaction if needed
2213 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002214
2215 if (mLayersAdded) {
2216 mLayersAdded = false;
2217 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002218 mVisibleRegionsDirty = true;
2219 }
2220
2221 // some layers might have been removed, so
2222 // we need to update the regions they're exposing.
2223 if (mLayersRemoved) {
2224 mLayersRemoved = false;
2225 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002227 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002228 // this layer is not visible anymore
2229 // TODO: we could traverse the tree from front to back and
2230 // compute the actual visible region
2231 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002232 Region visibleReg;
2233 visibleReg.set(layer->computeScreenBounds());
2234 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002235 }
Robert Carr2047fae2016-11-28 14:09:09 -08002236 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237 }
2238
2239 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002240
2241 updateCursorAsync();
2242}
2243
2244void SurfaceFlinger::updateCursorAsync()
2245{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002246 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2247 auto& displayDevice = mDisplays[displayId];
2248 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002249 continue;
2250 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002251
2252 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2253 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002254 }
2255 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002256}
2257
2258void SurfaceFlinger::commitTransaction()
2259{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002260 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002261 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262 for (const auto& l : mLayersPendingRemoval) {
2263 recordBufferingStats(l->getName().string(),
2264 l->getOccupancyHistory(true));
2265 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002266 }
2267 mLayersPendingRemoval.clear();
2268 }
2269
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002270 // If this transaction is part of a window animation then the next frame
2271 // we composite should be considered an animation as well.
2272 mAnimCompositionPending = mAnimTransactionPending;
2273
Mathias Agopian4fec8732012-06-29 14:12:52 -07002274 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002275 mDrawingState.traverseInZOrder([](Layer* layer) {
2276 layer->commitChildList();
2277 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002278 mTransactionPending = false;
2279 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002280 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281}
2282
Robert Carr2047fae2016-11-28 14:09:09 -08002283void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Mathias Agopian87baae12012-07-31 12:38:26 -07002284 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002285{
Mathias Agopian841cde52012-03-01 15:44:37 -08002286 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002287 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002288
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289 Region aboveOpaqueLayers;
2290 Region aboveCoveredLayers;
2291 Region dirty;
2292
Mathias Agopian87baae12012-07-31 12:38:26 -07002293 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294
Robert Carr2047fae2016-11-28 14:09:09 -08002295 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002297 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298
Jesse Hall01e29052013-02-19 16:13:35 -08002299 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07002300 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08002301 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002302
Mathias Agopianab028732010-03-16 16:41:46 -07002303 /*
2304 * opaqueRegion: area of a surface that is fully opaque.
2305 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002307
2308 /*
2309 * visibleRegion: area of a surface that is visible on screen
2310 * and not fully transparent. This is essentially the layer's
2311 * footprint minus the opaque regions above it.
2312 * Areas covered by a translucent surface are considered visible.
2313 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002314 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002315
2316 /*
2317 * coveredRegion: area of a surface that is covered by all
2318 * visible regions above it (which includes the translucent areas).
2319 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002321
Jesse Halla8026d22012-09-25 13:25:04 -07002322 /*
2323 * transparentRegion: area of a surface that is hinted to be completely
2324 * transparent. This is only used to tell when the layer has no visible
2325 * non-transparent regions and can be removed from the layer list. It
2326 * does not affect the visibleRegion of this layer or any layers
2327 * beneath it. The hint may not be correct if apps don't respect the
2328 * SurfaceView restrictions (which, sadly, some don't).
2329 */
2330 Region transparentRegion;
2331
Mathias Agopianab028732010-03-16 16:41:46 -07002332
2333 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002334 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002335 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002336 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002338 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002339 if (!visibleRegion.isEmpty()) {
2340 // Remove the transparent area from the visible region
2341 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002342 if (tr.preserveRects()) {
2343 // transform the transparent region
2344 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002345 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002346 // transformation too complex, can't do the
2347 // transparent region optimization.
2348 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002349 }
Mathias Agopianab028732010-03-16 16:41:46 -07002350 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351
Mathias Agopianab028732010-03-16 16:41:46 -07002352 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002353 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002354 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002355 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2356 // the opaque region is the layer's footprint
2357 opaqueRegion = visibleRegion;
2358 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 }
2360 }
2361
Mathias Agopianab028732010-03-16 16:41:46 -07002362 // Clip the covered region to the visible region
2363 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2364
2365 // Update aboveCoveredLayers for next (lower) layer
2366 aboveCoveredLayers.orSelf(visibleRegion);
2367
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002368 // subtract the opaque region covered by the layers above us
2369 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370
2371 // compute this layer's dirty region
2372 if (layer->contentDirty) {
2373 // we need to invalidate the whole region
2374 dirty = visibleRegion;
2375 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002376 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002377 layer->contentDirty = false;
2378 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002379 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002380 * the exposed region consists of two components:
2381 * 1) what's VISIBLE now and was COVERED before
2382 * 2) what's EXPOSED now less what was EXPOSED before
2383 *
2384 * note that (1) is conservative, we start with the whole
2385 * visible region but only keep what used to be covered by
2386 * something -- which mean it may have been exposed.
2387 *
2388 * (2) handles areas that were not covered by anything but got
2389 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002390 */
Mathias Agopianab028732010-03-16 16:41:46 -07002391 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002392 const Region oldVisibleRegion = layer->visibleRegion;
2393 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002394 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2395 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002396 }
2397 dirty.subtractSelf(aboveOpaqueLayers);
2398
2399 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002400 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401
Mathias Agopianab028732010-03-16 16:41:46 -07002402 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002403 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002404
Jesse Halla8026d22012-09-25 13:25:04 -07002405 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002406 layer->setVisibleRegion(visibleRegion);
2407 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002408 layer->setVisibleNonTransparentRegion(
2409 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002410 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002411
Mathias Agopian87baae12012-07-31 12:38:26 -07002412 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002413}
2414
Mathias Agopian87baae12012-07-31 12:38:26 -07002415void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
2416 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002417 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002418 const sp<DisplayDevice>& hw(mDisplays[dpy]);
2419 if (hw->getLayerStack() == layerStack) {
2420 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002421 }
2422 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002423}
2424
Dan Stoza6b9454d2014-11-07 16:00:59 -08002425bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002426{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002427 ALOGV("handlePageFlip");
2428
Brian Andersond6927fb2016-07-23 23:37:30 -07002429 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002432 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002433 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002434
2435 // Store the set of layers that need updates. This set must not change as
2436 // buffers are being latched, as this could result in a deadlock.
2437 // Example: Two producers share the same command stream and:
2438 // 1.) Layer 0 is latched
2439 // 2.) Layer 0 gets a new frame
2440 // 2.) Layer 1 gets a new frame
2441 // 3.) Layer 1 is latched.
2442 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2443 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002444 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002445 if (layer->hasQueuedFrame()) {
2446 frameQueued = true;
2447 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002448 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002449 } else {
2450 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002451 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002452 } else {
2453 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002454 }
Robert Carr2047fae2016-11-28 14:09:09 -08002455 });
2456
Dan Stoza9e56aa02015-11-02 13:00:03 -08002457 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002458 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002459 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002460 invalidateLayerStack(layer->getLayerStack(), dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002461 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002462 newDataLatched = true;
2463 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002464 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002465
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002466 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002467
2468 // If we will need to wake up at some time in the future to deal with a
2469 // queued frame that shouldn't be displayed during this vsync period, wake
2470 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002471 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002472 signalLayerUpdate();
2473 }
2474
2475 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002476 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477}
2478
Mathias Agopianad456f92011-01-13 17:53:01 -08002479void SurfaceFlinger::invalidateHwcGeometry()
2480{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002481 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002482}
2483
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002484
Fabien Sanglard830b8472016-11-30 16:35:58 -08002485void SurfaceFlinger::doDisplayComposition(
2486 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002487 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488{
Dan Stoza71433162014-02-04 16:22:36 -08002489 // We only need to actually compose the display if:
2490 // 1) It is being handled by hardware composer, which may need this to
2491 // keep its virtual display state machine in sync, or
2492 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002493 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002494 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002496 return;
2497 }
2498
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 ALOGV("doDisplayComposition");
2500
Mathias Agopian87baae12012-07-31 12:38:26 -07002501 Region dirtyRegion(inDirtyRegion);
2502
Mathias Agopianb8a55602009-06-26 19:06:36 -07002503 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002504 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002505
Fabien Sanglard830b8472016-11-30 16:35:58 -08002506 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002507 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002508 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2509 // takes a rectangle, we must make sure to update that whole
2510 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002511 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002512 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002513 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002514 // We need to redraw the rectangle that will be updated
2515 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002516 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002517 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002518 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002519 } else {
2520 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002521 dirtyRegion.set(displayDevice->bounds());
2522 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523 }
2524 }
2525
Fabien Sanglard830b8472016-11-30 16:35:58 -08002526 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002528 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002529 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002530
2531 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002532 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002533}
2534
Dan Stoza9e56aa02015-11-02 13:00:03 -08002535bool SurfaceFlinger::doComposeSurfaces(
2536 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002537{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002538 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002539
Dan Stoza9e56aa02015-11-02 13:00:03 -08002540 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002541
2542 mat4 oldColorMatrix;
2543 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2544 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2545 if (applyColorMatrix) {
2546 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2547 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2548 }
2549
Dan Stoza9e56aa02015-11-02 13:00:03 -08002550 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2551 if (hasClientComposition) {
2552 ALOGV("hasClientComposition");
2553
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002554#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002555 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002556 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002557#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002559 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002561 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002562
2563 // |mStateLock| not needed as we are on the main thread
2564 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002565 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2566 }
2567 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002568 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002569
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002570 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002571 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2572 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002573 // when using overlays, we assume a fully transparent framebuffer
2574 // NOTE: we could reduce how much we need to clear, for instance
2575 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002576 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002577 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002578 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002579 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002580 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002581 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002582
2583 // we remove the scissor part
2584 // we're left with the letterbox region
2585 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002586 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002587
2588 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002590
2591 // but limit it to the dirty region
2592 region.andSelf(dirty);
2593
Mathias Agopianb9494d52012-04-18 02:28:45 -07002594 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002595 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002596 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002597 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002598 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002599 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002600
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002602 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002603 // scissor on the main display. It should never be needed
2604 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605 const Rect& bounds(displayDevice->getBounds());
2606 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002607 if (scissor != bounds) {
2608 // scissor doesn't match the screen's dimensions, so we
2609 // need to clear everything outside of it and enable
2610 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002611
Mathias Agopianf45c5102012-10-24 16:29:17 -07002612 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002613 const uint32_t height = displayDevice->getHeight();
2614 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002615 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002616 }
2617 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002618 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002619
Mathias Agopian85d751c2012-08-29 16:59:24 -07002620 /*
2621 * and then, render the layers targeted at the framebuffer
2622 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002623
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 ALOGV("Rendering client layers");
2625 const Transform& displayTransform = displayDevice->getTransform();
2626 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002627 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628 bool firstLayer = true;
2629 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2630 const Region clip(dirty.intersect(
2631 displayTransform.transform(layer->visibleRegion)));
2632 ALOGV("Layer: %s", layer->getName().string());
2633 ALOGV(" Composition type: %s",
2634 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002635 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002636 switch (layer->getCompositionType(hwcId)) {
2637 case HWC2::Composition::Cursor:
2638 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002639 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002641 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002642 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2643 layer->isOpaque(state) && (state.alpha == 1.0f)
2644 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002645 // never clear the very first layer since we're
2646 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002647 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002648 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002649 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002650 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 case HWC2::Composition::Client: {
2652 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002653 break;
2654 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002656 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002657 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 } else {
2659 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002660 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002662 }
2663 } else {
2664 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002666 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002668 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002670 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002671 }
2672 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002673
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002674 if (applyColorMatrix) {
2675 getRenderEngine().setupColorTransform(oldColorMatrix);
2676 }
2677
Mathias Agopianf45c5102012-10-24 16:29:17 -07002678 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002680 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002681}
2682
Fabien Sanglard830b8472016-11-30 16:35:58 -08002683void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2684 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002685 RenderEngine& engine(getRenderEngine());
2686 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687}
2688
Dan Stoza7d89d062015-04-30 13:29:25 -07002689status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002690 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002691 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002692 const sp<Layer>& lbc,
2693 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002694{
Dan Stoza7d89d062015-04-30 13:29:25 -07002695 // add this layer to the current state list
2696 {
2697 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002698 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002699 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2700 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002701 return NO_MEMORY;
2702 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002703 if (parent == nullptr) {
2704 mCurrentState.layersSortedByZ.add(lbc);
2705 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002706 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2707 ALOGE("addClientLayer called with a removed parent");
2708 return NAME_NOT_FOUND;
2709 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002710 parent->addChild(lbc);
2711 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002712
Dan Stoza7d89d062015-04-30 13:29:25 -07002713 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002714 mLayersAdded = true;
2715 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002716 }
2717
Mathias Agopian96f08192010-06-02 23:28:45 -07002718 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002719 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002720
Dan Stoza7d89d062015-04-30 13:29:25 -07002721 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002722}
2723
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002724status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002725 Mutex::Autolock _l(mStateLock);
2726
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002728 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002729 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002730 if (topLevelOnly) {
2731 return NO_ERROR;
2732 }
2733
Chia-I Wu98f1c102017-05-30 14:54:08 -07002734 sp<Layer> ancestor = p;
2735 while (ancestor->getParent() != nullptr) {
2736 ancestor = ancestor->getParent();
2737 }
2738 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2739 ALOGE("removeLayer called with a layer whose parent has been removed");
2740 return NAME_NOT_FOUND;
2741 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002742
2743 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002744 } else {
2745 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002746 }
2747
Robert Carr136e2f62017-02-08 17:54:29 -08002748 // As a matter of normal operation, the LayerCleaner will produce a second
2749 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2750 // so we will succeed in promoting it, but it's already been removed
2751 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2752 // otherwise something has gone wrong and we are leaking the layer.
2753 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002754 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2755 layer->getName().string(),
2756 (p != nullptr) ? p->getName().string() : "no-parent");
2757 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002758 } else if (index < 0) {
2759 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002760 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761
2762 mLayersPendingRemoval.add(layer);
2763 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002764 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002765 setTransactionFlags(eTransactionNeeded);
2766 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002767}
2768
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002769uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002770 return android_atomic_release_load(&mTransactionFlags);
2771}
2772
Mathias Agopian3f844832013-08-07 21:24:32 -07002773uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2775}
2776
Mathias Agopian3f844832013-08-07 21:24:32 -07002777uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2779 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002780 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 }
2782 return old;
2783}
2784
Mathias Agopian8b33f032012-07-24 20:43:54 -07002785void SurfaceFlinger::setTransactionState(
2786 const Vector<ComposerState>& state,
2787 const Vector<DisplayState>& displays,
2788 uint32_t flags)
2789{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002790 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002791 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002792 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002793
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002794 if (flags & eAnimation) {
2795 // For window updates that are part of an animation we must wait for
2796 // previous animation "frames" to be handled.
2797 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002798 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002799 if (CC_UNLIKELY(err != NO_ERROR)) {
2800 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002801 // caller after a few seconds.
2802 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2803 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002804 mAnimTransactionPending = false;
2805 break;
2806 }
2807 }
2808 }
2809
Mathias Agopiane57f2922012-08-09 16:29:12 -07002810 size_t count = displays.size();
2811 for (size_t i=0 ; i<count ; i++) {
2812 const DisplayState& s(displays[i]);
2813 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002814 }
2815
Mathias Agopiane57f2922012-08-09 16:29:12 -07002816 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002817 for (size_t i=0 ; i<count ; i++) {
2818 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002819 // Here we need to check that the interface we're given is indeed
2820 // one of our own. A malicious client could give us a NULL
2821 // IInterface, or one of its own or even one of our own but a
2822 // different type. All these situations would cause us to crash.
2823 //
2824 // NOTE: it would be better to use RTTI as we could directly check
2825 // that we have a Client*. however, RTTI is disabled in Android.
2826 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002827 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002828 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002829 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002830 sp<Client> client( static_cast<Client *>(s.client.get()) );
2831 transactionFlags |= setClientStateLocked(client, s.state);
2832 }
2833 }
2834 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002835 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002836
Robert Carr2a7dbb42016-05-24 11:41:28 -07002837 // If a synchronous transaction is explicitly requested without any changes,
2838 // force a transaction anyway. This can be used as a flush mechanism for
2839 // previous async transactions.
2840 if (transactionFlags == 0 && (flags & eSynchronous)) {
2841 transactionFlags = eTransactionNeeded;
2842 }
2843
Mathias Agopian386aa982011-11-07 21:58:03 -08002844 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002845 if (mInterceptor.isEnabled()) {
2846 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2847 }
Irvel468051e2016-06-13 16:44:44 -07002848
Mathias Agopian386aa982011-11-07 21:58:03 -08002849 // this triggers the transaction
2850 setTransactionFlags(transactionFlags);
2851
2852 // if this is a synchronous transaction, wait for it to take effect
2853 // before returning.
2854 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002855 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002856 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002857 if (flags & eAnimation) {
2858 mAnimTransactionPending = true;
2859 }
2860 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002861 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2862 if (CC_UNLIKELY(err != NO_ERROR)) {
2863 // just in case something goes wrong in SF, return to the
2864 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002865 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2866 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002867 break;
2868 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002869 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 }
2871}
2872
Mathias Agopiane57f2922012-08-09 16:29:12 -07002873uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2874{
Jesse Hall9a143922012-10-04 16:29:19 -07002875 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2876 if (dpyIdx < 0)
2877 return 0;
2878
Mathias Agopiane57f2922012-08-09 16:29:12 -07002879 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002880 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002881 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002882 const uint32_t what = s.what;
2883 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002884 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002885 disp.surface = s.surface;
2886 flags |= eDisplayTransactionNeeded;
2887 }
2888 }
2889 if (what & DisplayState::eLayerStackChanged) {
2890 if (disp.layerStack != s.layerStack) {
2891 disp.layerStack = s.layerStack;
2892 flags |= eDisplayTransactionNeeded;
2893 }
2894 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002895 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002896 if (disp.orientation != s.orientation) {
2897 disp.orientation = s.orientation;
2898 flags |= eDisplayTransactionNeeded;
2899 }
2900 if (disp.frame != s.frame) {
2901 disp.frame = s.frame;
2902 flags |= eDisplayTransactionNeeded;
2903 }
2904 if (disp.viewport != s.viewport) {
2905 disp.viewport = s.viewport;
2906 flags |= eDisplayTransactionNeeded;
2907 }
2908 }
Michael Lentine47e45402014-07-18 15:34:25 -07002909 if (what & DisplayState::eDisplaySizeChanged) {
2910 if (disp.width != s.width) {
2911 disp.width = s.width;
2912 flags |= eDisplayTransactionNeeded;
2913 }
2914 if (disp.height != s.height) {
2915 disp.height = s.height;
2916 flags |= eDisplayTransactionNeeded;
2917 }
2918 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002919 }
2920 return flags;
2921}
2922
2923uint32_t SurfaceFlinger::setClientStateLocked(
2924 const sp<Client>& client,
2925 const layer_state_t& s)
2926{
2927 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002928 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002929 if (layer != 0) {
2930 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002931 bool geometryAppliesWithResize =
2932 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002934 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002935 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002936 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002937 }
2938 if (what & layer_state_t::eLayerChanged) {
2939 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002940 const auto& p = layer->getParent();
2941 if (p == nullptr) {
2942 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2943 if (layer->setLayer(s.z) && idx >= 0) {
2944 mCurrentState.layersSortedByZ.removeAt(idx);
2945 mCurrentState.layersSortedByZ.add(layer);
2946 // we need traversal (state changed)
2947 // AND transaction (list changed)
2948 flags |= eTransactionNeeded|eTraversalNeeded;
2949 }
2950 } else {
2951 if (p->setChildLayer(layer, s.z)) {
2952 flags |= eTransactionNeeded|eTraversalNeeded;
2953 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002954 }
2955 }
Robert Carrdb66e622017-04-10 16:55:57 -07002956 if (what & layer_state_t::eRelativeLayerChanged) {
2957 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2958 flags |= eTransactionNeeded|eTraversalNeeded;
2959 }
2960 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002961 if (what & layer_state_t::eSizeChanged) {
2962 if (layer->setSize(s.w, s.h)) {
2963 flags |= eTraversalNeeded;
2964 }
2965 }
2966 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002967 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002968 flags |= eTraversalNeeded;
2969 }
2970 if (what & layer_state_t::eMatrixChanged) {
2971 if (layer->setMatrix(s.matrix))
2972 flags |= eTraversalNeeded;
2973 }
2974 if (what & layer_state_t::eTransparentRegionChanged) {
2975 if (layer->setTransparentRegionHint(s.transparentRegion))
2976 flags |= eTraversalNeeded;
2977 }
Dan Stoza23116082015-06-18 14:58:39 -07002978 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002979 if (layer->setFlags(s.flags, s.mask))
2980 flags |= eTraversalNeeded;
2981 }
2982 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002983 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002984 flags |= eTraversalNeeded;
2985 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002986 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07002987 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002988 flags |= eTraversalNeeded;
2989 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002990 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002992 // We only allow setting layer stacks for top level layers,
2993 // everything else inherits layer stack from its parent.
2994 if (layer->hasParent()) {
2995 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2996 layer->getName().string());
2997 } else if (idx < 0) {
2998 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2999 "that also does not appear in the top level layer list. Something"
3000 " has gone wrong.", layer->getName().string());
3001 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 mCurrentState.layersSortedByZ.removeAt(idx);
3003 mCurrentState.layersSortedByZ.add(layer);
3004 // we need traversal (state changed)
3005 // AND transaction (list changed)
3006 flags |= eTransactionNeeded|eTraversalNeeded;
3007 }
3008 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003009 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003010 if (s.barrierHandle != nullptr) {
3011 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3012 } else if (s.barrierGbp != nullptr) {
3013 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3014 if (authenticateSurfaceTextureLocked(gbp)) {
3015 const auto& otherLayer =
3016 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3017 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3018 } else {
3019 ALOGE("Attempt to defer transaction to to an"
3020 " unrecognized GraphicBufferProducer");
3021 }
3022 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003023 // We don't trigger a traversal here because if no other state is
3024 // changed, we don't want this to cause any more work
3025 }
Robert Carr1db73f62016-12-21 12:58:51 -08003026 if (what & layer_state_t::eReparentChildren) {
3027 if (layer->reparentChildren(s.reparentHandle)) {
3028 flags |= eTransactionNeeded|eTraversalNeeded;
3029 }
3030 }
Robert Carr9524cb32017-02-13 11:32:32 -08003031 if (what & layer_state_t::eDetachChildren) {
3032 layer->detachChildren();
3033 }
Robert Carrc3574f72016-03-24 12:19:32 -07003034 if (what & layer_state_t::eOverrideScalingModeChanged) {
3035 layer->setOverrideScalingMode(s.overrideScalingMode);
3036 // We don't trigger a traversal here because if no other state is
3037 // changed, we don't want this to cause any more work
3038 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003039 }
3040 return flags;
3041}
3042
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003043status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003044 const String8& name,
3045 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003046 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003047 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3048 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003050 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003051 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003052 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003053 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003054 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003055
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003056 status_t result = NO_ERROR;
3057
3058 sp<Layer> layer;
3059
Cody Northropbc755282017-03-31 12:00:08 -06003060 String8 uniqueName = getUniqueLayerName(name);
3061
Mathias Agopian3165cc22012-08-08 19:42:09 -07003062 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3063 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003064 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003065 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003066 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003068 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003069 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003070 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003071 handle, gbp, &layer);
3072 break;
3073 default:
3074 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075 break;
3076 }
3077
Dan Stoza7d89d062015-04-30 13:29:25 -07003078 if (result != NO_ERROR) {
3079 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003081
Albert Chaulk479c60c2017-01-27 14:21:34 -05003082 layer->setInfo(windowType, ownerUid);
3083
Robert Carr1f0a16a2016-10-24 16:27:39 -07003084 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003085 if (result != NO_ERROR) {
3086 return result;
3087 }
Irvelffc9efc2016-07-27 15:16:37 -07003088 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003089
3090 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003091 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003092}
3093
Cody Northropbc755282017-03-31 12:00:08 -06003094String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3095{
3096 bool matchFound = true;
3097 uint32_t dupeCounter = 0;
3098
3099 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3100 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3101
3102 // Loop over layers until we're sure there is no matching name
3103 while (matchFound) {
3104 matchFound = false;
3105 mDrawingState.traverseInZOrder([&](Layer* layer) {
3106 if (layer->getName() == uniqueName) {
3107 matchFound = true;
3108 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3109 }
3110 });
3111 }
3112
3113 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3114
3115 return uniqueName;
3116}
3117
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003118status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3119 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3120 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121{
3122 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003123 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124 case PIXEL_FORMAT_TRANSPARENT:
3125 case PIXEL_FORMAT_TRANSLUCENT:
3126 format = PIXEL_FORMAT_RGBA_8888;
3127 break;
3128 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003129 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 break;
3131 }
3132
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003133 *outLayer = new Layer(this, client, name, w, h, flags);
3134 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3135 if (err == NO_ERROR) {
3136 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003137 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003139
3140 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3141 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142}
3143
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003144status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3145 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3146 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003148 *outLayer = new LayerDim(this, client, name, w, h, flags);
3149 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003150 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003151 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003152}
3153
Mathias Agopianac9fa422013-02-11 16:40:36 -08003154status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155{
Robert Carr9524cb32017-02-13 11:32:32 -08003156 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003157 status_t err = NO_ERROR;
3158 sp<Layer> l(client->getLayerUser(handle));
3159 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003160 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003161 err = removeLayer(l);
3162 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3163 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003164 }
3165 return err;
3166}
3167
Mathias Agopian13127d82013-03-05 17:47:11 -08003168status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003169{
Mathias Agopian67106042013-03-14 19:18:13 -07003170 // called by ~LayerCleaner() when all references to the IBinder (handle)
3171 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003172 sp<Layer> l = layer.promote();
3173 if (l == nullptr) {
3174 // The layer has already been removed, carry on
3175 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003176 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003177 // If we have a parent, then we can continue to live as long as it does.
3178 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179}
3180
Mathias Agopianb60314a2012-04-10 22:09:54 -07003181// ---------------------------------------------------------------------------
3182
Andy McFadden13a082e2012-08-24 10:16:42 -07003183void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003184 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003185 Vector<ComposerState> state;
3186 Vector<DisplayState> displays;
3187 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003188 d.what = DisplayState::eDisplayProjectionChanged |
3189 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003190 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003191 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003192 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003193 d.frame.makeInvalid();
3194 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003195 d.width = 0;
3196 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003197 displays.add(d);
3198 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003199 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003200
Dan Stoza9e56aa02015-11-02 13:00:03 -08003201 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3202 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003203 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003204
Brian Andersond0010582017-03-07 13:20:31 -08003205 // Use phase of 0 since phase is not known.
3206 // Use latency of 0, which will snap to the ideal latency.
3207 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003208}
3209
3210void SurfaceFlinger::initializeDisplays() {
3211 class MessageScreenInitialized : public MessageBase {
3212 SurfaceFlinger* flinger;
3213 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003214 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003215 virtual bool handler() {
3216 flinger->onInitializeDisplays();
3217 return true;
3218 }
3219 };
3220 sp<MessageBase> msg = new MessageScreenInitialized(this);
3221 postMessageAsync(msg); // we may be called from main thread, use async message
3222}
3223
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003224void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3225 int mode) {
3226 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3227 this);
3228 int32_t type = hw->getDisplayType();
3229 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003230
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003231 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003232 return;
3233 }
3234
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003235 hw->setPowerMode(mode);
3236 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3237 ALOGW("Trying to set power mode for virtual display");
3238 return;
3239 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003240
Irvelffc9efc2016-07-27 15:16:37 -07003241 if (mInterceptor.isEnabled()) {
3242 Mutex::Autolock _l(mStateLock);
3243 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3244 if (idx < 0) {
3245 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3246 return;
3247 }
3248 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3249 }
3250
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003251 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003252 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003253 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003254 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3255 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003256 // FIXME: eventthread only knows about the main display right now
3257 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003258 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003261 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003262 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003263 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003264
3265 struct sched_param param = {0};
3266 param.sched_priority = 1;
3267 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3268 ALOGW("Couldn't set SCHED_FIFO on display on");
3269 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003270 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003271 // Turn off the display
3272 struct sched_param param = {0};
3273 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3274 ALOGW("Couldn't set SCHED_OTHER on display off");
3275 }
3276
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003277 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003278 disableHardwareVsync(true); // also cancels any in-progress resync
3279
Mathias Agopiancde87a32012-09-13 14:09:01 -07003280 // FIXME: eventthread only knows about the main display right now
3281 mEventThread->onScreenReleased();
3282 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003283
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003284 getHwComposer().setPowerMode(type, mode);
3285 mVisibleRegionsDirty = true;
3286 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003287 } else if (mode == HWC_POWER_MODE_DOZE ||
3288 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003289 // Update display while dozing
3290 getHwComposer().setPowerMode(type, mode);
3291 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3292 // FIXME: eventthread only knows about the main display right now
3293 mEventThread->onScreenAcquired();
3294 resyncToHardwareVsync(true);
3295 }
3296 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3297 // Leave display going to doze
3298 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3299 disableHardwareVsync(true); // also cancels any in-progress resync
3300 // FIXME: eventthread only knows about the main display right now
3301 mEventThread->onScreenReleased();
3302 }
3303 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003304 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003305 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003306 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003307 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003308}
3309
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003310void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3311 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003312 SurfaceFlinger& mFlinger;
3313 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003314 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003315 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003316 MessageSetPowerMode(SurfaceFlinger& flinger,
3317 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3318 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003319 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003320 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003321 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003322 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003323 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003324 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003325 ALOGW("Attempt to set power mode = %d for virtual display",
3326 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003327 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003328 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003329 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003330 return true;
3331 }
3332 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003333 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003334 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003335}
3336
3337// ---------------------------------------------------------------------------
3338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003339status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3340{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003341 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003342
Mathias Agopianbd115332013-04-18 16:41:04 -07003343 IPCThreadState* ipc = IPCThreadState::self();
3344 const int pid = ipc->getCallingPid();
3345 const int uid = ipc->getCallingUid();
3346 if ((uid != AID_SHELL) &&
3347 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003348 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003349 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003351 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003352 // (this would indicate SF is stuck, but we want to be able to
3353 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003354 status_t err = mStateLock.timedLock(s2ns(1));
3355 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003356 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003357 result.appendFormat(
3358 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3359 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003360 }
3361
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003362 bool dumpAll = true;
3363 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003364 size_t numArgs = args.size();
3365 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003366 if ((index < numArgs) &&
3367 (args[index] == String16("--list"))) {
3368 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003369 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003370 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003371 }
3372
3373 if ((index < numArgs) &&
3374 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003375 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003376 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003377 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003378 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003379
3380 if ((index < numArgs) &&
3381 (args[index] == String16("--latency-clear"))) {
3382 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003383 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003384 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003385 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003386
3387 if ((index < numArgs) &&
3388 (args[index] == String16("--dispsync"))) {
3389 index++;
3390 mPrimaryDispSync.dump(result);
3391 dumpAll = false;
3392 }
Dan Stozab90cf072015-03-05 11:05:59 -08003393
3394 if ((index < numArgs) &&
3395 (args[index] == String16("--static-screen"))) {
3396 index++;
3397 dumpStaticScreenStats(result);
3398 dumpAll = false;
3399 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003400
3401 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003402 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003403 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003404 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003405 dumpAll = false;
3406 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003407
3408 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3409 index++;
3410 dumpWideColorInfo(result);
3411 dumpAll = false;
3412 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003414
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003415 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003416 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003417 }
3418
Mathias Agopian9795c422009-08-26 16:36:26 -07003419 if (locked) {
3420 mStateLock.unlock();
3421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003422 }
3423 write(fd, result.string(), result.size());
3424 return NO_ERROR;
3425}
3426
Dan Stozac7014012014-02-14 15:03:43 -08003427void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3428 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003429{
Robert Carr2047fae2016-11-28 14:09:09 -08003430 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003431 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003432 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003433}
3434
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003435void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003436 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003437{
3438 String8 name;
3439 if (index < args.size()) {
3440 name = String8(args[index]);
3441 index++;
3442 }
3443
Dan Stoza9e56aa02015-11-02 13:00:03 -08003444 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3445 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003446 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003447
3448 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003449 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003450 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003451 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003452 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003453 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003454 }
Robert Carr2047fae2016-11-28 14:09:09 -08003455 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003456 }
3457}
3458
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003459void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003460 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003461{
3462 String8 name;
3463 if (index < args.size()) {
3464 name = String8(args[index]);
3465 index++;
3466 }
3467
Robert Carr2047fae2016-11-28 14:09:09 -08003468 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003469 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003470 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003471 }
Robert Carr2047fae2016-11-28 14:09:09 -08003472 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003473
Svetoslavd85084b2014-03-20 10:28:31 -07003474 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003475}
3476
Jamie Gennis6547ff42013-07-16 20:12:42 -07003477// This should only be called from the main thread. Otherwise it would need
3478// the lock and should use mCurrentState rather than mDrawingState.
3479void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003480 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003481 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003482 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003483
3484 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3485}
3486
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003487void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003488{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003489 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003490 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3491
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003492 if (isLayerTripleBufferingDisabled())
3493 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003494
3495 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003496 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003497 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003498 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003499 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3500 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003501 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003502}
3503
Dan Stozab90cf072015-03-05 11:05:59 -08003504void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3505{
3506 result.appendFormat("Static screen stats:\n");
3507 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3508 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3509 float percent = 100.0f *
3510 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3511 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3512 b + 1, bucketTimeSec, percent);
3513 }
3514 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3515 float percent = 100.0f *
3516 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3517 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3518 NUM_BUCKETS - 1, bucketTimeSec, percent);
3519}
3520
Dan Stozae77c7662016-05-13 11:37:28 -07003521void SurfaceFlinger::recordBufferingStats(const char* layerName,
3522 std::vector<OccupancyTracker::Segment>&& history) {
3523 Mutex::Autolock lock(mBufferingStatsMutex);
3524 auto& stats = mBufferingStats[layerName];
3525 for (const auto& segment : history) {
3526 if (!segment.usedThirdBuffer) {
3527 stats.twoBufferTime += segment.totalTime;
3528 }
3529 if (segment.occupancyAverage < 1.0f) {
3530 stats.doubleBufferedTime += segment.totalTime;
3531 } else if (segment.occupancyAverage < 2.0f) {
3532 stats.tripleBufferedTime += segment.totalTime;
3533 }
3534 ++stats.numSegments;
3535 stats.totalTime += segment.totalTime;
3536 }
3537}
3538
Brian Andersond6927fb2016-07-23 23:37:30 -07003539void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3540 result.appendFormat("Layer frame timestamps:\n");
3541
3542 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3543 const size_t count = currentLayers.size();
3544 for (size_t i=0 ; i<count ; i++) {
3545 currentLayers[i]->dumpFrameEvents(result);
3546 }
3547}
3548
Dan Stozae77c7662016-05-13 11:37:28 -07003549void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3550 result.append("Buffering stats:\n");
3551 result.append(" [Layer name] <Active time> <Two buffer> "
3552 "<Double buffered> <Triple buffered>\n");
3553 Mutex::Autolock lock(mBufferingStatsMutex);
3554 typedef std::tuple<std::string, float, float, float> BufferTuple;
3555 std::map<float, BufferTuple, std::greater<float>> sorted;
3556 for (const auto& statsPair : mBufferingStats) {
3557 const char* name = statsPair.first.c_str();
3558 const BufferingStats& stats = statsPair.second;
3559 if (stats.numSegments == 0) {
3560 continue;
3561 }
3562 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3563 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3564 stats.totalTime;
3565 float doubleBufferRatio = static_cast<float>(
3566 stats.doubleBufferedTime) / stats.totalTime;
3567 float tripleBufferRatio = static_cast<float>(
3568 stats.tripleBufferedTime) / stats.totalTime;
3569 sorted.insert({activeTime, {name, twoBufferRatio,
3570 doubleBufferRatio, tripleBufferRatio}});
3571 }
3572 for (const auto& sortedPair : sorted) {
3573 float activeTime = sortedPair.first;
3574 const BufferTuple& values = sortedPair.second;
3575 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3576 std::get<0>(values).c_str(), activeTime,
3577 std::get<1>(values), std::get<2>(values),
3578 std::get<3>(values));
3579 }
3580 result.append("\n");
3581}
3582
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003583void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3584 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3585
3586 // TODO: print out if wide-color mode is active or not
3587
3588 for (size_t d = 0; d < mDisplays.size(); d++) {
3589 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3590 int32_t hwcId = displayDevice->getHwcDisplayId();
3591 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3592 continue;
3593 }
3594
3595 result.appendFormat("Display %d color modes:\n", hwcId);
3596 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3597 for (auto&& mode : modes) {
3598 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3599 }
3600
3601 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3602 result.appendFormat(" Current color mode: %s (%d)\n",
3603 decodeColorMode(currentMode).c_str(), currentMode);
3604 }
3605 result.append("\n");
3606}
3607
Mathias Agopian74d211a2013-04-22 16:55:35 +02003608void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3609 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003610{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003611 bool colorize = false;
3612 if (index < args.size()
3613 && (args[index] == String16("--color"))) {
3614 colorize = true;
3615 index++;
3616 }
3617
3618 Colorizer colorizer(colorize);
3619
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003620 // figure out if we're stuck somewhere
3621 const nsecs_t now = systemTime();
3622 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3623 const nsecs_t inTransaction(mDebugInTransaction);
3624 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3625 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3626
3627 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003628 * Dump library configuration.
3629 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003630
3631 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003632 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003633 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003634 appendSfConfigString(result);
3635 appendUiConfigString(result);
3636 appendGuiConfigString(result);
3637 result.append("\n");
3638
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003639 result.append("\nWide-Color information:\n");
3640 dumpWideColorInfo(result);
3641
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003642 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003643 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003644 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003645 result.append(SyncFeatures::getInstance().toString());
3646 result.append("\n");
3647
Dan Stoza9e56aa02015-11-02 13:00:03 -08003648 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3649
Andy McFadden41d67d72014-04-25 16:58:34 -07003650 colorizer.bold(result);
3651 result.append("DispSync configuration: ");
3652 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003653 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003654 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003655 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003656 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003657 result.append("\n");
3658
Dan Stozab90cf072015-03-05 11:05:59 -08003659 // Dump static screen stats
3660 result.append("\n");
3661 dumpStaticScreenStats(result);
3662 result.append("\n");
3663
Dan Stozae77c7662016-05-13 11:37:28 -07003664 dumpBufferingStats(result);
3665
Andy McFadden4803b742012-09-24 19:07:20 -07003666 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003667 * Dump the visible layer list
3668 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003669 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003670 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003671 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003672 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003673 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003674 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003675
3676 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003677 * Dump Display state
3678 */
3679
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003680 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003681 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003682 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003683 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3684 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003685 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003686 }
3687
3688 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003689 * Dump SurfaceFlinger global state
3690 */
3691
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003692 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003693 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003694 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003695
Mathias Agopian888c8222012-08-04 21:10:38 -07003696 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003697 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003698
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003699 colorizer.bold(result);
3700 result.appendFormat("EGL implementation : %s\n",
3701 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3702 colorizer.reset(result);
3703 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003704 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003705
Mathias Agopian875d8e12013-06-07 15:35:48 -07003706 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003707
Mathias Agopian42977342012-08-05 00:40:46 -07003708 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003709 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3710 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003711 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003712 " last eglSwapBuffers() time: %f us\n"
3713 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003714 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003715 " refresh-rate : %f fps\n"
3716 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003717 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003718 " gpu_to_cpu_unsupported : %d\n"
3719 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003720 mLastSwapBufferTime/1000.0,
3721 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003722 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003723 1e9 / activeConfig->getVsyncPeriod(),
3724 activeConfig->getDpiX(),
3725 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003726 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003727
Mathias Agopian74d211a2013-04-22 16:55:35 +02003728 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003729 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003730
Mathias Agopian74d211a2013-04-22 16:55:35 +02003731 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003732 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003733
3734 /*
3735 * VSYNC state
3736 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003737 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003738 result.append("\n");
3739
3740 /*
3741 * HWC layer minidump
3742 */
3743 for (size_t d = 0; d < mDisplays.size(); d++) {
3744 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3745 int32_t hwcId = displayDevice->getHwcDisplayId();
3746 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3747 continue;
3748 }
3749
3750 result.appendFormat("Display %d HWC layers:\n", hwcId);
3751 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003752 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003753 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003754 });
Dan Stozae22aec72016-08-01 13:20:59 -07003755 result.append("\n");
3756 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757
3758 /*
3759 * Dump HWComposer state
3760 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003761 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003762 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003763 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003764 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003765 result.appendFormat(" h/w composer %s\n",
3766 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003767 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003768
3769 /*
3770 * Dump gralloc state
3771 */
3772 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3773 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003774
3775 /*
3776 * Dump VrFlinger state if in use.
3777 */
3778 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3779 result.append("VrFlinger state:\n");
3780 result.append(mVrFlinger->Dump().c_str());
3781 result.append("\n");
3782 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003783}
3784
Mathias Agopian13127d82013-03-05 17:47:11 -08003785const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003786SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003787 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003788 wp<IBinder> dpy;
3789 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3790 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3791 dpy = mDisplays.keyAt(i);
3792 break;
3793 }
3794 }
3795 if (dpy == NULL) {
3796 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3797 // Just use the primary display so we have something to return
3798 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3799 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003800 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003801}
3802
Keun young Park63f165f2012-08-31 10:53:36 -07003803bool SurfaceFlinger::startDdmConnection()
3804{
3805 void* libddmconnection_dso =
3806 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3807 if (!libddmconnection_dso) {
3808 return false;
3809 }
3810 void (*DdmConnection_start)(const char* name);
3811 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003812 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003813 if (!DdmConnection_start) {
3814 dlclose(libddmconnection_dso);
3815 return false;
3816 }
3817 (*DdmConnection_start)(getServiceName());
3818 return true;
3819}
3820
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003821status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003822 switch (code) {
3823 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003824 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003825 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003826 case CLEAR_ANIMATION_FRAME_STATS:
3827 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003828 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003829 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 {
3831 // codes that require permission check
3832 IPCThreadState* ipc = IPCThreadState::self();
3833 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003834 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003835 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003836 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003837 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003838 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003839 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003840 break;
3841 }
Robert Carr1db73f62016-12-21 12:58:51 -08003842 /*
3843 * Calling setTransactionState is safe, because you need to have been
3844 * granted a reference to Client* and Handle* to do anything with it.
3845 *
3846 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3847 */
3848 case SET_TRANSACTION_STATE:
3849 case CREATE_SCOPED_CONNECTION:
3850 {
3851 return OK;
3852 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003853 case CAPTURE_SCREEN:
3854 {
3855 // codes that require permission check
3856 IPCThreadState* ipc = IPCThreadState::self();
3857 const int pid = ipc->getCallingPid();
3858 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003859 if ((uid != AID_GRAPHICS) &&
3860 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003861 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003862 return PERMISSION_DENIED;
3863 }
3864 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 }
3866 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003867 return OK;
3868}
3869
3870status_t SurfaceFlinger::onTransact(
3871 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3872{
3873 status_t credentialCheck = CheckTransactCodeCredentials(code);
3874 if (credentialCheck != OK) {
3875 return credentialCheck;
3876 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003877
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3879 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003880 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003881 IPCThreadState* ipc = IPCThreadState::self();
3882 const int uid = ipc->getCallingUid();
3883 if (CC_UNLIKELY(uid != AID_SYSTEM
3884 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003885 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003886 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003887 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 return PERMISSION_DENIED;
3889 }
3890 int n;
3891 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003892 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003893 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 return NO_ERROR;
3895 case 1002: // SHOW_UPDATES
3896 n = data.readInt32();
3897 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003898 invalidateHwcGeometry();
3899 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003902 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003903 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003904 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003905 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003906 setTransactionFlags(
3907 eTransactionNeeded|
3908 eDisplayTransactionNeeded|
3909 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003910 return NO_ERROR;
3911 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003912 case 1006:{ // send empty update
3913 signalRefresh();
3914 return NO_ERROR;
3915 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003916 case 1008: // toggle use of hw composer
3917 n = data.readInt32();
3918 mDebugDisableHWC = n ? 1 : 0;
3919 invalidateHwcGeometry();
3920 repaintEverything();
3921 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003922 case 1009: // toggle use of transform hint
3923 n = data.readInt32();
3924 mDebugDisableTransformHint = n ? 1 : 0;
3925 invalidateHwcGeometry();
3926 repaintEverything();
3927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003929 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003930 reply->writeInt32(0);
3931 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003932 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003933 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 return NO_ERROR;
3935 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003936 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003937 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003938 return NO_ERROR;
3939 }
3940 case 1014: {
3941 // daltonize
3942 n = data.readInt32();
3943 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003944 case 1:
3945 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3946 break;
3947 case 2:
3948 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3949 break;
3950 case 3:
3951 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3952 break;
3953 default:
3954 mDaltonizer.setType(ColorBlindnessType::None);
3955 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003956 }
3957 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003958 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003959 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003960 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003961 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003962 invalidateHwcGeometry();
3963 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003964 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003966 case 1015: {
3967 // apply a color matrix
3968 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003969 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07003970 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07003971 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003972 for (size_t j = 0; j < 4; j++) {
3973 mColorMatrix[i][j] = data.readFloat();
3974 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003975 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003976 } else {
3977 mColorMatrix = mat4();
3978 }
Romain Guy88d37dd2017-05-26 17:57:05 -07003979
3980 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
3981 // the division by w in the fragment shader
3982 float4 lastRow(transpose(mColorMatrix)[3]);
3983 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
3984 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
3985 }
3986
Alan Viverette9c5a3332013-09-12 20:04:35 -07003987 invalidateHwcGeometry();
3988 repaintEverything();
3989 return NO_ERROR;
3990 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003991 // This is an experimental interface
3992 // Needs to be shifted to proper binder interface when we productize
3993 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003994 n = data.readInt32();
3995 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003996 return NO_ERROR;
3997 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003998 case 1017: {
3999 n = data.readInt32();
4000 mForceFullDamage = static_cast<bool>(n);
4001 return NO_ERROR;
4002 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004003 case 1018: { // Modify Choreographer's phase offset
4004 n = data.readInt32();
4005 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4006 return NO_ERROR;
4007 }
4008 case 1019: { // Modify SurfaceFlinger's phase offset
4009 n = data.readInt32();
4010 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4011 return NO_ERROR;
4012 }
Irvel468051e2016-06-13 16:44:44 -07004013 case 1020: { // Layer updates interceptor
4014 n = data.readInt32();
4015 if (n) {
4016 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004017 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004018 }
4019 else{
4020 ALOGV("Interceptor disabled");
4021 mInterceptor.disable();
4022 }
4023 return NO_ERROR;
4024 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004025 case 1021: { // Disable HWC virtual displays
4026 n = data.readInt32();
4027 mUseHwcVirtualDisplays = !n;
4028 return NO_ERROR;
4029 }
Romain Guy0147a172017-06-01 13:53:56 -07004030 case 1022: { // Set saturation boost
4031 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4032
4033 invalidateHwcGeometry();
4034 repaintEverything();
4035 return NO_ERROR;
4036 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004037 }
4038 }
4039 return err;
4040}
4041
Mathias Agopian53331da2011-08-22 21:44:41 -07004042void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004043 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004044 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004045}
4046
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004047// Checks that the requested width and height are valid and updates them to the display dimensions
4048// if they are set to 0
4049static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4050 Transform::orientation_flags rotation,
4051 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4052 // get screen geometry
4053 uint32_t displayWidth = displayDevice->getWidth();
4054 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004055
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004056 if (rotation & Transform::ROT_90) {
4057 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004058 }
4059
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004060 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4061 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4062 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4063 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004064 }
4065
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004066 if (*requestedWidth == 0) {
4067 *requestedWidth = displayWidth;
4068 }
4069 if (*requestedHeight == 0) {
4070 *requestedHeight = displayHeight;
4071 }
4072
4073 return NO_ERROR;
4074}
4075
4076// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4077class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004078public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004079 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4080 ~WindowDisconnector() {
4081 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004082 }
4083
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004084private:
4085 ANativeWindow* mWindow;
4086 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004087};
4088
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004089static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4090 uint32_t requestedHeight, bool hasWideColorDisplay,
4091 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4092 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4093 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4094
4095 int err = 0;
4096 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4097 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4098 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4099 err |= native_window_set_usage(window, usage);
4100
4101 if (hasWideColorDisplay) {
4102 err |= native_window_set_buffers_data_space(window,
4103 renderEngineUsesWideColor
4104 ? HAL_DATASPACE_DISPLAY_P3
4105 : HAL_DATASPACE_V0_SRGB);
4106 }
4107
4108 if (err != NO_ERROR) {
4109 return BAD_VALUE;
4110 }
4111
4112 /* TODO: Once we have the sync framework everywhere this can use
4113 * server-side waits on the fence that dequeueBuffer returns.
4114 */
4115 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4116 if (err != NO_ERROR) {
4117 return err;
4118 }
4119
4120 return NO_ERROR;
4121}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004122
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004123status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4124 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004125 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004126 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004127 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004128 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004129
4130 if (CC_UNLIKELY(display == 0))
4131 return BAD_VALUE;
4132
4133 if (CC_UNLIKELY(producer == 0))
4134 return BAD_VALUE;
4135
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004136 // if we have secure windows on this display, never allow the screen capture
4137 // unless the producer interface is local (i.e.: we can take a screenshot for
4138 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004139 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004140
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004141 // Convert to surfaceflinger's internal rotation type.
4142 Transform::orientation_flags rotationFlags;
4143 switch (rotation) {
4144 case ISurfaceComposer::eRotateNone:
4145 rotationFlags = Transform::ROT_0;
4146 break;
4147 case ISurfaceComposer::eRotate90:
4148 rotationFlags = Transform::ROT_90;
4149 break;
4150 case ISurfaceComposer::eRotate180:
4151 rotationFlags = Transform::ROT_180;
4152 break;
4153 case ISurfaceComposer::eRotate270:
4154 rotationFlags = Transform::ROT_270;
4155 break;
4156 default:
4157 rotationFlags = Transform::ROT_0;
4158 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4159 break;
4160 }
4161
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004162 { // Autolock scope
4163 Mutex::Autolock lock(mStateLock);
4164 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4165 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004166 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004167
4168 // create a surface (because we're a producer, and we need to
4169 // dequeue/queue a buffer)
4170 sp<Surface> surface = new Surface(producer, false);
4171
4172 // Put the screenshot Surface into async mode so that
4173 // Layer::headFenceHasSignaled will always return true and we'll latch the
4174 // first buffer regardless of whether or not its acquire fence has
4175 // signaled. This is needed to avoid a race condition in the rotation
4176 // animation. See b/30209608
4177 surface->setAsyncMode(true);
4178
4179 ANativeWindow* window = surface.get();
4180
4181 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4182 if (result != NO_ERROR) {
4183 return result;
4184 }
4185 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4186
4187 ANativeWindowBuffer* buffer = nullptr;
4188 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4189 getRenderEngine().usesWideColor(), &buffer);
4190 if (result != NO_ERROR) {
4191 return result;
4192 }
4193
4194 // This mutex protects syncFd and captureResult for communication of the return values from the
4195 // main thread back to this Binder thread
4196 std::mutex captureMutex;
4197 std::condition_variable captureCondition;
4198 std::unique_lock<std::mutex> captureLock(captureMutex);
4199 int syncFd = -1;
4200 std::optional<status_t> captureResult;
4201
4202 sp<LambdaMessage> message = new LambdaMessage([&]() {
4203 // If there is a refresh pending, bug out early and tell the binder thread to try again
4204 // after the refresh.
4205 if (mRefreshPending) {
4206 ATRACE_NAME("Skipping screenshot for now");
4207 std::unique_lock<std::mutex> captureLock(captureMutex);
4208 captureResult = std::make_optional<status_t>(EAGAIN);
4209 captureCondition.notify_one();
4210 return;
4211 }
4212
4213 status_t result = NO_ERROR;
4214 int fd = -1;
4215 {
4216 Mutex::Autolock _l(mStateLock);
4217 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4218 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4219 minLayerZ, maxLayerZ, useIdentityTransform,
4220 rotationFlags, isLocalScreenshot, &fd);
4221 }
4222
4223 {
4224 std::unique_lock<std::mutex> captureLock(captureMutex);
4225 syncFd = fd;
4226 captureResult = std::make_optional<status_t>(result);
4227 captureCondition.notify_one();
4228 }
4229 });
4230
4231 result = postMessageAsync(message);
4232 if (result == NO_ERROR) {
4233 captureCondition.wait(captureLock, [&]() { return captureResult; });
4234 while (*captureResult == EAGAIN) {
4235 captureResult.reset();
4236 result = postMessageAsync(message);
4237 if (result != NO_ERROR) {
4238 return result;
4239 }
4240 captureCondition.wait(captureLock, [&]() { return captureResult; });
4241 }
4242 result = *captureResult;
4243 }
4244
4245 if (result == NO_ERROR) {
4246 // queueBuffer takes ownership of syncFd
4247 result = window->queueBuffer(window, buffer, syncFd);
4248 }
4249
4250 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004251}
4252
Mathias Agopian180f10d2013-04-10 22:55:41 -07004253
4254void SurfaceFlinger::renderScreenImplLocked(
4255 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004256 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004257 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004258 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004259{
4260 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004261 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004262
4263 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004264 const int32_t hw_w = hw->getWidth();
4265 const int32_t hw_h = hw->getHeight();
4266 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004267 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004268
Dan Stozac1879002014-05-22 15:59:05 -07004269 // if a default or invalid sourceCrop is passed in, set reasonable values
4270 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4271 !sourceCrop.isValid()) {
4272 sourceCrop.setLeftTop(Point(0, 0));
4273 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4274 }
4275
4276 // ensure that sourceCrop is inside screen
4277 if (sourceCrop.left < 0) {
4278 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4279 }
Dan Stozabe31f442014-06-11 11:20:54 -07004280 if (sourceCrop.right > hw_w) {
4281 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004282 }
4283 if (sourceCrop.top < 0) {
4284 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4285 }
Dan Stozabe31f442014-06-11 11:20:54 -07004286 if (sourceCrop.bottom > hw_h) {
4287 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004288 }
4289
Romain Guy88d37dd2017-05-26 17:57:05 -07004290#ifdef USE_HWC2
4291 engine.setWideColor(hw->getWideColorSupport());
4292 engine.setColorMode(hw->getActiveColorMode());
4293#endif
4294
Mathias Agopian180f10d2013-04-10 22:55:41 -07004295 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004296 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004297
4298 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004299 engine.setViewportAndProjection(
4300 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004301 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004302
4303 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004304 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004305
Robert Carr1f0a16a2016-10-24 16:27:39 -07004306 // We loop through the first level of layers without traversing,
4307 // as we need to interpret min/max layer Z in the top level Z space.
4308 for (const auto& layer : mDrawingState.layersSortedByZ) {
4309 if (layer->getLayerStack() != hw->getLayerStack()) {
4310 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004311 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004312 const Layer::State& state(layer->getDrawingState());
4313 if (state.z < minLayerZ || state.z > maxLayerZ) {
4314 continue;
4315 }
Dan Stoza412903f2017-04-27 13:42:17 -07004316 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004317 if (!layer->isVisible()) {
4318 return;
4319 }
4320 if (filtering) layer->setFiltering(true);
4321 layer->draw(hw, useIdentityTransform);
4322 if (filtering) layer->setFiltering(false);
4323 });
4324 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004325
Mathias Agopian931bda12013-08-28 18:11:46 -07004326 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004327}
4328
Dan Stozaabcda352017-06-01 14:37:39 -07004329// A simple RAII class that holds an EGLImage and destroys it either:
4330// a) When the destroy() method is called
4331// b) When the object goes out of scope
4332class ImageHolder {
4333public:
4334 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4335 ~ImageHolder() { destroy(); }
4336
4337 void destroy() {
4338 if (mImage != EGL_NO_IMAGE_KHR) {
4339 eglDestroyImageKHR(mDisplay, mImage);
4340 mImage = EGL_NO_IMAGE_KHR;
4341 }
4342 }
4343
4344private:
4345 const EGLDisplay mDisplay;
4346 EGLImageKHR mImage;
4347};
4348
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004349status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4350 ANativeWindowBuffer* buffer, Rect sourceCrop,
4351 uint32_t reqWidth, uint32_t reqHeight,
4352 int32_t minLayerZ, int32_t maxLayerZ,
4353 bool useIdentityTransform,
4354 Transform::orientation_flags rotation,
4355 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004356 ATRACE_CALL();
4357
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004358 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004359 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004360 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004361 if ((layer->getLayerStack() != hw->getLayerStack()) ||
4362 (state.z < minLayerZ || state.z > maxLayerZ)) {
4363 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004364 }
Dan Stoza412903f2017-04-27 13:42:17 -07004365 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004366 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4367 layer->isSecure());
4368 });
4369 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004370
4371 if (!isLocalScreenshot && secureLayerIsVisible) {
4372 ALOGW("FB is protected: PERMISSION_DENIED");
4373 return PERMISSION_DENIED;
4374 }
4375
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004376 int syncFd = -1;
4377 // create an EGLImage from the buffer so we can later
4378 // turn it into a texture
4379 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4380 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4381 if (image == EGL_NO_IMAGE_KHR) {
4382 return BAD_VALUE;
4383 }
4384
Dan Stozaabcda352017-06-01 14:37:39 -07004385 // This will automatically destroy the image if we return before calling its destroy method
4386 ImageHolder imageHolder(mEGLDisplay, image);
4387
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004388 // this binds the given EGLImage as a framebuffer for the
4389 // duration of this scope.
4390 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004391 if (imageBond.getStatus() != NO_ERROR) {
4392 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004393 return INVALID_OPERATION;
4394 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004395
Dan Stozaabcda352017-06-01 14:37:39 -07004396 // this will in fact render into our dequeued buffer
4397 // via an FBO, which means we didn't have to create
4398 // an EGLSurface and therefore we're not
4399 // dependent on the context's EGLConfig.
4400 renderScreenImplLocked(
4401 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4402 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004403
Dan Stozaabcda352017-06-01 14:37:39 -07004404 // Attempt to create a sync khr object that can produce a sync point. If that
4405 // isn't available, create a non-dupable sync object in the fallback path and
4406 // wait on it directly.
4407 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4408 if (!DEBUG_SCREENSHOTS) {
4409 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4410 // native fence fd will not be populated until flush() is done.
4411 getRenderEngine().flush();
4412 }
4413
4414 if (sync != EGL_NO_SYNC_KHR) {
4415 // get the sync fd
4416 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4417 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4418 ALOGW("captureScreen: failed to dup sync khr object");
4419 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004420 }
Dan Stozaabcda352017-06-01 14:37:39 -07004421 eglDestroySyncKHR(mEGLDisplay, sync);
4422 } else {
4423 // fallback path
4424 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004425 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004426 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4427 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4428 EGLint eglErr = eglGetError();
4429 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4430 ALOGW("captureScreen: fence wait timed out");
4431 } else {
4432 ALOGW_IF(eglErr != EGL_SUCCESS,
4433 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004434 }
4435 eglDestroySyncKHR(mEGLDisplay, sync);
4436 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004437 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004438 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004439 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004440 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004441
4442 if (DEBUG_SCREENSHOTS) {
4443 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4444 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4445 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4446 hw, minLayerZ, maxLayerZ);
4447 delete [] pixels;
4448 }
4449
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004450 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004451 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004452
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004453 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004454}
4455
Mathias Agopiand5556842013-09-19 17:08:37 -07004456void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004457 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004458 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004459 for (size_t y=0 ; y<h ; y++) {
4460 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4461 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004462 if (p[x] != 0xFF000000) return;
4463 }
4464 }
4465 ALOGE("*** we just took a black screenshot ***\n"
4466 "requested minz=%d, maxz=%d, layerStack=%d",
4467 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004468
Robert Carr2047fae2016-11-28 14:09:09 -08004469 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004470 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004471 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004472 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
4473 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004474 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004475 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4476 layer->isVisible() ? '+' : '-',
4477 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004478 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004479 i++;
4480 });
4481 }
4482 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004483 }
4484}
4485
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004486// ---------------------------------------------------------------------------
4487
Dan Stoza412903f2017-04-27 13:42:17 -07004488void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4489 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004490}
4491
Dan Stoza412903f2017-04-27 13:42:17 -07004492void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4493 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004494}
4495
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004496}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004497
4498
4499#if defined(__gl_h_)
4500#error "don't include gl/gl.h in this file"
4501#endif
4502
4503#if defined(__gl2_h_)
4504#error "don't include gl2/gl2.h in this file"
4505#endif