blob: 769ff9c574b79f2484c8903aaa51f98197eaaaf5 [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
Steven Thomasd7f49c52017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Jiyong Park00b15b82017-08-10 20:30:56 +0900100extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
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
Steven Thomasd7f49c52017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700132bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700142 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700144 mTransactionPending(false),
145 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700146 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700147 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700148 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800149 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800151 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800154 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700156 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700157 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700158 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700159 mDebugInSwapBuffers(0),
160 mLastSwapBufferTime(0),
161 mDebugInTransaction(0),
162 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700163 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700164 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800165 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000166 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700167 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700168 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700169 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800170 mHasPoweredOff(false),
171 mFrameBuckets(),
172 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700173 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800174 mNumLayers(0),
Steven Thomasd7f49c52017-07-26 18:48:28 -0700175 mVrFlingerRequestsDisplay(false),
176 mMainThreadId(std::this_thread::get_id()),
177 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800179 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800180
181 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
183
184 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
186
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700190 useContextPriority = getBool< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::useContextPriority>(false);
192
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700193 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
194 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
195
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700196 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
197 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
198
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800199 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
200 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
201
Steven Thomas050b2c82017-03-06 11:45:16 -0800202 // Vr flinger is only enabled on Daydream ready devices.
203 useVrFlinger = getBool< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::useVrFlinger>(false);
205
Fabien Sanglard1971b632017-03-10 14:50:03 -0800206 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
208
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600209 hasWideColorDisplay =
210 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
211
Saurabh Shahf4174532017-07-13 10:45:07 -0700212 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 // debugging stuff...
215 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700216
Mathias Agopianb4b17302013-03-20 18:36:41 -0700217 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700218 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 property_get("debug.sf.showupdates", value, "0");
221 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700222
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700223 property_get("debug.sf.ddms", value, "0");
224 mDebugDDMS = atoi(value);
225 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700226 if (!startDdmConnection()) {
227 // start failed, and DDMS debugging not enabled
228 mDebugDDMS = 0;
229 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700230 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700231 ALOGI_IF(mDebugRegion, "showupdates enabled");
232 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700233
234 property_get("debug.sf.disable_backpressure", value, "0");
235 mPropagateBackpressure = !atoi(value);
236 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700237
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800238 property_get("debug.sf.enable_hwc_vds", value, "0");
239 mUseHwcVirtualDisplays = atoi(value);
240 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800241
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800242 property_get("ro.sf.disable_triple_buffer", value, "1");
243 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800244 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700245
Romain Guy11d63f42017-07-20 12:47:14 -0700246 // We should be reading 'persist.sys.sf.color_saturation' here
247 // but since /data may be encrypted, we need to wait until after vold
248 // comes online to attempt to read the property. The property is
249 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250}
251
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252void SurfaceFlinger::onFirstRef()
253{
254 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800255}
256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257SurfaceFlinger::~SurfaceFlinger()
258{
Mathias Agopiana4912602012-07-12 14:25:33 -0700259 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
260 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
261 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262}
263
Dan Stozac7014012014-02-14 15:03:43 -0800264void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800265{
266 // the window manager died on us. prepare its eulogy.
267
Andy McFadden13a082e2012-08-24 10:16:42 -0700268 // restore initial conditions (default device unblank, etc)
269 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800270
271 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700272 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800273}
274
Robert Carr1db73f62016-12-21 12:58:51 -0800275static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700276 status_t err = client->initCheck();
277 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800278 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279 }
Robert Carr1db73f62016-12-21 12:58:51 -0800280 return nullptr;
281}
282
283sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
284 return initClient(new Client(this));
285}
286
287sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
288 const sp<IGraphicBufferProducer>& gbp) {
289 if (authenticateSurfaceTexture(gbp) == false) {
290 return nullptr;
291 }
292 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
293 if (layer == nullptr) {
294 return nullptr;
295 }
296
297 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298}
299
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700300sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
301 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302{
303 class DisplayToken : public BBinder {
304 sp<SurfaceFlinger> flinger;
305 virtual ~DisplayToken() {
306 // no more references, this display must be terminated
307 Mutex::Autolock _l(flinger->mStateLock);
308 flinger->mCurrentState.displays.removeItem(this);
309 flinger->setTransactionFlags(eDisplayTransactionNeeded);
310 }
311 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700312 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700313 : flinger(flinger) {
314 }
315 };
316
317 sp<BBinder> token = new DisplayToken(this);
318
319 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700320 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700321 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700322 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700323 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324 return token;
325}
326
Jesse Hall6c913be2013-08-08 12:15:49 -0700327void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
328 Mutex::Autolock _l(mStateLock);
329
330 ssize_t idx = mCurrentState.displays.indexOfKey(display);
331 if (idx < 0) {
332 ALOGW("destroyDisplay: invalid display token");
333 return;
334 }
335
336 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
337 if (!info.isVirtualDisplay()) {
338 ALOGE("destroyDisplay called for non-virtual display");
339 return;
340 }
Irvelffc9efc2016-07-27 15:16:37 -0700341 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700342 mCurrentState.displays.removeItemsAt(idx);
343 setTransactionFlags(eDisplayTransactionNeeded);
344}
345
Jesse Hall692c7232012-11-08 15:41:56 -0800346void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800347 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800348 ALOGW_IF(mBuiltinDisplays[type],
349 "Overwriting display token for display type %d", type);
350 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800351 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700352 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800353 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700354 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800355}
356
Mathias Agopiane57f2922012-08-09 16:29:12 -0700357sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700358 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700359 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
360 return NULL;
361 }
Jesse Hall692c7232012-11-08 15:41:56 -0800362 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700363}
364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365void SurfaceFlinger::bootFinished()
366{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700367 if (mStartPropertySetThread->join() != NO_ERROR) {
368 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 const nsecs_t now = systemTime();
371 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000372 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700373
374 // wait patiently for the window manager death
375 const String16 name("window");
376 sp<IBinder> window(defaultServiceManager()->getService(name));
377 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700379 }
380
Steven Thomas050b2c82017-03-06 11:45:16 -0800381 if (mVrFlinger) {
382 mVrFlinger->OnBootFinished();
383 }
384
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700385 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700386 // formerly we would just kill the process, but we now ask it to exit so it
387 // can choose where to stop the animation.
388 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700389
390 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
391 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
392 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700393
Romain Guyc53d3552017-07-20 18:49:46 -0700394 sp<LambdaMessage> bootFinished = new LambdaMessage([&]() {
395 mBootFinished = true;
396
Romain Guy11d63f42017-07-20 12:47:14 -0700397 readPersistentProperties();
Romain Guyc53d3552017-07-20 18:49:46 -0700398
399#ifdef USE_HWC2
400 sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
401 if (hw->getWideColorSupport()) {
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -0600402 hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
Romain Guyc53d3552017-07-20 18:49:46 -0700403 setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
404 }
405#endif
Romain Guy11d63f42017-07-20 12:47:14 -0700406 });
Romain Guyc53d3552017-07-20 18:49:46 -0700407 postMessageAsync(bootFinished);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408}
409
Mathias Agopian3f844832013-08-07 21:24:32 -0700410void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700411 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700412 RenderEngine& engine;
413 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700414 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700415 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
416 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700417 }
418 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700419 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700420 return true;
421 }
422 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700423 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700424}
425
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426class DispSyncSource : public VSyncSource, private DispSync::Callback {
427public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700428 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000429 const char* name) :
430 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700431 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700432 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000433 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
434 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 mDispSync(dispSync),
436 mCallbackMutex(),
437 mCallback(),
438 mVsyncMutex(),
439 mPhaseOffset(phaseOffset),
440 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700441
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700442 virtual ~DispSyncSource() {}
443
444 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700445 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700446 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700448 static_cast<DispSync::Callback*>(this));
449 if (err != NO_ERROR) {
450 ALOGE("error registering vsync callback: %s (%d)",
451 strerror(-err), err);
452 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700453 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 } else {
455 status_t err = mDispSync->removeEventListener(
456 static_cast<DispSync::Callback*>(this));
457 if (err != NO_ERROR) {
458 ALOGE("error unregistering vsync callback: %s (%d)",
459 strerror(-err), err);
460 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700461 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700462 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700463 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700464 }
465
466 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700467 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700468 mCallback = callback;
469 }
470
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700471 virtual void setPhaseOffset(nsecs_t phaseOffset) {
472 Mutex::Autolock lock(mVsyncMutex);
473
474 // Normalize phaseOffset to [0, period)
475 auto period = mDispSync->getPeriod();
476 phaseOffset %= period;
477 if (phaseOffset < 0) {
478 // If we're here, then phaseOffset is in (-period, 0). After this
479 // operation, it will be in (0, period)
480 phaseOffset += period;
481 }
482 mPhaseOffset = phaseOffset;
483
484 // If we're not enabled, we don't need to mess with the listeners
485 if (!mEnabled) {
486 return;
487 }
488
489 // Remove the listener with the old offset
490 status_t err = mDispSync->removeEventListener(
491 static_cast<DispSync::Callback*>(this));
492 if (err != NO_ERROR) {
493 ALOGE("error unregistering vsync callback: %s (%d)",
494 strerror(-err), err);
495 }
496
497 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000498 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700499 static_cast<DispSync::Callback*>(this));
500 if (err != NO_ERROR) {
501 ALOGE("error registering vsync callback: %s (%d)",
502 strerror(-err), err);
503 }
504 }
505
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700506private:
507 virtual void onDispSyncEvent(nsecs_t when) {
508 sp<VSyncSource::Callback> callback;
509 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700510 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700511 callback = mCallback;
512
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700513 if (mTraceVsync) {
514 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700515 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700516 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700517 }
518
519 if (callback != NULL) {
520 callback->onVSyncEvent(when);
521 }
522 }
523
Tim Murray4a4e4a22016-04-19 16:29:23 +0000524 const char* const mName;
525
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700526 int mValue;
527
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700528 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700529 const String8 mVsyncOnLabel;
530 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700531
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700532 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700533
534 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700535 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700536
537 Mutex mVsyncMutex; // Protects the following
538 nsecs_t mPhaseOffset;
539 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700540};
541
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700542class InjectVSyncSource : public VSyncSource {
543public:
544 InjectVSyncSource() {}
545
546 virtual ~InjectVSyncSource() {}
547
548 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
549 std::lock_guard<std::mutex> lock(mCallbackMutex);
550 mCallback = callback;
551 }
552
553 virtual void onInjectSyncEvent(nsecs_t when) {
554 std::lock_guard<std::mutex> lock(mCallbackMutex);
555 mCallback->onVSyncEvent(when);
556 }
557
558 virtual void setVSyncEnabled(bool) {}
559 virtual void setPhaseOffset(nsecs_t) {}
560
561private:
562 std::mutex mCallbackMutex; // Protects the following
563 sp<VSyncSource::Callback> mCallback;
564};
565
Wei Wangf9b05ee2017-07-19 20:59:39 -0700566// Do not call property_set on main thread which will be blocked by init
567// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700569 ALOGI( "SurfaceFlinger's main thread ready to run. "
570 "Initializing graphics H/W...");
571
Romain Guyc53d3552017-07-20 18:49:46 -0700572 ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900573
Steven Thomasd7f49c52017-07-26 18:48:28 -0700574 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800575
Steven Thomasd7f49c52017-07-26 18:48:28 -0700576 // initialize EGL for the default display
577 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
578 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800579
Steven Thomasd7f49c52017-07-26 18:48:28 -0700580 // start the EventThread
581 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
582 vsyncPhaseOffsetNs, true, "app");
583 mEventThread = new EventThread(vsyncSrc, *this, false);
584 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
585 sfVsyncPhaseOffsetNs, true, "sf");
586 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
587 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800588
Steven Thomasd7f49c52017-07-26 18:48:28 -0700589 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
590 struct sched_param param = {0};
591 param.sched_priority = 2;
592 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
593 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
594 }
595 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
596 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800597 }
598
Steven Thomasd7f49c52017-07-26 18:48:28 -0700599 // Get a RenderEngine for the given display / config (can't fail)
600 mRenderEngine = RenderEngine::create(mEGLDisplay,
601 HAL_PIXEL_FORMAT_RGBA_8888,
602 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800603
Steven Thomasd7f49c52017-07-26 18:48:28 -0700604 // retrieve the EGL context that was selected/created
605 mEGLContext = mRenderEngine->getEGLContext();
606
607 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
608 "couldn't create EGLContext");
609
610 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611 "Starting with vr flinger active is not currently supported.");
612 mHwc.reset(new HWComposer(false));
613 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800614
Steven Thomas050b2c82017-03-06 11:45:16 -0800615 if (useVrFlinger) {
616 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700617 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800618 mVrFlingerRequestsDisplay = requestDisplay;
619 signalTransaction();
620 };
621 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
622 vrFlingerRequestDisplayCallback);
623 if (!mVrFlinger) {
624 ALOGE("Failed to start vrflinger");
625 }
626 }
627
Jamie Gennisd1700752013-10-14 12:22:52 -0700628 mEventControlThread = new EventControlThread(this);
629 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
630
Mathias Agopian92a979a2012-08-02 18:32:23 -0700631 // initialize our drawing state
632 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700633
Andy McFadden13a082e2012-08-24 10:16:42 -0700634 // set initial conditions (e.g. unblank default device)
635 initializeDisplays();
636
Dan Stoza4e637772016-07-28 13:31:51 -0700637 mRenderEngine->primeCache();
638
Wei Wangf9b05ee2017-07-19 20:59:39 -0700639 // Inform native graphics APIs whether the present timestamp is supported:
640 if (getHwComposer().hasCapability(
641 HWC2::Capability::PresentFenceIsNotReliable)) {
642 mStartPropertySetThread = new StartPropertySetThread(false);
643 } else {
644 mStartPropertySetThread = new StartPropertySetThread(true);
645 }
646
647 if (mStartPropertySetThread->Start() != NO_ERROR) {
648 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800650
Dan Stoza9e56aa02015-11-02 13:00:03 -0800651 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700652}
653
Romain Guy11d63f42017-07-20 12:47:14 -0700654void SurfaceFlinger::readPersistentProperties() {
655 char value[PROPERTY_VALUE_MAX];
656
657 property_get("persist.sys.sf.color_saturation", value, "1.0");
658 mSaturation = atof(value);
659 ALOGV("Saturation is set to %.2f", mSaturation);
660}
661
Mathias Agopiana67e4182012-06-19 17:26:12 -0700662void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800663 // Start boot animation service by setting a property mailbox
664 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700665 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800666 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700667 if (mStartPropertySetThread->join() != NO_ERROR) {
668 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800669 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700670}
671
Mathias Agopian875d8e12013-06-07 15:35:48 -0700672size_t SurfaceFlinger::getMaxTextureSize() const {
673 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700674}
675
Mathias Agopian875d8e12013-06-07 15:35:48 -0700676size_t SurfaceFlinger::getMaxViewportDims() const {
677 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700678}
679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800681
Jamie Gennis582270d2011-08-17 18:19:00 -0700682bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800683 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800684 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800685 return authenticateSurfaceTextureLocked(bufferProducer);
686}
687
688bool SurfaceFlinger::authenticateSurfaceTextureLocked(
689 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800690 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700691 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800692}
693
Brian Anderson6b376712017-04-04 10:51:39 -0700694status_t SurfaceFlinger::getSupportedFrameTimestamps(
695 std::vector<FrameEvent>* outSupported) const {
696 *outSupported = {
697 FrameEvent::REQUESTED_PRESENT,
698 FrameEvent::ACQUIRE,
699 FrameEvent::LATCH,
700 FrameEvent::FIRST_REFRESH_START,
701 FrameEvent::LAST_REFRESH_START,
702 FrameEvent::GPU_COMPOSITION_DONE,
703 FrameEvent::DEQUEUE_READY,
704 FrameEvent::RELEASE,
705 };
706 if (!getHwComposer().hasCapability(
707 HWC2::Capability::PresentFenceIsNotReliable)) {
708 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
709 }
710 return NO_ERROR;
711}
712
Dan Stoza7f7da322014-05-02 15:26:25 -0700713status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
714 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700715 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700716 return BAD_VALUE;
717 }
718
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500719 if (!display.get())
720 return NAME_NOT_FOUND;
721
Jesse Hall692c7232012-11-08 15:41:56 -0800722 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700723 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800724 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700725 type = i;
726 break;
727 }
728 }
729
730 if (type < 0) {
731 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700732 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700733
Mathias Agopian8b736f12012-08-13 17:54:26 -0700734 // TODO: Not sure if display density should handled by SF any longer
735 class Density {
736 static int getDensityFromProperty(char const* propName) {
737 char property[PROPERTY_VALUE_MAX];
738 int density = 0;
739 if (property_get(propName, property, NULL) > 0) {
740 density = atoi(property);
741 }
742 return density;
743 }
744 public:
745 static int getEmuDensity() {
746 return getDensityFromProperty("qemu.sf.lcd_density"); }
747 static int getBuildDensity() {
748 return getDensityFromProperty("ro.sf.lcd_density"); }
749 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700750
Dan Stoza7f7da322014-05-02 15:26:25 -0700751 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700752
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700754 DisplayInfo info = DisplayInfo();
755
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756 float xdpi = hwConfig->getDpiX();
757 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700758
759 if (type == DisplayDevice::DISPLAY_PRIMARY) {
760 // The density of the device is provided by a build property
761 float density = Density::getBuildDensity() / 160.0f;
762 if (density == 0) {
763 // the build doesn't provide a density -- this is wrong!
764 // use xdpi instead
765 ALOGE("ro.sf.lcd_density must be defined as a build property");
766 density = xdpi / 160.0f;
767 }
768 if (Density::getEmuDensity()) {
769 // if "qemu.sf.lcd_density" is specified, it overrides everything
770 xdpi = ydpi = density = Density::getEmuDensity();
771 density /= 160.0f;
772 }
773 info.density = density;
774
775 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000776 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
777 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700778 } else {
779 // TODO: where should this value come from?
780 static const int TV_DENSITY = 213;
781 info.density = TV_DENSITY / 160.0f;
782 info.orientation = 0;
783 }
784
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 info.w = hwConfig->getWidth();
786 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700787 info.xdpi = xdpi;
788 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800789 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900790 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800791
Andy McFadden91b2ca82014-06-13 14:04:23 -0700792 // This is how far in advance a buffer must be queued for
793 // presentation at a given time. If you want a buffer to appear
794 // on the screen at time N, you must submit the buffer before
795 // (N - presentationDeadline).
796 //
797 // Normally it's one full refresh period (to give SF a chance to
798 // latch the buffer), but this can be reduced by configuring a
799 // DispSync offset. Any additional delays introduced by the hardware
800 // composer or panel must be accounted for here.
801 //
802 // We add an additional 1ms to allow for processing time and
803 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800805 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700806
807 // All non-virtual displays are currently considered secure.
808 info.secure = true;
809
Michael Wright28f24d02016-07-12 13:30:53 -0700810 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700811 }
812
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 return NO_ERROR;
814}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700815
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800816status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700817 DisplayStatInfo* stats) {
818 if (stats == NULL) {
819 return BAD_VALUE;
820 }
821
822 // FIXME for now we always return stats for the primary display
823 memset(stats, 0, sizeof(*stats));
824 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
825 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
826 return NO_ERROR;
827}
828
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700829int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800830 if (display == NULL) {
831 ALOGE("%s : display is NULL", __func__);
832 return BAD_VALUE;
833 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700834
835 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700836 if (device != NULL) {
837 return device->getActiveConfig();
838 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700839
Dan Stoza24a42e92015-03-09 10:04:11 -0700840 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700841}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700842
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700843void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
844 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
845 this);
846 int32_t type = hw->getDisplayType();
847 int currentMode = hw->getActiveConfig();
848
849 if (mode == currentMode) {
850 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
851 return;
852 }
853
854 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
855 ALOGW("Trying to set config for virtual display");
856 return;
857 }
858
859 hw->setActiveConfig(mode);
860 getHwComposer().setActiveConfig(type, mode);
861}
862
863status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
864 class MessageSetActiveConfig: public MessageBase {
865 SurfaceFlinger& mFlinger;
866 sp<IBinder> mDisplay;
867 int mMode;
868 public:
869 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
870 int mode) :
871 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
872 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700873 Vector<DisplayInfo> configs;
874 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700875 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700876 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700877 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700878 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700879 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
881 if (hw == NULL) {
882 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700883 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700884 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
885 ALOGW("Attempt to set active config = %d for virtual display",
886 mMode);
887 } else {
888 mFlinger.setActiveConfigInternal(hw, mMode);
889 }
890 return true;
891 }
892 };
893 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
894 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700895 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700896}
Michael Wright28f24d02016-07-12 13:30:53 -0700897status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
898 Vector<android_color_mode_t>* outColorModes) {
899 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
900 return BAD_VALUE;
901 }
902
903 if (!display.get()) {
904 return NAME_NOT_FOUND;
905 }
906
907 int32_t type = NAME_NOT_FOUND;
908 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
909 if (display == mBuiltinDisplays[i]) {
910 type = i;
911 break;
912 }
913 }
914
915 if (type < 0) {
916 return type;
917 }
918
919 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
920 outColorModes->clear();
921 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
922
923 return NO_ERROR;
924}
925
926android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700927 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700928 if (device != nullptr) {
929 return device->getActiveColorMode();
930 }
931 return static_cast<android_color_mode_t>(BAD_VALUE);
932}
933
934void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
935 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700936 int32_t type = hw->getDisplayType();
937 android_color_mode_t currentMode = hw->getActiveColorMode();
938
939 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700940 return;
941 }
942
943 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
944 ALOGW("Trying to set config for virtual display");
945 return;
946 }
947
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600948 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
949 hw->getDisplayType());
950
Michael Wright28f24d02016-07-12 13:30:53 -0700951 hw->setActiveColorMode(mode);
952 getHwComposer().setActiveColorMode(type, mode);
953}
954
955
956status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
957 android_color_mode_t colorMode) {
958 class MessageSetActiveColorMode: public MessageBase {
959 SurfaceFlinger& mFlinger;
960 sp<IBinder> mDisplay;
961 android_color_mode_t mMode;
962 public:
963 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
964 android_color_mode_t mode) :
965 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
966 virtual bool handler() {
967 Vector<android_color_mode_t> modes;
968 mFlinger.getDisplayColorModes(mDisplay, &modes);
969 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
970 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600971 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
972 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700973 return true;
974 }
975 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
976 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600977 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
978 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700979 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600980 ALOGW("Attempt to set active color mode %s %d for virtual display",
981 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700982 } else {
983 mFlinger.setActiveColorModeInternal(hw, mMode);
984 }
985 return true;
986 }
987 };
988 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
989 postMessageSync(msg);
990 return NO_ERROR;
991}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700992
Svetoslavd85084b2014-03-20 10:28:31 -0700993status_t SurfaceFlinger::clearAnimationFrameStats() {
994 Mutex::Autolock _l(mStateLock);
995 mAnimFrameTracker.clearStats();
996 return NO_ERROR;
997}
998
999status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1000 Mutex::Autolock _l(mStateLock);
1001 mAnimFrameTracker.getStats(outStats);
1002 return NO_ERROR;
1003}
1004
Dan Stozac4f471e2016-03-24 09:31:08 -07001005status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1006 HdrCapabilities* outCapabilities) const {
1007 Mutex::Autolock _l(mStateLock);
1008
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001009 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001010 if (displayDevice == nullptr) {
1011 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1012 return BAD_VALUE;
1013 }
1014
1015 std::unique_ptr<HdrCapabilities> capabilities =
1016 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1017 if (capabilities) {
1018 std::swap(*outCapabilities, *capabilities);
1019 } else {
1020 return BAD_VALUE;
1021 }
1022
1023 return NO_ERROR;
1024}
1025
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001026status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1027 if (enable == mInjectVSyncs) {
1028 return NO_ERROR;
1029 }
1030
1031 if (enable) {
1032 mInjectVSyncs = enable;
1033 ALOGV("VSync Injections enabled");
1034 if (mVSyncInjector.get() == nullptr) {
1035 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001036 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001037 }
1038 mEventQueue.setEventThread(mInjectorEventThread);
1039 } else {
1040 mInjectVSyncs = enable;
1041 ALOGV("VSync Injections disabled");
1042 mEventQueue.setEventThread(mSFEventThread);
1043 mVSyncInjector.clear();
1044 }
1045 return NO_ERROR;
1046}
1047
1048status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1049 if (!mInjectVSyncs) {
1050 ALOGE("VSync Injections not enabled");
1051 return BAD_VALUE;
1052 }
1053 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1054 ALOGV("Injecting VSync inside SurfaceFlinger");
1055 mVSyncInjector->onInjectSyncEvent(when);
1056 }
1057 return NO_ERROR;
1058}
1059
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001060// ----------------------------------------------------------------------------
1061
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001062sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1063 ISurfaceComposer::VsyncSource vsyncSource) {
1064 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1065 return mSFEventThread->createEventConnection();
1066 } else {
1067 return mEventThread->createEventConnection();
1068 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001069}
1070
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001071// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001072
1073void SurfaceFlinger::waitForEvent() {
1074 mEventQueue.waitMessage();
1075}
1076
1077void SurfaceFlinger::signalTransaction() {
1078 mEventQueue.invalidate();
1079}
1080
1081void SurfaceFlinger::signalLayerUpdate() {
1082 mEventQueue.invalidate();
1083}
1084
1085void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001086 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001087 mEventQueue.refresh();
1088}
1089
1090status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001091 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001092 return mEventQueue.postMessage(msg, reltime);
1093}
1094
1095status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001096 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001097 status_t res = mEventQueue.postMessage(msg, reltime);
1098 if (res == NO_ERROR) {
1099 msg->wait();
1100 }
1101 return res;
1102}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001103
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001104void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001105 do {
1106 waitForEvent();
1107 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001108}
1109
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001110void SurfaceFlinger::enableHardwareVsync() {
1111 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001112 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001113 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001114 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1115 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001116 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001117 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001118}
1119
Jesse Hall948fe0c2013-10-14 12:56:09 -07001120void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001121 Mutex::Autolock _l(mHWVsyncLock);
1122
Jesse Hall948fe0c2013-10-14 12:56:09 -07001123 if (makeAvailable) {
1124 mHWVsyncAvailable = true;
1125 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001126 // Hardware vsync is not currently available, so abort the resync
1127 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001128 return;
1129 }
1130
Dan Stoza9e56aa02015-11-02 13:00:03 -08001131 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1132 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001133
1134 mPrimaryDispSync.reset();
1135 mPrimaryDispSync.setPeriod(period);
1136
1137 if (!mPrimaryHWVsyncEnabled) {
1138 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001139 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1140 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001141 mPrimaryHWVsyncEnabled = true;
1142 }
1143}
1144
Jesse Hall948fe0c2013-10-14 12:56:09 -07001145void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001146 Mutex::Autolock _l(mHWVsyncLock);
1147 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001148 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1149 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001150 mPrimaryDispSync.endResync();
1151 mPrimaryHWVsyncEnabled = false;
1152 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001153 if (makeUnavailable) {
1154 mHWVsyncAvailable = false;
1155 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001156}
1157
Tim Murray4a4e4a22016-04-19 16:29:23 +00001158void SurfaceFlinger::resyncWithRateLimit() {
1159 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001160
1161 // No explicit locking is needed here since EventThread holds a lock while calling this method
1162 static nsecs_t sLastResyncAttempted = 0;
1163 const nsecs_t now = systemTime();
1164 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001165 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001166 }
Dan Stoza57164302017-05-08 14:03:54 -07001167 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001168}
1169
Steven Thomasd7f49c52017-07-26 18:48:28 -07001170void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1171 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001172 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001173 // Ignore any vsyncs from a previous hardware composer.
1174 if (sequenceId != mComposerSequenceId) {
1175 return;
1176 }
1177
1178 int32_t type;
1179 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001180 return;
1181 }
1182
Jamie Gennisd1700752013-10-14 12:22:52 -07001183 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001184
Jamie Gennisd1700752013-10-14 12:22:52 -07001185 { // Scope for the lock
1186 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001187 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001188 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001189 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001190 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001191
1192 if (needsHwVsync) {
1193 enableHardwareVsync();
1194 } else {
1195 disableHardwareVsync(false);
1196 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001197}
1198
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001199void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001200 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001201 *compositorTiming = mCompositorTiming;
1202}
1203
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001204void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001205 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001206 wp<IBinder> token = mBuiltinDisplays[type];
1207
1208 // All non-virtual displays are currently considered secure.
1209 const bool isSecure = true;
1210
1211 sp<IGraphicBufferProducer> producer;
1212 sp<IGraphicBufferConsumer> consumer;
1213 BufferQueue::createBufferQueue(&producer, &consumer);
1214
1215 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1216
1217 bool hasWideColorModes = false;
1218 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1219 for (android_color_mode_t colorMode : modes) {
1220 switch (colorMode) {
1221 case HAL_COLOR_MODE_DISPLAY_P3:
1222 case HAL_COLOR_MODE_ADOBE_RGB:
1223 case HAL_COLOR_MODE_DCI_P3:
1224 hasWideColorModes = true;
1225 break;
1226 default:
1227 break;
1228 }
1229 }
1230 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1231 token, fbs, producer, mRenderEngine->getEGLConfig(),
1232 hasWideColorModes && hasWideColorDisplay);
1233 mDisplays.add(token, hw);
Romain Guyc53d3552017-07-20 18:49:46 -07001234 setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001235 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001236
1237 // Add the primary display token to mDrawingState so we don't try to
1238 // recreate the DisplayDevice for the primary display.
1239 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1240
1241 // make the GLContext current so that we can create textures when creating
1242 // Layers (which may happens before we render something)
1243 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001244}
1245
Steven Thomasd7f49c52017-07-26 18:48:28 -07001246void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1247 hwc2_display_t display, HWC2::Connection connection,
1248 bool primaryDisplay) {
1249 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1250 sequenceId, display,
1251 connection == HWC2::Connection::Connected ?
1252 "connected" : "disconnected",
1253 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001254
Steven Thomasd7f49c52017-07-26 18:48:28 -07001255 // Only lock if we're not on the main thread. This function is normally
1256 // called on a hwbinder thread, but for the primary display it's called on
1257 // the main thread with the state lock already held, so don't attempt to
1258 // acquire it here.
1259 ConditionalLock lock(mStateLock,
1260 std::this_thread::get_id() != mMainThreadId);
1261
1262 if (primaryDisplay) {
1263 mHwc->onHotplug(display, connection);
1264 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1265 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001266 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001267 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001268 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001269 if (sequenceId != mComposerSequenceId) {
1270 return;
1271 }
1272 if (mHwc->isUsingVrComposer()) {
1273 ALOGE("External displays are not supported by the vr hardware composer.");
1274 return;
1275 }
1276 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001277 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasd7f49c52017-07-26 18:48:28 -07001278 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001279 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001280 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001281 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1282 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001283 }
1284 setTransactionFlags(eDisplayTransactionNeeded);
1285
Andy McFadden9e9689c2012-10-10 18:17:51 -07001286 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001287 }
Mathias Agopian86303202012-07-24 22:46:10 -07001288}
1289
Steven Thomasd7f49c52017-07-26 18:48:28 -07001290void SurfaceFlinger::onRefreshReceived(int sequenceId,
1291 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001292 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001293 if (sequenceId != mComposerSequenceId) {
1294 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001295 }
Steven Thomasd7f49c52017-07-26 18:48:28 -07001296 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001297}
1298
Dan Stoza9e56aa02015-11-02 13:00:03 -08001299void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001300 ATRACE_CALL();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001301 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 getHwComposer().setVsyncEnabled(disp,
1303 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001304}
1305
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasd7f49c52017-07-26 18:48:28 -07001307void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001308 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 // Clear the drawing state so that the logic inside of
1310 // handleTransactionLocked will fire. It will determine the delta between
1311 // mCurrentState and mDrawingState and re-apply all changes when we make the
1312 // transition.
1313 mDrawingState.displays.clear();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001314 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001315 mDisplays.clear();
1316}
1317
Steven Thomas050b2c82017-03-06 11:45:16 -08001318void SurfaceFlinger::updateVrFlinger() {
1319 if (!mVrFlinger)
1320 return;
1321 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1322 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001323 return;
1324 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325
Steven Thomasd7f49c52017-07-26 18:48:28 -07001326 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1327 ALOGE("Vr flinger is only supported for remote hardware composer"
1328 " service connections. Ignoring request to transition to vr"
1329 " flinger.");
1330 mVrFlingerRequestsDisplay = false;
1331 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001332 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001333
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001335
Steven Thomasd7f49c52017-07-26 18:48:28 -07001336 int currentDisplayPowerMode = getDisplayDeviceLocked(
1337 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001338
Steven Thomasd7f49c52017-07-26 18:48:28 -07001339 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001340 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001341 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001342
Steven Thomasd7f49c52017-07-26 18:48:28 -07001343 resetDisplayState();
1344 mHwc.reset(); // Delete the current instance before creating the new one
1345 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1346 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001347
Steven Thomasd7f49c52017-07-26 18:48:28 -07001348 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1349 "Switched to non-remote hardware composer");
1350
1351 if (vrFlingerRequestsDisplay) {
1352 mVrFlinger->GrantDisplayOwnership();
1353 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001354 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001356
1357 mVisibleRegionsDirty = true;
1358 invalidateHwcGeometry();
1359
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001360 // Re-enable default display.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001361 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1362 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1363 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001364
Steven Thomasd7f49c52017-07-26 18:48:28 -07001365 // Reset the timing values to account for the period of the swapped in HWC
1366 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1367 const nsecs_t period = activeConfig->getVsyncPeriod();
1368 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001369
Steven Thomasd7f49c52017-07-26 18:48:28 -07001370 // Use phase of 0 since phase is not known.
1371 // Use latency of 0, which will snap to the ideal latency.
1372 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374 android_atomic_or(1, &mRepaintEverything);
1375 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001376}
1377
Mathias Agopian4fec8732012-06-29 14:12:52 -07001378void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001379 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001380 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001381 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001382 bool frameMissed = !mHadClientComposition &&
1383 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001384 (mPreviousPresentFence->getSignalTime() ==
1385 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001386 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001387 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001388 signalLayerUpdate();
1389 break;
1390 }
1391
Steven Thomas050b2c82017-03-06 11:45:16 -08001392 // Now that we're going to make it to the handleMessageTransaction()
1393 // call below it's safe to call updateVrFlinger(), which will
1394 // potentially trigger a display handoff.
1395 updateVrFlinger();
1396
Dan Stoza6b9454d2014-11-07 16:00:59 -08001397 bool refreshNeeded = handleMessageTransaction();
1398 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001399 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001400 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001401 // Signal a refresh if a transaction modified the window state,
1402 // a new buffer was latched, or if HWC has requested a full
1403 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001404 signalRefresh();
1405 }
1406 break;
1407 }
1408 case MessageQueue::REFRESH: {
1409 handleMessageRefresh();
1410 break;
1411 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001412 }
1413}
1414
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001416 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001417 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001418 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001420 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001422}
1423
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001425 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001427}
1428
1429void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001430 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001431
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001432 mRefreshPending = false;
1433
Pablo Ceballos40845df2016-01-25 17:41:15 -08001434 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001435
Brian Andersond6927fb2016-07-23 23:37:30 -07001436 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001437 rebuildLayerStacks();
1438 setUpHWComposer();
1439 doDebugFlashRegions();
1440 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001441 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001442
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001443 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001444
1445 mHadClientComposition = false;
1446 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1447 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1448 mHadClientComposition = mHadClientComposition ||
1449 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1450 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001451
Dan Stoza9e56aa02015-11-02 13:00:03 -08001452 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001453}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001454
Mathias Agopiancd60f992012-08-16 16:28:27 -07001455void SurfaceFlinger::doDebugFlashRegions()
1456{
1457 // is debugging enabled
1458 if (CC_LIKELY(!mDebugRegion))
1459 return;
1460
1461 const bool repaintEverything = mRepaintEverything;
1462 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1463 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001464 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465 // transform the dirty region into this screen's coordinate space
1466 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1467 if (!dirtyRegion.isEmpty()) {
1468 // redraw the whole screen
1469 doComposeSurfaces(hw, Region(hw->bounds()));
1470
1471 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001473 RenderEngine& engine(getRenderEngine());
1474 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1475
Mathias Agopianda27af92012-09-13 18:17:13 -07001476 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 }
1478 }
1479 }
1480
1481 postFramebuffer();
1482
1483 if (mDebugRegion > 1) {
1484 usleep(mDebugRegion * 1000);
1485 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001486
Dan Stoza9e56aa02015-11-02 13:00:03 -08001487 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001488 auto& displayDevice = mDisplays[displayId];
1489 if (!displayDevice->isDisplayOn()) {
1490 continue;
1491 }
1492
1493 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001494 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1495 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001496 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001497}
1498
Brian Andersond6927fb2016-07-23 23:37:30 -07001499void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001500{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001501 ATRACE_CALL();
1502 ALOGV("preComposition");
1503
Mathias Agopiancd60f992012-08-16 16:28:27 -07001504 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001505 mDrawingState.traverseInZOrder([&](Layer* layer) {
1506 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001507 needExtraInvalidate = true;
1508 }
Robert Carr2047fae2016-11-28 14:09:09 -08001509 });
1510
Mathias Agopiancd60f992012-08-16 16:28:27 -07001511 if (needExtraInvalidate) {
1512 signalLayerUpdate();
1513 }
1514}
1515
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001516void SurfaceFlinger::updateCompositorTiming(
1517 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1518 std::shared_ptr<FenceTime>& presentFenceTime) {
1519 // Update queue of past composite+present times and determine the
1520 // most recently known composite to present latency.
1521 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1522 nsecs_t compositeToPresentLatency = -1;
1523 while (!mCompositePresentTimes.empty()) {
1524 CompositePresentTime& cpt = mCompositePresentTimes.front();
1525 // Cached values should have been updated before calling this method,
1526 // which helps avoid duplicate syscalls.
1527 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1528 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1529 break;
1530 }
1531 compositeToPresentLatency = displayTime - cpt.composite;
1532 mCompositePresentTimes.pop();
1533 }
1534
1535 // Don't let mCompositePresentTimes grow unbounded, just in case.
1536 while (mCompositePresentTimes.size() > 16) {
1537 mCompositePresentTimes.pop();
1538 }
1539
Brian Andersond0010582017-03-07 13:20:31 -08001540 setCompositorTimingSnapped(
1541 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1542}
1543
1544void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1545 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001546 // Integer division and modulo round toward 0 not -inf, so we need to
1547 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001548 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001549 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1550 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1551
Brian Andersond0010582017-03-07 13:20:31 -08001552 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1553 if (idealLatency <= 0) {
1554 idealLatency = vsyncInterval;
1555 }
1556
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001557 // Snap the latency to a value that removes scheduling jitter from the
1558 // composition and present times, which often have >1ms of jitter.
1559 // Reducing jitter is important if an app attempts to extrapolate
1560 // something (such as user input) to an accurate diasplay time.
1561 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1562 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001563 nsecs_t bias = vsyncInterval / 2;
1564 int64_t extraVsyncs =
1565 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1566 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1567 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568
Brian Andersond0010582017-03-07 13:20:31 -08001569 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001570 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1571 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001572 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573}
1574
1575void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001576{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001577 ATRACE_CALL();
1578 ALOGV("postComposition");
1579
Brian Anderson3546a3f2016-07-14 11:51:14 -07001580 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001581 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001582 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001583 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001584 }
1585
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001586 // |mStateLock| not needed as we are on the main thread
1587 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001588
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001589 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001590 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1591 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1592 glCompositionDoneFenceTime =
1593 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1594 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1595 } else {
1596 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1597 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001598
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001599 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001600 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1601 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1602 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1605 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1606
1607 // We use the refreshStartTime which might be sampled a little later than
1608 // when we started doing work for this frame, but that should be okay
1609 // since updateCompositorTiming has snapping logic.
1610 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001611 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001612 CompositorTiming compositorTiming;
1613 {
1614 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1615 compositorTiming = mCompositorTiming;
1616 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001617
Robert Carr2047fae2016-11-28 14:09:09 -08001618 mDrawingState.traverseInZOrder([&](Layer* layer) {
1619 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001620 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001621 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001622 recordBufferingStats(layer->getName().string(),
1623 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001624 }
Robert Carr2047fae2016-11-28 14:09:09 -08001625 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001626
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001627 if (presentFenceTime->isValid()) {
1628 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001629 enableHardwareVsync();
1630 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001631 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001632 }
1633 }
1634
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001635 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001636 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001637 enableHardwareVsync();
1638 }
1639 }
1640
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001641 if (mAnimCompositionPending) {
1642 mAnimCompositionPending = false;
1643
Brian Anderson4e606e32017-03-16 15:34:57 -07001644 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001645 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001646 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001647 } else {
1648 // The HWC doesn't support present fences, so use the refresh
1649 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 nsecs_t presentTime =
1651 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001652 mAnimFrameTracker.setActualPresentTime(presentTime);
1653 }
1654 mAnimFrameTracker.advanceFrame();
1655 }
Dan Stozab90cf072015-03-05 11:05:59 -08001656
1657 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1658 return;
1659 }
1660
1661 nsecs_t currentTime = systemTime();
1662 if (mHasPoweredOff) {
1663 mHasPoweredOff = false;
1664 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001665 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001666 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001667 if (numPeriods < NUM_BUCKETS - 1) {
1668 mFrameBuckets[numPeriods] += elapsedTime;
1669 } else {
1670 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1671 }
1672 mTotalTime += elapsedTime;
1673 }
1674 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675}
1676
1677void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001678 ATRACE_CALL();
1679 ALOGV("rebuildLayerStacks");
1680
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001682 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1683 ATRACE_CALL();
1684 mVisibleRegionsDirty = false;
1685 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001686
Jeff Sharkey76488112017-02-27 14:15:18 -07001687 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1688 Region opaqueRegion;
1689 Region dirtyRegion;
1690 Vector<sp<Layer>> layersSortedByZ;
1691 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1692 const Transform& tr(displayDevice->getTransform());
1693 const Rect bounds(displayDevice->getBounds());
1694 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001695 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001696
Jeff Sharkey76488112017-02-27 14:15:18 -07001697 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001698 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1699 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001700 Region drawRegion(tr.transform(
1701 layer->visibleNonTransparentRegion));
1702 drawRegion.andSelf(bounds);
1703 if (!drawRegion.isEmpty()) {
1704 layersSortedByZ.add(layer);
1705 } else {
1706 // Clear out the HWC layer if this layer was
1707 // previously visible, but no longer is
Steven Thomasd7f49c52017-07-26 18:48:28 -07001708 layer->destroyHwcLayer(
1709 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001710 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001711 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001712 // WM changes displayDevice->layerStack upon sleep/awake.
1713 // Here we make sure we delete the HWC layers even if
1714 // WM changed their layer stack.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001715 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001716 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001717 });
1718 }
1719 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1720 displayDevice->undefinedRegion.set(bounds);
1721 displayDevice->undefinedRegion.subtractSelf(
1722 tr.transform(opaqueRegion));
1723 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001724 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001725 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001726}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001727
Romain Guy0147a172017-06-01 13:53:56 -07001728mat4 SurfaceFlinger::computeSaturationMatrix() const {
1729 if (mSaturation == 1.0f) {
1730 return mat4();
1731 }
1732
1733 // Rec.709 luma coefficients
1734 float3 luminance{0.213f, 0.715f, 0.072f};
1735 luminance *= 1.0f - mSaturation;
1736 return mat4(
1737 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1738 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1739 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1740 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1741 );
1742}
1743
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001744// pickColorMode translates a given dataspace into the best available color mode.
1745// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001746android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001747 switch (dataSpace) {
1748 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1749 // system expects.
1750 case HAL_DATASPACE_UNKNOWN:
1751 case HAL_DATASPACE_SRGB:
1752 case HAL_DATASPACE_V0_SRGB:
1753 return HAL_COLOR_MODE_SRGB;
1754 break;
1755
1756 case HAL_DATASPACE_DISPLAY_P3:
1757 return HAL_COLOR_MODE_DISPLAY_P3;
1758 break;
1759
1760 default:
1761 // TODO (courtneygo): Do we want to assert an error here?
1762 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1763 dataSpace);
1764 return HAL_COLOR_MODE_SRGB;
1765 break;
1766 }
1767}
1768
Romain Guy0147a172017-06-01 13:53:56 -07001769android_dataspace SurfaceFlinger::bestTargetDataSpace(
1770 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001771 // Only support sRGB and Display-P3 right now.
1772 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1773 return HAL_DATASPACE_DISPLAY_P3;
1774 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001775 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1776 return HAL_DATASPACE_DISPLAY_P3;
1777 }
1778 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1779 return HAL_DATASPACE_DISPLAY_P3;
1780 }
1781
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001782 return HAL_DATASPACE_V0_SRGB;
1783}
1784
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001786 ATRACE_CALL();
1787 ALOGV("setUpHWComposer");
1788
Jesse Hall028dc8f2013-08-20 16:35:32 -07001789 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001790 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1791 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1792 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1793
1794 // If nothing has changed (!dirty), don't recompose.
1795 // If something changed, but we don't currently have any visible layers,
1796 // and didn't when we last did a composition, then skip it this time.
1797 // The second rule does two things:
1798 // - When all layers are removed from a display, we'll emit one black
1799 // frame, then nothing more until we get new layers.
1800 // - When a display is created with a private layer stack, we won't
1801 // emit any black frames until a layer is added to the layer stack.
1802 bool mustRecompose = dirty && !(empty && wasEmpty);
1803
1804 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1805 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1806 mustRecompose ? "doing" : "skipping",
1807 dirty ? "+" : "-",
1808 empty ? "+" : "-",
1809 wasEmpty ? "+" : "-");
1810
Dan Stoza71433162014-02-04 16:22:36 -08001811 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001812
1813 if (mustRecompose) {
1814 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1815 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001816 }
1817
Dan Stoza9e56aa02015-11-02 13:00:03 -08001818 // build the h/w work list
1819 if (CC_UNLIKELY(mGeometryInvalid)) {
1820 mGeometryInvalid = false;
1821 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1822 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1823 const auto hwcId = displayDevice->getHwcDisplayId();
1824 if (hwcId >= 0) {
1825 const Vector<sp<Layer>>& currentLayers(
1826 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001827 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001828 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001829 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001830 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001831 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001833 }
1834 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001835
Robert Carrae060832016-11-28 10:51:00 -08001836 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001837 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001838 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001839 }
1840 }
1841 }
1842 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 }
Riley Andrews03414a12014-07-01 14:22:59 -07001844
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001845
Romain Guy0147a172017-06-01 13:53:56 -07001846 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001847
Dan Stoza9e56aa02015-11-02 13:00:03 -08001848 // Set the per-frame data
1849 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1850 auto& displayDevice = mDisplays[displayId];
1851 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001852
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 if (hwcId < 0) {
1854 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001855 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001856 if (colorMatrix != mPreviousColorMatrix) {
1857 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1858 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1859 "display %zd: %d", displayId, result);
1860 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1862 layer->setPerFrameData(displayDevice);
1863 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001864
1865 if (hasWideColorDisplay) {
1866 android_color_mode newColorMode;
1867 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1868
1869 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1870 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1871 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1872 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1873 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1874 }
1875 newColorMode = pickColorMode(newDataSpace);
1876
Romain Guyc53d3552017-07-20 18:49:46 -07001877 // We want the color mode of the boot animation to match that of the bootloader
1878 // To achieve this we suppress color mode changes until after the boot animation
1879 if (mBootFinished) {
1880 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001881 displayDevice->setCompositionDataSpace(newDataSpace);
Romain Guyc53d3552017-07-20 18:49:46 -07001882 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001883 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 }
1885
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001886 mPreviousColorMatrix = colorMatrix;
1887
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001889 auto& displayDevice = mDisplays[displayId];
1890 if (!displayDevice->isDisplayOn()) {
1891 continue;
1892 }
1893
1894 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1896 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001897 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001898}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001899
Mathias Agopiancd60f992012-08-16 16:28:27 -07001900void SurfaceFlinger::doComposition() {
1901 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 ALOGV("doComposition");
1903
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001904 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001905 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001906 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001907 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001908 // transform the dirty region into this screen's coordinate space
1909 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001910
1911 // repaint the framebuffer (if needed)
1912 doDisplayComposition(hw, dirtyRegion);
1913
Mathias Agopiancd60f992012-08-16 16:28:27 -07001914 hw->dirtyRegion.clear();
1915 hw->flip(hw->swapRegion);
1916 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001917 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001918 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001919 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001920}
1921
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001922void SurfaceFlinger::postFramebuffer()
1923{
Mathias Agopian841cde52012-03-01 15:44:37 -08001924 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001925 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001926
Mathias Agopiana44b0412011-10-16 18:46:35 -07001927 const nsecs_t now = systemTime();
1928 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001929
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1931 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001932 if (!displayDevice->isDisplayOn()) {
1933 continue;
1934 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001935 const auto hwcId = displayDevice->getHwcDisplayId();
1936 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001937 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001938 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001939 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001940 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1942 sp<Fence> releaseFence = Fence::NO_FENCE;
1943 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1944 releaseFence = displayDevice->getClientTargetAcquireFence();
1945 } else {
1946 auto hwcLayer = layer->getHwcLayer(hwcId);
1947 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001948 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001949 layer->onLayerDisplayed(releaseFence);
1950 }
1951 if (hwcId >= 0) {
1952 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001953 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001954 }
1955
Mathias Agopiana44b0412011-10-16 18:46:35 -07001956 mLastSwapBufferTime = systemTime() - now;
1957 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001958
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001959 // |mStateLock| not needed as we are on the main thread
1960 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001961 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1962 logFrameStats();
1963 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001964}
1965
Mathias Agopian87baae12012-07-31 12:38:26 -07001966void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001967{
Mathias Agopian841cde52012-03-01 15:44:37 -08001968 ATRACE_CALL();
1969
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001970 // here we keep a copy of the drawing state (that is the state that's
1971 // going to be overwritten by handleTransactionLocked()) outside of
1972 // mStateLock so that the side-effects of the State assignment
1973 // don't happen with mStateLock held (which can cause deadlocks).
1974 State drawingState(mDrawingState);
1975
Mathias Agopianca4d3602011-05-19 15:38:14 -07001976 Mutex::Autolock _l(mStateLock);
1977 const nsecs_t now = systemTime();
1978 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001979
Mathias Agopianca4d3602011-05-19 15:38:14 -07001980 // Here we're guaranteed that some transaction flags are set
1981 // so we can call handleTransactionLocked() unconditionally.
1982 // We call getTransactionFlags(), which will also clear the flags,
1983 // with mStateLock held to guarantee that mCurrentState won't change
1984 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001985
Mathias Agopiane57f2922012-08-09 16:29:12 -07001986 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001987 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001988
Mathias Agopianca4d3602011-05-19 15:38:14 -07001989 mLastTransactionTime = systemTime() - now;
1990 mDebugInTransaction = 0;
1991 invalidateHwcGeometry();
1992 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001993}
1994
Mathias Agopian87baae12012-07-31 12:38:26 -07001995void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001996{
Dan Stoza7dde5992015-05-22 09:51:44 -07001997 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001998 mCurrentState.traverseInZOrder([](Layer* layer) {
1999 layer->notifyAvailableFrames();
2000 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002001
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002002 /*
2003 * Traversal of the children
2004 * (perform the transaction for each of them if needed)
2005 */
2006
Mathias Agopian3559b072012-08-15 13:46:03 -07002007 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002008 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002009 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002010 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002011
2012 const uint32_t flags = layer->doTransaction(0);
2013 if (flags & Layer::eVisibleRegion)
2014 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002015 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016 }
2017
2018 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002019 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002020 */
2021
Mathias Agopiane57f2922012-08-09 16:29:12 -07002022 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002023 // here we take advantage of Vector's copy-on-write semantics to
2024 // improve performance by skipping the transaction entirely when
2025 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002026 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2027 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002028 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002029 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002030 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002031 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002032
2033 // find the displays that were removed
2034 // (ie: in drawing state but not in current state)
2035 // also handle displays that changed
2036 // (ie: displays that are in both lists)
2037 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002038 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2039 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002040 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002041 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002042 // Call makeCurrent() on the primary display so we can
2043 // be sure that nothing associated with this display
2044 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002045 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002046 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002047 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002048 if (hw != NULL)
2049 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002050 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002051 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002052 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002053 } else {
2054 ALOGW("trying to remove the main display");
2055 }
2056 } else {
2057 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002058 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002059 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002060 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2061 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002062 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002063 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002064 // recreating the DisplayDevice, so we just remove it
2065 // from the drawing state, so that it get re-added
2066 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002067 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002068 if (hw != NULL)
2069 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002070 mDisplays.removeItem(display);
2071 mDrawingState.displays.removeItemsAt(i);
2072 dc--; i--;
2073 // at this point we must loop to the next item
2074 continue;
2075 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002076
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002077 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002078 if (disp != NULL) {
2079 if (state.layerStack != draw[i].layerStack) {
2080 disp->setLayerStack(state.layerStack);
2081 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002082 if ((state.orientation != draw[i].orientation)
2083 || (state.viewport != draw[i].viewport)
2084 || (state.frame != draw[i].frame))
2085 {
2086 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002087 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002088 }
Michael Lentine47e45402014-07-18 15:34:25 -07002089 if (state.width != draw[i].width || state.height != draw[i].height) {
2090 disp->setDisplaySize(state.width, state.height);
2091 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002092 }
2093 }
2094 }
2095
2096 // find displays that were added
2097 // (ie: in current state but not in drawing state)
2098 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002099 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002100 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002101
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002102 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002103 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002104 sp<IGraphicBufferProducer> bqProducer;
2105 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002106 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002107
Dan Stoza9e56aa02015-11-02 13:00:03 -08002108 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002109 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002110 // Virtual displays without a surface are dormant:
2111 // they have external state (layer stack, projection,
2112 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002113 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002114
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002115 // Allow VR composer to use virtual displays.
Steven Thomasd7f49c52017-07-26 18:48:28 -07002116 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002117 int width = 0;
2118 int status = state.surface->query(
2119 NATIVE_WINDOW_WIDTH, &width);
2120 ALOGE_IF(status != NO_ERROR,
2121 "Unable to query width (%d)", status);
2122 int height = 0;
2123 status = state.surface->query(
2124 NATIVE_WINDOW_HEIGHT, &height);
2125 ALOGE_IF(status != NO_ERROR,
2126 "Unable to query height (%d)", status);
2127 int intFormat = 0;
2128 status = state.surface->query(
2129 NATIVE_WINDOW_FORMAT, &intFormat);
2130 ALOGE_IF(status != NO_ERROR,
2131 "Unable to query format (%d)", status);
2132 auto format = static_cast<android_pixel_format_t>(
2133 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002134
Dan Stoza8cf150a2016-08-02 10:27:31 -07002135 mHwc->allocateVirtualDisplay(width, height, &format,
2136 &hwcId);
2137 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002138
Dan Stoza5cf424b2016-05-20 14:02:39 -07002139 // TODO: Plumb requested format back up to consumer
2140
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 sp<VirtualDisplaySurface> vds =
2142 new VirtualDisplaySurface(*mHwc,
2143 hwcId, state.surface, bqProducer,
2144 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002145
2146 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002147 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002148 }
2149 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002150 ALOGE_IF(state.surface!=NULL,
2151 "adding a supported display, but rendering "
2152 "surface is provided (%p), ignoring it",
2153 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002154
2155 hwcId = state.type;
2156 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2157 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002158 }
2159
2160 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002161 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002162 sp<DisplayDevice> hw =
2163 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2164 dispSurface, producer,
2165 mRenderEngine->getEGLConfig(),
2166 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002167 hw->setLayerStack(state.layerStack);
2168 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002169 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002170 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002171 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002173 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002174 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002175 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002176 }
2177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002178 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002180
Mathias Agopian84300952012-11-21 16:02:13 -08002181 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2182 // The transform hint might have changed for some layers
2183 // (either because a display has changed, or because a layer
2184 // as changed).
2185 //
2186 // Walk through all the layers in currentLayers,
2187 // and update their transform hint.
2188 //
2189 // If a layer is visible only on a single display, then that
2190 // display is used to calculate the hint, otherwise we use the
2191 // default display.
2192 //
2193 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2194 // the hint is set before we acquire a buffer from the surface texture.
2195 //
2196 // NOTE: layer transactions have taken place already, so we use their
2197 // drawing state. However, SurfaceFlinger's own transaction has not
2198 // happened yet, so we must use the current state layer list
2199 // (soon to become the drawing state list).
2200 //
2201 sp<const DisplayDevice> disp;
2202 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002203 bool first = true;
2204 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002205 // NOTE: we rely on the fact that layers are sorted by
2206 // layerStack first (so we don't have to traverse the list
2207 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002208 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002209 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002210 currentlayerStack = layerStack;
2211 // figure out if this layerstack is mirrored
2212 // (more than one display) if so, pick the default display,
2213 // if not, pick the only display it's on.
2214 disp.clear();
2215 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2216 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002217 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002218 if (disp == NULL) {
2219 disp = hw;
2220 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002221 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002222 break;
2223 }
2224 }
2225 }
2226 }
Chet Haase91d25932013-04-11 15:24:55 -07002227 if (disp == NULL) {
2228 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2229 // redraw after transform hint changes. See bug 8508397.
2230
2231 // could be null when this layer is using a layerStack
2232 // that is not visible on any display. Also can occur at
2233 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002234 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002235 }
Chet Haase91d25932013-04-11 15:24:55 -07002236 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002237
2238 first = false;
2239 });
Mathias Agopian84300952012-11-21 16:02:13 -08002240 }
2241
2242
Mathias Agopian3559b072012-08-15 13:46:03 -07002243 /*
2244 * Perform our own transaction if needed
2245 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002246
2247 if (mLayersAdded) {
2248 mLayersAdded = false;
2249 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002250 mVisibleRegionsDirty = true;
2251 }
2252
2253 // some layers might have been removed, so
2254 // we need to update the regions they're exposing.
2255 if (mLayersRemoved) {
2256 mLayersRemoved = false;
2257 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002258 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002259 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002260 // this layer is not visible anymore
2261 // TODO: we could traverse the tree from front to back and
2262 // compute the actual visible region
2263 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002264 Region visibleReg;
2265 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002266 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002267 }
Robert Carr2047fae2016-11-28 14:09:09 -08002268 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002269 }
2270
2271 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002272
2273 updateCursorAsync();
2274}
2275
2276void SurfaceFlinger::updateCursorAsync()
2277{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2279 auto& displayDevice = mDisplays[displayId];
2280 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002281 continue;
2282 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002283
2284 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2285 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002286 }
2287 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002288}
2289
2290void SurfaceFlinger::commitTransaction()
2291{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002292 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002293 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002294 for (const auto& l : mLayersPendingRemoval) {
2295 recordBufferingStats(l->getName().string(),
2296 l->getOccupancyHistory(true));
2297 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002298 }
2299 mLayersPendingRemoval.clear();
2300 }
2301
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002302 // If this transaction is part of a window animation then the next frame
2303 // we composite should be considered an animation as well.
2304 mAnimCompositionPending = mAnimTransactionPending;
2305
Mathias Agopian4fec8732012-06-29 14:12:52 -07002306 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002307 mDrawingState.traverseInZOrder([](Layer* layer) {
2308 layer->commitChildList();
2309 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002310 mTransactionPending = false;
2311 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002312 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002313}
2314
Chia-I Wuab0c3192017-08-01 11:29:00 -07002315void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002316 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317{
Mathias Agopian841cde52012-03-01 15:44:37 -08002318 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002319 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002320
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002321 Region aboveOpaqueLayers;
2322 Region aboveCoveredLayers;
2323 Region dirty;
2324
Mathias Agopian87baae12012-07-31 12:38:26 -07002325 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326
Robert Carr2047fae2016-11-28 14:09:09 -08002327 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002329 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002330
Jesse Hall01e29052013-02-19 16:13:35 -08002331 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002332 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002333 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002334
Mathias Agopianab028732010-03-16 16:41:46 -07002335 /*
2336 * opaqueRegion: area of a surface that is fully opaque.
2337 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002338 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002339
2340 /*
2341 * visibleRegion: area of a surface that is visible on screen
2342 * and not fully transparent. This is essentially the layer's
2343 * footprint minus the opaque regions above it.
2344 * Areas covered by a translucent surface are considered visible.
2345 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002347
2348 /*
2349 * coveredRegion: area of a surface that is covered by all
2350 * visible regions above it (which includes the translucent areas).
2351 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002353
Jesse Halla8026d22012-09-25 13:25:04 -07002354 /*
2355 * transparentRegion: area of a surface that is hinted to be completely
2356 * transparent. This is only used to tell when the layer has no visible
2357 * non-transparent regions and can be removed from the layer list. It
2358 * does not affect the visibleRegion of this layer or any layers
2359 * beneath it. The hint may not be correct if apps don't respect the
2360 * SurfaceView restrictions (which, sadly, some don't).
2361 */
2362 Region transparentRegion;
2363
Mathias Agopianab028732010-03-16 16:41:46 -07002364
2365 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002366 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002367 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002368 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002370 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002371 if (!visibleRegion.isEmpty()) {
2372 // Remove the transparent area from the visible region
2373 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002374 if (tr.preserveRects()) {
2375 // transform the transparent region
2376 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002377 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002378 // transformation too complex, can't do the
2379 // transparent region optimization.
2380 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002381 }
Mathias Agopianab028732010-03-16 16:41:46 -07002382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002383
Mathias Agopianab028732010-03-16 16:41:46 -07002384 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002385 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002386 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002387 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2388 // the opaque region is the layer's footprint
2389 opaqueRegion = visibleRegion;
2390 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391 }
2392 }
2393
Mathias Agopianab028732010-03-16 16:41:46 -07002394 // Clip the covered region to the visible region
2395 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2396
2397 // Update aboveCoveredLayers for next (lower) layer
2398 aboveCoveredLayers.orSelf(visibleRegion);
2399
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 // subtract the opaque region covered by the layers above us
2401 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002402
2403 // compute this layer's dirty region
2404 if (layer->contentDirty) {
2405 // we need to invalidate the whole region
2406 dirty = visibleRegion;
2407 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002408 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409 layer->contentDirty = false;
2410 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002411 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002412 * the exposed region consists of two components:
2413 * 1) what's VISIBLE now and was COVERED before
2414 * 2) what's EXPOSED now less what was EXPOSED before
2415 *
2416 * note that (1) is conservative, we start with the whole
2417 * visible region but only keep what used to be covered by
2418 * something -- which mean it may have been exposed.
2419 *
2420 * (2) handles areas that were not covered by anything but got
2421 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002422 */
Mathias Agopianab028732010-03-16 16:41:46 -07002423 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424 const Region oldVisibleRegion = layer->visibleRegion;
2425 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002426 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2427 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 }
2429 dirty.subtractSelf(aboveOpaqueLayers);
2430
2431 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002432 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002433
Mathias Agopianab028732010-03-16 16:41:46 -07002434 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002436
Jesse Halla8026d22012-09-25 13:25:04 -07002437 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002438 layer->setVisibleRegion(visibleRegion);
2439 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002440 layer->setVisibleNonTransparentRegion(
2441 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002442 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002443
Mathias Agopian87baae12012-07-31 12:38:26 -07002444 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445}
2446
Chia-I Wuab0c3192017-08-01 11:29:00 -07002447void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002448 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002449 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002450 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002451 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002452 }
2453 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002454}
2455
Dan Stoza6b9454d2014-11-07 16:00:59 -08002456bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002458 ALOGV("handlePageFlip");
2459
Brian Andersond6927fb2016-07-23 23:37:30 -07002460 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461
Mathias Agopian4fec8732012-06-29 14:12:52 -07002462 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002463 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002464 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002465
2466 // Store the set of layers that need updates. This set must not change as
2467 // buffers are being latched, as this could result in a deadlock.
2468 // Example: Two producers share the same command stream and:
2469 // 1.) Layer 0 is latched
2470 // 2.) Layer 0 gets a new frame
2471 // 2.) Layer 1 gets a new frame
2472 // 3.) Layer 1 is latched.
2473 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2474 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002475 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002476 if (layer->hasQueuedFrame()) {
2477 frameQueued = true;
2478 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002479 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002480 } else {
2481 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002482 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002483 } else {
2484 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002485 }
Robert Carr2047fae2016-11-28 14:09:09 -08002486 });
2487
Dan Stoza9e56aa02015-11-02 13:00:03 -08002488 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002489 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002490 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002491 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002492 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002493 newDataLatched = true;
2494 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002495 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002496
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002497 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002498
2499 // If we will need to wake up at some time in the future to deal with a
2500 // queued frame that shouldn't be displayed during this vsync period, wake
2501 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002502 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002503 signalLayerUpdate();
2504 }
2505
2506 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002507 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508}
2509
Mathias Agopianad456f92011-01-13 17:53:01 -08002510void SurfaceFlinger::invalidateHwcGeometry()
2511{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002512 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002513}
2514
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002515
Fabien Sanglard830b8472016-11-30 16:35:58 -08002516void SurfaceFlinger::doDisplayComposition(
2517 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002518 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002519{
Dan Stoza71433162014-02-04 16:22:36 -08002520 // We only need to actually compose the display if:
2521 // 1) It is being handled by hardware composer, which may need this to
2522 // keep its virtual display state machine in sync, or
2523 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002524 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002525 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002526 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002527 return;
2528 }
2529
Dan Stoza9e56aa02015-11-02 13:00:03 -08002530 ALOGV("doDisplayComposition");
2531
Mathias Agopian87baae12012-07-31 12:38:26 -07002532 Region dirtyRegion(inDirtyRegion);
2533
Mathias Agopianb8a55602009-06-26 19:06:36 -07002534 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002535 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536
Fabien Sanglard830b8472016-11-30 16:35:58 -08002537 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002538 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002539 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2540 // takes a rectangle, we must make sure to update that whole
2541 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002542 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002543 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002544 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002545 // We need to redraw the rectangle that will be updated
2546 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002547 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002548 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002549 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002550 } else {
2551 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002552 dirtyRegion.set(displayDevice->bounds());
2553 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 }
2555 }
2556
Fabien Sanglard830b8472016-11-30 16:35:58 -08002557 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002559 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002560 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002561
2562 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002563 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002564}
2565
Dan Stoza9e56aa02015-11-02 13:00:03 -08002566bool SurfaceFlinger::doComposeSurfaces(
2567 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002568{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002570
Dan Stoza9e56aa02015-11-02 13:00:03 -08002571 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002572
2573 mat4 oldColorMatrix;
2574 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2575 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2576 if (applyColorMatrix) {
2577 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2578 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2579 }
2580
Dan Stoza9e56aa02015-11-02 13:00:03 -08002581 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2582 if (hasClientComposition) {
2583 ALOGV("hasClientComposition");
2584
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002585#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002586 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002587 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002588#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002590 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002591 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002592 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002593
2594 // |mStateLock| not needed as we are on the main thread
2595 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002596 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2597 }
2598 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002599 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002600
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002601 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002602 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2603 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002604 // when using overlays, we assume a fully transparent framebuffer
2605 // NOTE: we could reduce how much we need to clear, for instance
2606 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002607 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002608 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002610 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002611 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002612 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002613
2614 // we remove the scissor part
2615 // we're left with the letterbox region
2616 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002618
2619 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002621
2622 // but limit it to the dirty region
2623 region.andSelf(dirty);
2624
Mathias Agopianb9494d52012-04-18 02:28:45 -07002625 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002626 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002627 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002628 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002629 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002630 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002631
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002633 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002634 // scissor on the main display. It should never be needed
2635 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002636 const Rect& bounds(displayDevice->getBounds());
2637 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002638 if (scissor != bounds) {
2639 // scissor doesn't match the screen's dimensions, so we
2640 // need to clear everything outside of it and enable
2641 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002642
Mathias Agopianf45c5102012-10-24 16:29:17 -07002643 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 const uint32_t height = displayDevice->getHeight();
2645 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002646 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002647 }
2648 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002649 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002650
Mathias Agopian85d751c2012-08-29 16:59:24 -07002651 /*
2652 * and then, render the layers targeted at the framebuffer
2653 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002654
Dan Stoza9e56aa02015-11-02 13:00:03 -08002655 ALOGV("Rendering client layers");
2656 const Transform& displayTransform = displayDevice->getTransform();
2657 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002658 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 bool firstLayer = true;
2660 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2661 const Region clip(dirty.intersect(
2662 displayTransform.transform(layer->visibleRegion)));
2663 ALOGV("Layer: %s", layer->getName().string());
2664 ALOGV(" Composition type: %s",
2665 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002666 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002667 switch (layer->getCompositionType(hwcId)) {
2668 case HWC2::Composition::Cursor:
2669 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002670 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002672 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2674 layer->isOpaque(state) && (state.alpha == 1.0f)
2675 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002676 // never clear the very first layer since we're
2677 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002678 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002679 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002680 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002681 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002682 case HWC2::Composition::Client: {
2683 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002684 break;
2685 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002686 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002687 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002688 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 } else {
2690 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002691 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002692 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002693 }
2694 } else {
2695 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002697 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002698 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002699 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002700 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002701 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002702 }
2703 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002704
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002705 if (applyColorMatrix) {
2706 getRenderEngine().setupColorTransform(oldColorMatrix);
2707 }
2708
Mathias Agopianf45c5102012-10-24 16:29:17 -07002709 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002710 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002711 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712}
2713
Fabien Sanglard830b8472016-11-30 16:35:58 -08002714void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2715 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002716 RenderEngine& engine(getRenderEngine());
2717 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718}
2719
Dan Stoza7d89d062015-04-30 13:29:25 -07002720status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002721 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002722 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 const sp<Layer>& lbc,
2724 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002725{
Dan Stoza7d89d062015-04-30 13:29:25 -07002726 // add this layer to the current state list
2727 {
2728 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002729 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002730 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2731 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002732 return NO_MEMORY;
2733 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 if (parent == nullptr) {
2735 mCurrentState.layersSortedByZ.add(lbc);
2736 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002737 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2738 ALOGE("addClientLayer called with a removed parent");
2739 return NAME_NOT_FOUND;
2740 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 parent->addChild(lbc);
2742 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002743
Dan Stoza7d89d062015-04-30 13:29:25 -07002744 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002745 mLayersAdded = true;
2746 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002747 }
2748
Mathias Agopian96f08192010-06-02 23:28:45 -07002749 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002750 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002751
Dan Stoza7d89d062015-04-30 13:29:25 -07002752 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002753}
2754
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002755status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002756 Mutex::Autolock _l(mStateLock);
2757
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002759 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002760 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002761 if (topLevelOnly) {
2762 return NO_ERROR;
2763 }
2764
Chia-I Wu98f1c102017-05-30 14:54:08 -07002765 sp<Layer> ancestor = p;
2766 while (ancestor->getParent() != nullptr) {
2767 ancestor = ancestor->getParent();
2768 }
2769 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2770 ALOGE("removeLayer called with a layer whose parent has been removed");
2771 return NAME_NOT_FOUND;
2772 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002773
2774 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002775 } else {
2776 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002777 }
2778
Robert Carr136e2f62017-02-08 17:54:29 -08002779 // As a matter of normal operation, the LayerCleaner will produce a second
2780 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2781 // so we will succeed in promoting it, but it's already been removed
2782 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2783 // otherwise something has gone wrong and we are leaking the layer.
2784 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2786 layer->getName().string(),
2787 (p != nullptr) ? p->getName().string() : "no-parent");
2788 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002789 } else if (index < 0) {
2790 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002791 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792
Chia-I Wuc6657022017-08-15 11:18:17 -07002793 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002794 mLayersPendingRemoval.add(layer);
2795 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002796 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002797 setTransactionFlags(eTransactionNeeded);
2798 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799}
2800
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002801uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002802 return android_atomic_release_load(&mTransactionFlags);
2803}
2804
Mathias Agopian3f844832013-08-07 21:24:32 -07002805uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2807}
2808
Mathias Agopian3f844832013-08-07 21:24:32 -07002809uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2811 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002812 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 }
2814 return old;
2815}
2816
Mathias Agopian8b33f032012-07-24 20:43:54 -07002817void SurfaceFlinger::setTransactionState(
2818 const Vector<ComposerState>& state,
2819 const Vector<DisplayState>& displays,
2820 uint32_t flags)
2821{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002822 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002823 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002824 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002825
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002826 if (flags & eAnimation) {
2827 // For window updates that are part of an animation we must wait for
2828 // previous animation "frames" to be handled.
2829 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002830 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002831 if (CC_UNLIKELY(err != NO_ERROR)) {
2832 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002833 // caller after a few seconds.
2834 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2835 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002836 mAnimTransactionPending = false;
2837 break;
2838 }
2839 }
2840 }
2841
Mathias Agopiane57f2922012-08-09 16:29:12 -07002842 size_t count = displays.size();
2843 for (size_t i=0 ; i<count ; i++) {
2844 const DisplayState& s(displays[i]);
2845 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002846 }
2847
Mathias Agopiane57f2922012-08-09 16:29:12 -07002848 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002849 for (size_t i=0 ; i<count ; i++) {
2850 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002851 // Here we need to check that the interface we're given is indeed
2852 // one of our own. A malicious client could give us a NULL
2853 // IInterface, or one of its own or even one of our own but a
2854 // different type. All these situations would cause us to crash.
2855 //
2856 // NOTE: it would be better to use RTTI as we could directly check
2857 // that we have a Client*. however, RTTI is disabled in Android.
2858 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002859 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002860 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002861 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002862 sp<Client> client( static_cast<Client *>(s.client.get()) );
2863 transactionFlags |= setClientStateLocked(client, s.state);
2864 }
2865 }
2866 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002867 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002868
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002869 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2870 // anyway. This can be used as a flush mechanism for previous async transactions.
2871 // Empty animation transaction can be used to simulate back-pressure, so also force a
2872 // transaction for empty animation transactions.
2873 if (transactionFlags == 0 &&
2874 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002875 transactionFlags = eTransactionNeeded;
2876 }
2877
Mathias Agopian386aa982011-11-07 21:58:03 -08002878 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002879 if (mInterceptor.isEnabled()) {
2880 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2881 }
Irvel468051e2016-06-13 16:44:44 -07002882
Mathias Agopian386aa982011-11-07 21:58:03 -08002883 // this triggers the transaction
2884 setTransactionFlags(transactionFlags);
2885
2886 // if this is a synchronous transaction, wait for it to take effect
2887 // before returning.
2888 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002889 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002890 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002891 if (flags & eAnimation) {
2892 mAnimTransactionPending = true;
2893 }
2894 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002895 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2896 if (CC_UNLIKELY(err != NO_ERROR)) {
2897 // just in case something goes wrong in SF, return to the
2898 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002899 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2900 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002901 break;
2902 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002903 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 }
2905}
2906
Mathias Agopiane57f2922012-08-09 16:29:12 -07002907uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2908{
Jesse Hall9a143922012-10-04 16:29:19 -07002909 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2910 if (dpyIdx < 0)
2911 return 0;
2912
Mathias Agopiane57f2922012-08-09 16:29:12 -07002913 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002914 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002915 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002916 const uint32_t what = s.what;
2917 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002918 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002919 disp.surface = s.surface;
2920 flags |= eDisplayTransactionNeeded;
2921 }
2922 }
2923 if (what & DisplayState::eLayerStackChanged) {
2924 if (disp.layerStack != s.layerStack) {
2925 disp.layerStack = s.layerStack;
2926 flags |= eDisplayTransactionNeeded;
2927 }
2928 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002929 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002930 if (disp.orientation != s.orientation) {
2931 disp.orientation = s.orientation;
2932 flags |= eDisplayTransactionNeeded;
2933 }
2934 if (disp.frame != s.frame) {
2935 disp.frame = s.frame;
2936 flags |= eDisplayTransactionNeeded;
2937 }
2938 if (disp.viewport != s.viewport) {
2939 disp.viewport = s.viewport;
2940 flags |= eDisplayTransactionNeeded;
2941 }
2942 }
Michael Lentine47e45402014-07-18 15:34:25 -07002943 if (what & DisplayState::eDisplaySizeChanged) {
2944 if (disp.width != s.width) {
2945 disp.width = s.width;
2946 flags |= eDisplayTransactionNeeded;
2947 }
2948 if (disp.height != s.height) {
2949 disp.height = s.height;
2950 flags |= eDisplayTransactionNeeded;
2951 }
2952 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002953 }
2954 return flags;
2955}
2956
2957uint32_t SurfaceFlinger::setClientStateLocked(
2958 const sp<Client>& client,
2959 const layer_state_t& s)
2960{
2961 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002962 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002963 if (layer != 0) {
2964 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002965 bool geometryAppliesWithResize =
2966 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002967 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002968 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002969 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002970 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002971 }
2972 if (what & layer_state_t::eLayerChanged) {
2973 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002974 const auto& p = layer->getParent();
2975 if (p == nullptr) {
2976 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2977 if (layer->setLayer(s.z) && idx >= 0) {
2978 mCurrentState.layersSortedByZ.removeAt(idx);
2979 mCurrentState.layersSortedByZ.add(layer);
2980 // we need traversal (state changed)
2981 // AND transaction (list changed)
2982 flags |= eTransactionNeeded|eTraversalNeeded;
2983 }
2984 } else {
2985 if (p->setChildLayer(layer, s.z)) {
2986 flags |= eTransactionNeeded|eTraversalNeeded;
2987 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002988 }
2989 }
Robert Carrdb66e622017-04-10 16:55:57 -07002990 if (what & layer_state_t::eRelativeLayerChanged) {
2991 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2992 flags |= eTransactionNeeded|eTraversalNeeded;
2993 }
2994 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002995 if (what & layer_state_t::eSizeChanged) {
2996 if (layer->setSize(s.w, s.h)) {
2997 flags |= eTraversalNeeded;
2998 }
2999 }
3000 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003001 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 flags |= eTraversalNeeded;
3003 }
3004 if (what & layer_state_t::eMatrixChanged) {
3005 if (layer->setMatrix(s.matrix))
3006 flags |= eTraversalNeeded;
3007 }
3008 if (what & layer_state_t::eTransparentRegionChanged) {
3009 if (layer->setTransparentRegionHint(s.transparentRegion))
3010 flags |= eTraversalNeeded;
3011 }
Dan Stoza23116082015-06-18 14:58:39 -07003012 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003013 if (layer->setFlags(s.flags, s.mask))
3014 flags |= eTraversalNeeded;
3015 }
3016 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003017 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003018 flags |= eTraversalNeeded;
3019 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003020 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003021 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003022 flags |= eTraversalNeeded;
3023 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003024 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003025 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003026 // We only allow setting layer stacks for top level layers,
3027 // everything else inherits layer stack from its parent.
3028 if (layer->hasParent()) {
3029 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3030 layer->getName().string());
3031 } else if (idx < 0) {
3032 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3033 "that also does not appear in the top level layer list. Something"
3034 " has gone wrong.", layer->getName().string());
3035 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003036 mCurrentState.layersSortedByZ.removeAt(idx);
3037 mCurrentState.layersSortedByZ.add(layer);
3038 // we need traversal (state changed)
3039 // AND transaction (list changed)
3040 flags |= eTransactionNeeded|eTraversalNeeded;
3041 }
3042 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003043 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003044 if (s.barrierHandle != nullptr) {
3045 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3046 } else if (s.barrierGbp != nullptr) {
3047 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3048 if (authenticateSurfaceTextureLocked(gbp)) {
3049 const auto& otherLayer =
3050 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3051 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3052 } else {
3053 ALOGE("Attempt to defer transaction to to an"
3054 " unrecognized GraphicBufferProducer");
3055 }
3056 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003057 // We don't trigger a traversal here because if no other state is
3058 // changed, we don't want this to cause any more work
3059 }
Robert Carr1db73f62016-12-21 12:58:51 -08003060 if (what & layer_state_t::eReparentChildren) {
3061 if (layer->reparentChildren(s.reparentHandle)) {
3062 flags |= eTransactionNeeded|eTraversalNeeded;
3063 }
3064 }
Robert Carr9524cb32017-02-13 11:32:32 -08003065 if (what & layer_state_t::eDetachChildren) {
3066 layer->detachChildren();
3067 }
Robert Carrc3574f72016-03-24 12:19:32 -07003068 if (what & layer_state_t::eOverrideScalingModeChanged) {
3069 layer->setOverrideScalingMode(s.overrideScalingMode);
3070 // We don't trigger a traversal here because if no other state is
3071 // changed, we don't want this to cause any more work
3072 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003073 }
3074 return flags;
3075}
3076
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003077status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003078 const String8& name,
3079 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003080 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003081 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3082 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003084 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003085 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003086 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003087 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003088 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003089
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003090 status_t result = NO_ERROR;
3091
3092 sp<Layer> layer;
3093
Cody Northropbc755282017-03-31 12:00:08 -06003094 String8 uniqueName = getUniqueLayerName(name);
3095
Mathias Agopian3165cc22012-08-08 19:42:09 -07003096 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3097 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003098 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003099 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003100 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003102 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003103 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003104 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003105 handle, gbp, &layer);
3106 break;
3107 default:
3108 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 break;
3110 }
3111
Dan Stoza7d89d062015-04-30 13:29:25 -07003112 if (result != NO_ERROR) {
3113 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003115
Chia-I Wuab0c3192017-08-01 11:29:00 -07003116 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3117 // TODO b/64227542
3118 if (windowType == 441731) {
3119 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3120 layer->setPrimaryDisplayOnly();
3121 }
3122
Albert Chaulk479c60c2017-01-27 14:21:34 -05003123 layer->setInfo(windowType, ownerUid);
3124
Robert Carr1f0a16a2016-10-24 16:27:39 -07003125 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003126 if (result != NO_ERROR) {
3127 return result;
3128 }
Irvelffc9efc2016-07-27 15:16:37 -07003129 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003130
3131 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003132 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003133}
3134
Cody Northropbc755282017-03-31 12:00:08 -06003135String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3136{
3137 bool matchFound = true;
3138 uint32_t dupeCounter = 0;
3139
3140 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3141 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3142
3143 // Loop over layers until we're sure there is no matching name
3144 while (matchFound) {
3145 matchFound = false;
3146 mDrawingState.traverseInZOrder([&](Layer* layer) {
3147 if (layer->getName() == uniqueName) {
3148 matchFound = true;
3149 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3150 }
3151 });
3152 }
3153
3154 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3155
3156 return uniqueName;
3157}
3158
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003159status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3160 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3161 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162{
3163 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003164 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 case PIXEL_FORMAT_TRANSPARENT:
3166 case PIXEL_FORMAT_TRANSLUCENT:
3167 format = PIXEL_FORMAT_RGBA_8888;
3168 break;
3169 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003170 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 break;
3172 }
3173
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003174 *outLayer = new Layer(this, client, name, w, h, flags);
3175 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3176 if (err == NO_ERROR) {
3177 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003178 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003180
3181 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3182 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183}
3184
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003185status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3186 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3187 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003189 *outLayer = new LayerDim(this, client, name, w, h, flags);
3190 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003191 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003192 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003193}
3194
Mathias Agopianac9fa422013-02-11 16:40:36 -08003195status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196{
Robert Carr9524cb32017-02-13 11:32:32 -08003197 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003198 status_t err = NO_ERROR;
3199 sp<Layer> l(client->getLayerUser(handle));
3200 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003201 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003202 err = removeLayer(l);
3203 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3204 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003205 }
3206 return err;
3207}
3208
Mathias Agopian13127d82013-03-05 17:47:11 -08003209status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003210{
Mathias Agopian67106042013-03-14 19:18:13 -07003211 // called by ~LayerCleaner() when all references to the IBinder (handle)
3212 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003213 sp<Layer> l = layer.promote();
3214 if (l == nullptr) {
3215 // The layer has already been removed, carry on
3216 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003217 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003218 // If we have a parent, then we can continue to live as long as it does.
3219 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220}
3221
Mathias Agopianb60314a2012-04-10 22:09:54 -07003222// ---------------------------------------------------------------------------
3223
Andy McFadden13a082e2012-08-24 10:16:42 -07003224void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003225 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003226 Vector<ComposerState> state;
3227 Vector<DisplayState> displays;
3228 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003229 d.what = DisplayState::eDisplayProjectionChanged |
3230 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003231 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003232 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003233 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003234 d.frame.makeInvalid();
3235 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003236 d.width = 0;
3237 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003238 displays.add(d);
3239 setTransactionState(state, displays, 0);
Steven Thomasd7f49c52017-07-26 18:48:28 -07003240 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3241 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003242
Dan Stoza9e56aa02015-11-02 13:00:03 -08003243 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3244 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003245 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003246
Brian Andersond0010582017-03-07 13:20:31 -08003247 // Use phase of 0 since phase is not known.
3248 // Use latency of 0, which will snap to the ideal latency.
3249 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003250}
3251
3252void SurfaceFlinger::initializeDisplays() {
3253 class MessageScreenInitialized : public MessageBase {
3254 SurfaceFlinger* flinger;
3255 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003256 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003257 virtual bool handler() {
3258 flinger->onInitializeDisplays();
3259 return true;
3260 }
3261 };
3262 sp<MessageBase> msg = new MessageScreenInitialized(this);
3263 postMessageAsync(msg); // we may be called from main thread, use async message
3264}
3265
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003266void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasd7f49c52017-07-26 18:48:28 -07003267 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003268 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3269 this);
3270 int32_t type = hw->getDisplayType();
3271 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003272
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003273 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003274 return;
3275 }
3276
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003277 hw->setPowerMode(mode);
3278 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3279 ALOGW("Trying to set power mode for virtual display");
3280 return;
3281 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003282
Irvelffc9efc2016-07-27 15:16:37 -07003283 if (mInterceptor.isEnabled()) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003284 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003285 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3286 if (idx < 0) {
3287 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3288 return;
3289 }
3290 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3291 }
3292
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003293 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003294 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003295 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003296 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3297 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003298 // FIXME: eventthread only knows about the main display right now
3299 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003300 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003301 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003302
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003303 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003304 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003305 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003306
3307 struct sched_param param = {0};
3308 param.sched_priority = 1;
3309 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3310 ALOGW("Couldn't set SCHED_FIFO on display on");
3311 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003312 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003313 // Turn off the display
3314 struct sched_param param = {0};
3315 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3316 ALOGW("Couldn't set SCHED_OTHER on display off");
3317 }
3318
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003319 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003320 disableHardwareVsync(true); // also cancels any in-progress resync
3321
Mathias Agopiancde87a32012-09-13 14:09:01 -07003322 // FIXME: eventthread only knows about the main display right now
3323 mEventThread->onScreenReleased();
3324 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003325
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003326 getHwComposer().setPowerMode(type, mode);
3327 mVisibleRegionsDirty = true;
3328 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003329 } else if (mode == HWC_POWER_MODE_DOZE ||
3330 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003331 // Update display while dozing
3332 getHwComposer().setPowerMode(type, mode);
3333 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3334 // FIXME: eventthread only knows about the main display right now
3335 mEventThread->onScreenAcquired();
3336 resyncToHardwareVsync(true);
3337 }
3338 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3339 // Leave display going to doze
3340 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3341 disableHardwareVsync(true); // also cancels any in-progress resync
3342 // FIXME: eventthread only knows about the main display right now
3343 mEventThread->onScreenReleased();
3344 }
3345 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003346 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003347 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003348 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003349 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003350}
3351
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003352void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3353 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003354 SurfaceFlinger& mFlinger;
3355 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003356 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003357 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003358 MessageSetPowerMode(SurfaceFlinger& flinger,
3359 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3360 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003361 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003362 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003363 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003364 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003365 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003366 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003367 ALOGW("Attempt to set power mode = %d for virtual display",
3368 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003369 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003370 mFlinger.setPowerModeInternal(
3371 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003372 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003373 return true;
3374 }
3375 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003376 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003377 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003378}
3379
3380// ---------------------------------------------------------------------------
3381
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3383{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003385
Mathias Agopianbd115332013-04-18 16:41:04 -07003386 IPCThreadState* ipc = IPCThreadState::self();
3387 const int pid = ipc->getCallingPid();
3388 const int uid = ipc->getCallingUid();
3389 if ((uid != AID_SHELL) &&
3390 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003391 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003392 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003394 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003395 // (this would indicate SF is stuck, but we want to be able to
3396 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003397 status_t err = mStateLock.timedLock(s2ns(1));
3398 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003399 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003400 result.appendFormat(
3401 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3402 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003403 }
3404
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003405 bool dumpAll = true;
3406 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003407 size_t numArgs = args.size();
3408 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003409 if ((index < numArgs) &&
3410 (args[index] == String16("--list"))) {
3411 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003412 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003413 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003414 }
3415
3416 if ((index < numArgs) &&
3417 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003418 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003420 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003421 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003422
3423 if ((index < numArgs) &&
3424 (args[index] == String16("--latency-clear"))) {
3425 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003426 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003427 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003428 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003429
3430 if ((index < numArgs) &&
3431 (args[index] == String16("--dispsync"))) {
3432 index++;
3433 mPrimaryDispSync.dump(result);
3434 dumpAll = false;
3435 }
Dan Stozab90cf072015-03-05 11:05:59 -08003436
3437 if ((index < numArgs) &&
3438 (args[index] == String16("--static-screen"))) {
3439 index++;
3440 dumpStaticScreenStats(result);
3441 dumpAll = false;
3442 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003443
3444 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003445 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003446 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003447 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003448 dumpAll = false;
3449 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003450
3451 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3452 index++;
3453 dumpWideColorInfo(result);
3454 dumpAll = false;
3455 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003456 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003457
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003458 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003459 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003460 }
3461
Mathias Agopian9795c422009-08-26 16:36:26 -07003462 if (locked) {
3463 mStateLock.unlock();
3464 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003465 }
3466 write(fd, result.string(), result.size());
3467 return NO_ERROR;
3468}
3469
Dan Stozac7014012014-02-14 15:03:43 -08003470void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3471 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003472{
Robert Carr2047fae2016-11-28 14:09:09 -08003473 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003474 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003475 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003476}
3477
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003478void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003479 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003480{
3481 String8 name;
3482 if (index < args.size()) {
3483 name = String8(args[index]);
3484 index++;
3485 }
3486
Dan Stoza9e56aa02015-11-02 13:00:03 -08003487 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3488 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003489 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003490
3491 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003492 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003493 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003494 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003495 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003496 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003497 }
Robert Carr2047fae2016-11-28 14:09:09 -08003498 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003499 }
3500}
3501
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003502void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003503 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003504{
3505 String8 name;
3506 if (index < args.size()) {
3507 name = String8(args[index]);
3508 index++;
3509 }
3510
Robert Carr2047fae2016-11-28 14:09:09 -08003511 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003512 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003513 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003514 }
Robert Carr2047fae2016-11-28 14:09:09 -08003515 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003516
Svetoslavd85084b2014-03-20 10:28:31 -07003517 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003518}
3519
Jamie Gennis6547ff42013-07-16 20:12:42 -07003520// This should only be called from the main thread. Otherwise it would need
3521// the lock and should use mCurrentState rather than mDrawingState.
3522void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003523 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003524 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003525 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003526
3527 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3528}
3529
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003530void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003531{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003532 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003533 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3534
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003535 if (isLayerTripleBufferingDisabled())
3536 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003537
3538 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003539 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003540 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003541 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003542 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3543 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003544 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003545}
3546
Dan Stozab90cf072015-03-05 11:05:59 -08003547void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3548{
3549 result.appendFormat("Static screen stats:\n");
3550 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3551 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3552 float percent = 100.0f *
3553 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3554 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3555 b + 1, bucketTimeSec, percent);
3556 }
3557 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3558 float percent = 100.0f *
3559 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3560 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3561 NUM_BUCKETS - 1, bucketTimeSec, percent);
3562}
3563
Dan Stozae77c7662016-05-13 11:37:28 -07003564void SurfaceFlinger::recordBufferingStats(const char* layerName,
3565 std::vector<OccupancyTracker::Segment>&& history) {
3566 Mutex::Autolock lock(mBufferingStatsMutex);
3567 auto& stats = mBufferingStats[layerName];
3568 for (const auto& segment : history) {
3569 if (!segment.usedThirdBuffer) {
3570 stats.twoBufferTime += segment.totalTime;
3571 }
3572 if (segment.occupancyAverage < 1.0f) {
3573 stats.doubleBufferedTime += segment.totalTime;
3574 } else if (segment.occupancyAverage < 2.0f) {
3575 stats.tripleBufferedTime += segment.totalTime;
3576 }
3577 ++stats.numSegments;
3578 stats.totalTime += segment.totalTime;
3579 }
3580}
3581
Brian Andersond6927fb2016-07-23 23:37:30 -07003582void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3583 result.appendFormat("Layer frame timestamps:\n");
3584
3585 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3586 const size_t count = currentLayers.size();
3587 for (size_t i=0 ; i<count ; i++) {
3588 currentLayers[i]->dumpFrameEvents(result);
3589 }
3590}
3591
Dan Stozae77c7662016-05-13 11:37:28 -07003592void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3593 result.append("Buffering stats:\n");
3594 result.append(" [Layer name] <Active time> <Two buffer> "
3595 "<Double buffered> <Triple buffered>\n");
3596 Mutex::Autolock lock(mBufferingStatsMutex);
3597 typedef std::tuple<std::string, float, float, float> BufferTuple;
3598 std::map<float, BufferTuple, std::greater<float>> sorted;
3599 for (const auto& statsPair : mBufferingStats) {
3600 const char* name = statsPair.first.c_str();
3601 const BufferingStats& stats = statsPair.second;
3602 if (stats.numSegments == 0) {
3603 continue;
3604 }
3605 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3606 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3607 stats.totalTime;
3608 float doubleBufferRatio = static_cast<float>(
3609 stats.doubleBufferedTime) / stats.totalTime;
3610 float tripleBufferRatio = static_cast<float>(
3611 stats.tripleBufferedTime) / stats.totalTime;
3612 sorted.insert({activeTime, {name, twoBufferRatio,
3613 doubleBufferRatio, tripleBufferRatio}});
3614 }
3615 for (const auto& sortedPair : sorted) {
3616 float activeTime = sortedPair.first;
3617 const BufferTuple& values = sortedPair.second;
3618 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3619 std::get<0>(values).c_str(), activeTime,
3620 std::get<1>(values), std::get<2>(values),
3621 std::get<3>(values));
3622 }
3623 result.append("\n");
3624}
3625
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003626void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3627 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3628
3629 // TODO: print out if wide-color mode is active or not
3630
3631 for (size_t d = 0; d < mDisplays.size(); d++) {
3632 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3633 int32_t hwcId = displayDevice->getHwcDisplayId();
3634 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3635 continue;
3636 }
3637
3638 result.appendFormat("Display %d color modes:\n", hwcId);
3639 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3640 for (auto&& mode : modes) {
3641 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3642 }
3643
3644 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3645 result.appendFormat(" Current color mode: %s (%d)\n",
3646 decodeColorMode(currentMode).c_str(), currentMode);
3647 }
3648 result.append("\n");
3649}
3650
Mathias Agopian74d211a2013-04-22 16:55:35 +02003651void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3652 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003653{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003654 bool colorize = false;
3655 if (index < args.size()
3656 && (args[index] == String16("--color"))) {
3657 colorize = true;
3658 index++;
3659 }
3660
3661 Colorizer colorizer(colorize);
3662
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003663 // figure out if we're stuck somewhere
3664 const nsecs_t now = systemTime();
3665 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3666 const nsecs_t inTransaction(mDebugInTransaction);
3667 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3668 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3669
3670 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003671 * Dump library configuration.
3672 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003673
3674 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003675 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003676 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003677 appendSfConfigString(result);
3678 appendUiConfigString(result);
3679 appendGuiConfigString(result);
3680 result.append("\n");
3681
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003682 result.append("\nWide-Color information:\n");
3683 dumpWideColorInfo(result);
3684
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003685 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003686 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003687 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003688 result.append(SyncFeatures::getInstance().toString());
3689 result.append("\n");
3690
Dan Stoza9e56aa02015-11-02 13:00:03 -08003691 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3692
Andy McFadden41d67d72014-04-25 16:58:34 -07003693 colorizer.bold(result);
3694 result.append("DispSync configuration: ");
3695 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003696 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003697 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003698 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003699 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003700 result.append("\n");
3701
Dan Stozab90cf072015-03-05 11:05:59 -08003702 // Dump static screen stats
3703 result.append("\n");
3704 dumpStaticScreenStats(result);
3705 result.append("\n");
3706
Dan Stozae77c7662016-05-13 11:37:28 -07003707 dumpBufferingStats(result);
3708
Andy McFadden4803b742012-09-24 19:07:20 -07003709 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003710 * Dump the visible layer list
3711 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003712 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003713 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003714 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003715 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003716 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003717 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003718
3719 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003720 * Dump Display state
3721 */
3722
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003723 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003724 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003725 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003726 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3727 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003728 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003729 }
3730
3731 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003732 * Dump SurfaceFlinger global state
3733 */
3734
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003735 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003736 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003737 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003738
Mathias Agopian888c8222012-08-04 21:10:38 -07003739 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003740 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003741
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003742 colorizer.bold(result);
3743 result.appendFormat("EGL implementation : %s\n",
3744 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3745 colorizer.reset(result);
3746 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003747 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003748
Mathias Agopian875d8e12013-06-07 15:35:48 -07003749 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003750
Mathias Agopian42977342012-08-05 00:40:46 -07003751 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003752 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3753 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003754 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003755 " last eglSwapBuffers() time: %f us\n"
3756 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003757 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003758 " refresh-rate : %f fps\n"
3759 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003760 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003761 " gpu_to_cpu_unsupported : %d\n"
3762 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003763 mLastSwapBufferTime/1000.0,
3764 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003765 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003766 1e9 / activeConfig->getVsyncPeriod(),
3767 activeConfig->getDpiX(),
3768 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003769 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770
Mathias Agopian74d211a2013-04-22 16:55:35 +02003771 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003772 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003773
Mathias Agopian74d211a2013-04-22 16:55:35 +02003774 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003775 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003776
3777 /*
3778 * VSYNC state
3779 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003780 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003781 result.append("\n");
3782
3783 /*
3784 * HWC layer minidump
3785 */
3786 for (size_t d = 0; d < mDisplays.size(); d++) {
3787 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3788 int32_t hwcId = displayDevice->getHwcDisplayId();
3789 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3790 continue;
3791 }
3792
3793 result.appendFormat("Display %d HWC layers:\n", hwcId);
3794 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003795 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003796 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003797 });
Dan Stozae22aec72016-08-01 13:20:59 -07003798 result.append("\n");
3799 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003800
3801 /*
3802 * Dump HWComposer state
3803 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003804 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003805 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003806 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003807 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003808 result.appendFormat(" h/w composer %s\n",
3809 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003810 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003811
3812 /*
3813 * Dump gralloc state
3814 */
3815 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3816 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003817
3818 /*
3819 * Dump VrFlinger state if in use.
3820 */
3821 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3822 result.append("VrFlinger state:\n");
3823 result.append(mVrFlinger->Dump().c_str());
3824 result.append("\n");
3825 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003826}
3827
Mathias Agopian13127d82013-03-05 17:47:11 -08003828const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003829SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003830 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003831 wp<IBinder> dpy;
3832 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3833 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3834 dpy = mDisplays.keyAt(i);
3835 break;
3836 }
3837 }
3838 if (dpy == NULL) {
3839 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3840 // Just use the primary display so we have something to return
3841 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3842 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003843 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003844}
3845
Keun young Park63f165f2012-08-31 10:53:36 -07003846bool SurfaceFlinger::startDdmConnection()
3847{
3848 void* libddmconnection_dso =
3849 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3850 if (!libddmconnection_dso) {
3851 return false;
3852 }
3853 void (*DdmConnection_start)(const char* name);
3854 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003855 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003856 if (!DdmConnection_start) {
3857 dlclose(libddmconnection_dso);
3858 return false;
3859 }
3860 (*DdmConnection_start)(getServiceName());
3861 return true;
3862}
3863
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003864status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 switch (code) {
3866 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003867 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003868 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003869 case CLEAR_ANIMATION_FRAME_STATS:
3870 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003872 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873 {
3874 // codes that require permission check
3875 IPCThreadState* ipc = IPCThreadState::self();
3876 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003877 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003878 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003879 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003880 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003881 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003883 break;
3884 }
Robert Carr1db73f62016-12-21 12:58:51 -08003885 /*
3886 * Calling setTransactionState is safe, because you need to have been
3887 * granted a reference to Client* and Handle* to do anything with it.
3888 *
3889 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3890 */
3891 case SET_TRANSACTION_STATE:
3892 case CREATE_SCOPED_CONNECTION:
3893 {
3894 return OK;
3895 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003896 case CAPTURE_SCREEN:
3897 {
3898 // codes that require permission check
3899 IPCThreadState* ipc = IPCThreadState::self();
3900 const int pid = ipc->getCallingPid();
3901 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003902 if ((uid != AID_GRAPHICS) &&
3903 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003904 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003905 return PERMISSION_DENIED;
3906 }
3907 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908 }
3909 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003910 return OK;
3911}
3912
3913status_t SurfaceFlinger::onTransact(
3914 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3915{
3916 status_t credentialCheck = CheckTransactCodeCredentials(code);
3917 if (credentialCheck != OK) {
3918 return credentialCheck;
3919 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003920
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003921 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3922 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003923 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003924 IPCThreadState* ipc = IPCThreadState::self();
3925 const int uid = ipc->getCallingUid();
3926 if (CC_UNLIKELY(uid != AID_SYSTEM
3927 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003928 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003929 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003930 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931 return PERMISSION_DENIED;
3932 }
3933 int n;
3934 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003935 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003936 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003937 return NO_ERROR;
3938 case 1002: // SHOW_UPDATES
3939 n = data.readInt32();
3940 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003941 invalidateHwcGeometry();
3942 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003943 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003945 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003946 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003948 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003949 setTransactionFlags(
3950 eTransactionNeeded|
3951 eDisplayTransactionNeeded|
3952 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003953 return NO_ERROR;
3954 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003955 case 1006:{ // send empty update
3956 signalRefresh();
3957 return NO_ERROR;
3958 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003959 case 1008: // toggle use of hw composer
3960 n = data.readInt32();
3961 mDebugDisableHWC = n ? 1 : 0;
3962 invalidateHwcGeometry();
3963 repaintEverything();
3964 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003965 case 1009: // toggle use of transform hint
3966 n = data.readInt32();
3967 mDebugDisableTransformHint = n ? 1 : 0;
3968 invalidateHwcGeometry();
3969 repaintEverything();
3970 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003971 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003972 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973 reply->writeInt32(0);
3974 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003975 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003976 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 return NO_ERROR;
3978 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003979 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003980 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003981 return NO_ERROR;
3982 }
3983 case 1014: {
3984 // daltonize
3985 n = data.readInt32();
3986 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003987 case 1:
3988 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3989 break;
3990 case 2:
3991 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3992 break;
3993 case 3:
3994 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3995 break;
3996 default:
3997 mDaltonizer.setType(ColorBlindnessType::None);
3998 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003999 }
4000 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004001 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004002 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004003 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004004 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004005 invalidateHwcGeometry();
4006 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004007 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004008 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004009 case 1015: {
4010 // apply a color matrix
4011 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004012 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004013 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004014 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004015 for (size_t j = 0; j < 4; j++) {
4016 mColorMatrix[i][j] = data.readFloat();
4017 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004018 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004019 } else {
4020 mColorMatrix = mat4();
4021 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004022
4023 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4024 // the division by w in the fragment shader
4025 float4 lastRow(transpose(mColorMatrix)[3]);
4026 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4027 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4028 }
4029
Alan Viverette9c5a3332013-09-12 20:04:35 -07004030 invalidateHwcGeometry();
4031 repaintEverything();
4032 return NO_ERROR;
4033 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004034 // This is an experimental interface
4035 // Needs to be shifted to proper binder interface when we productize
4036 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004037 n = data.readInt32();
4038 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004039 return NO_ERROR;
4040 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004041 case 1017: {
4042 n = data.readInt32();
4043 mForceFullDamage = static_cast<bool>(n);
4044 return NO_ERROR;
4045 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004046 case 1018: { // Modify Choreographer's phase offset
4047 n = data.readInt32();
4048 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4049 return NO_ERROR;
4050 }
4051 case 1019: { // Modify SurfaceFlinger's phase offset
4052 n = data.readInt32();
4053 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4054 return NO_ERROR;
4055 }
Irvel468051e2016-06-13 16:44:44 -07004056 case 1020: { // Layer updates interceptor
4057 n = data.readInt32();
4058 if (n) {
4059 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004060 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004061 }
4062 else{
4063 ALOGV("Interceptor disabled");
4064 mInterceptor.disable();
4065 }
4066 return NO_ERROR;
4067 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004068 case 1021: { // Disable HWC virtual displays
4069 n = data.readInt32();
4070 mUseHwcVirtualDisplays = !n;
4071 return NO_ERROR;
4072 }
Romain Guy0147a172017-06-01 13:53:56 -07004073 case 1022: { // Set saturation boost
4074 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4075
4076 invalidateHwcGeometry();
4077 repaintEverything();
4078 return NO_ERROR;
4079 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004080 }
4081 }
4082 return err;
4083}
4084
Mathias Agopian53331da2011-08-22 21:44:41 -07004085void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004086 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004087 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004088}
4089
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004090// Checks that the requested width and height are valid and updates them to the display dimensions
4091// if they are set to 0
4092static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4093 Transform::orientation_flags rotation,
4094 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4095 // get screen geometry
4096 uint32_t displayWidth = displayDevice->getWidth();
4097 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004098
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004099 if (rotation & Transform::ROT_90) {
4100 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004101 }
4102
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004103 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4104 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4105 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4106 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004107 }
4108
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004109 if (*requestedWidth == 0) {
4110 *requestedWidth = displayWidth;
4111 }
4112 if (*requestedHeight == 0) {
4113 *requestedHeight = displayHeight;
4114 }
4115
4116 return NO_ERROR;
4117}
4118
4119// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4120class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004121public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004122 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4123 ~WindowDisconnector() {
4124 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004125 }
4126
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004127private:
4128 ANativeWindow* mWindow;
4129 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004130};
4131
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004132static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4133 uint32_t requestedHeight, bool hasWideColorDisplay,
4134 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4135 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4136 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4137
4138 int err = 0;
4139 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4140 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4141 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4142 err |= native_window_set_usage(window, usage);
4143
4144 if (hasWideColorDisplay) {
4145 err |= native_window_set_buffers_data_space(window,
4146 renderEngineUsesWideColor
4147 ? HAL_DATASPACE_DISPLAY_P3
4148 : HAL_DATASPACE_V0_SRGB);
4149 }
4150
4151 if (err != NO_ERROR) {
4152 return BAD_VALUE;
4153 }
4154
4155 /* TODO: Once we have the sync framework everywhere this can use
4156 * server-side waits on the fence that dequeueBuffer returns.
4157 */
4158 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4159 if (err != NO_ERROR) {
4160 return err;
4161 }
4162
4163 return NO_ERROR;
4164}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004165
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004166status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4167 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004168 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004169 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004170 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004171 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004172
4173 if (CC_UNLIKELY(display == 0))
4174 return BAD_VALUE;
4175
4176 if (CC_UNLIKELY(producer == 0))
4177 return BAD_VALUE;
4178
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004179 // if we have secure windows on this display, never allow the screen capture
4180 // unless the producer interface is local (i.e.: we can take a screenshot for
4181 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004182 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004183
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004184 // Convert to surfaceflinger's internal rotation type.
4185 Transform::orientation_flags rotationFlags;
4186 switch (rotation) {
4187 case ISurfaceComposer::eRotateNone:
4188 rotationFlags = Transform::ROT_0;
4189 break;
4190 case ISurfaceComposer::eRotate90:
4191 rotationFlags = Transform::ROT_90;
4192 break;
4193 case ISurfaceComposer::eRotate180:
4194 rotationFlags = Transform::ROT_180;
4195 break;
4196 case ISurfaceComposer::eRotate270:
4197 rotationFlags = Transform::ROT_270;
4198 break;
4199 default:
4200 rotationFlags = Transform::ROT_0;
4201 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4202 break;
4203 }
4204
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004205 { // Autolock scope
4206 Mutex::Autolock lock(mStateLock);
4207 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4208 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004209 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004210
4211 // create a surface (because we're a producer, and we need to
4212 // dequeue/queue a buffer)
4213 sp<Surface> surface = new Surface(producer, false);
4214
4215 // Put the screenshot Surface into async mode so that
4216 // Layer::headFenceHasSignaled will always return true and we'll latch the
4217 // first buffer regardless of whether or not its acquire fence has
4218 // signaled. This is needed to avoid a race condition in the rotation
4219 // animation. See b/30209608
4220 surface->setAsyncMode(true);
4221
4222 ANativeWindow* window = surface.get();
4223
4224 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4225 if (result != NO_ERROR) {
4226 return result;
4227 }
4228 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4229
4230 ANativeWindowBuffer* buffer = nullptr;
4231 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4232 getRenderEngine().usesWideColor(), &buffer);
4233 if (result != NO_ERROR) {
4234 return result;
4235 }
4236
4237 // This mutex protects syncFd and captureResult for communication of the return values from the
4238 // main thread back to this Binder thread
4239 std::mutex captureMutex;
4240 std::condition_variable captureCondition;
4241 std::unique_lock<std::mutex> captureLock(captureMutex);
4242 int syncFd = -1;
4243 std::optional<status_t> captureResult;
4244
4245 sp<LambdaMessage> message = new LambdaMessage([&]() {
4246 // If there is a refresh pending, bug out early and tell the binder thread to try again
4247 // after the refresh.
4248 if (mRefreshPending) {
4249 ATRACE_NAME("Skipping screenshot for now");
4250 std::unique_lock<std::mutex> captureLock(captureMutex);
4251 captureResult = std::make_optional<status_t>(EAGAIN);
4252 captureCondition.notify_one();
4253 return;
4254 }
4255
4256 status_t result = NO_ERROR;
4257 int fd = -1;
4258 {
4259 Mutex::Autolock _l(mStateLock);
4260 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4261 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4262 minLayerZ, maxLayerZ, useIdentityTransform,
4263 rotationFlags, isLocalScreenshot, &fd);
4264 }
4265
4266 {
4267 std::unique_lock<std::mutex> captureLock(captureMutex);
4268 syncFd = fd;
4269 captureResult = std::make_optional<status_t>(result);
4270 captureCondition.notify_one();
4271 }
4272 });
4273
4274 result = postMessageAsync(message);
4275 if (result == NO_ERROR) {
4276 captureCondition.wait(captureLock, [&]() { return captureResult; });
4277 while (*captureResult == EAGAIN) {
4278 captureResult.reset();
4279 result = postMessageAsync(message);
4280 if (result != NO_ERROR) {
4281 return result;
4282 }
4283 captureCondition.wait(captureLock, [&]() { return captureResult; });
4284 }
4285 result = *captureResult;
4286 }
4287
4288 if (result == NO_ERROR) {
4289 // queueBuffer takes ownership of syncFd
4290 result = window->queueBuffer(window, buffer, syncFd);
4291 }
4292
4293 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004294}
4295
Mathias Agopian180f10d2013-04-10 22:55:41 -07004296
4297void SurfaceFlinger::renderScreenImplLocked(
4298 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004299 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004300 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004301 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004302{
4303 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004304 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004305
4306 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004307 const int32_t hw_w = hw->getWidth();
4308 const int32_t hw_h = hw->getHeight();
4309 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004310 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004311
Dan Stozac1879002014-05-22 15:59:05 -07004312 // if a default or invalid sourceCrop is passed in, set reasonable values
4313 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4314 !sourceCrop.isValid()) {
4315 sourceCrop.setLeftTop(Point(0, 0));
4316 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4317 }
4318
4319 // ensure that sourceCrop is inside screen
4320 if (sourceCrop.left < 0) {
4321 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4322 }
Dan Stozabe31f442014-06-11 11:20:54 -07004323 if (sourceCrop.right > hw_w) {
4324 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004325 }
4326 if (sourceCrop.top < 0) {
4327 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4328 }
Dan Stozabe31f442014-06-11 11:20:54 -07004329 if (sourceCrop.bottom > hw_h) {
4330 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004331 }
4332
Romain Guy88d37dd2017-05-26 17:57:05 -07004333#ifdef USE_HWC2
4334 engine.setWideColor(hw->getWideColorSupport());
4335 engine.setColorMode(hw->getActiveColorMode());
4336#endif
4337
Mathias Agopian180f10d2013-04-10 22:55:41 -07004338 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004339 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004340
4341 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004342 engine.setViewportAndProjection(
4343 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004344 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004345
4346 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004347 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004348
Robert Carr1f0a16a2016-10-24 16:27:39 -07004349 // We loop through the first level of layers without traversing,
4350 // as we need to interpret min/max layer Z in the top level Z space.
4351 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004352 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004353 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004354 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004355 const Layer::State& state(layer->getDrawingState());
4356 if (state.z < minLayerZ || state.z > maxLayerZ) {
4357 continue;
4358 }
Dan Stoza412903f2017-04-27 13:42:17 -07004359 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004360 if (!layer->isVisible()) {
4361 return;
4362 }
4363 if (filtering) layer->setFiltering(true);
4364 layer->draw(hw, useIdentityTransform);
4365 if (filtering) layer->setFiltering(false);
4366 });
4367 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004368
Mathias Agopian931bda12013-08-28 18:11:46 -07004369 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004370}
4371
Dan Stozaabcda352017-06-01 14:37:39 -07004372// A simple RAII class that holds an EGLImage and destroys it either:
4373// a) When the destroy() method is called
4374// b) When the object goes out of scope
4375class ImageHolder {
4376public:
4377 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4378 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004379
Dan Stozaabcda352017-06-01 14:37:39 -07004380 void destroy() {
4381 if (mImage != EGL_NO_IMAGE_KHR) {
4382 eglDestroyImageKHR(mDisplay, mImage);
4383 mImage = EGL_NO_IMAGE_KHR;
4384 }
4385 }
4386
4387private:
4388 const EGLDisplay mDisplay;
4389 EGLImageKHR mImage;
4390};
4391
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004392status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4393 ANativeWindowBuffer* buffer, Rect sourceCrop,
4394 uint32_t reqWidth, uint32_t reqHeight,
4395 int32_t minLayerZ, int32_t maxLayerZ,
4396 bool useIdentityTransform,
4397 Transform::orientation_flags rotation,
4398 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004399 ATRACE_CALL();
4400
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004401 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004402 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004403 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004404 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004405 (state.z < minLayerZ || state.z > maxLayerZ)) {
4406 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004407 }
Dan Stoza412903f2017-04-27 13:42:17 -07004408 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004409 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4410 layer->isSecure());
4411 });
4412 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004413
4414 if (!isLocalScreenshot && secureLayerIsVisible) {
4415 ALOGW("FB is protected: PERMISSION_DENIED");
4416 return PERMISSION_DENIED;
4417 }
4418
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004419 int syncFd = -1;
4420 // create an EGLImage from the buffer so we can later
4421 // turn it into a texture
4422 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4423 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4424 if (image == EGL_NO_IMAGE_KHR) {
4425 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004426 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004427
Dan Stozaabcda352017-06-01 14:37:39 -07004428 // This will automatically destroy the image if we return before calling its destroy method
4429 ImageHolder imageHolder(mEGLDisplay, image);
4430
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004431 // this binds the given EGLImage as a framebuffer for the
4432 // duration of this scope.
4433 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004434 if (imageBond.getStatus() != NO_ERROR) {
4435 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004436 return INVALID_OPERATION;
4437 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004438
Dan Stozaabcda352017-06-01 14:37:39 -07004439 // this will in fact render into our dequeued buffer
4440 // via an FBO, which means we didn't have to create
4441 // an EGLSurface and therefore we're not
4442 // dependent on the context's EGLConfig.
4443 renderScreenImplLocked(
4444 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4445 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004446
Dan Stozaabcda352017-06-01 14:37:39 -07004447 // Attempt to create a sync khr object that can produce a sync point. If that
4448 // isn't available, create a non-dupable sync object in the fallback path and
4449 // wait on it directly.
4450 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4451 if (!DEBUG_SCREENSHOTS) {
4452 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4453 // native fence fd will not be populated until flush() is done.
4454 getRenderEngine().flush();
4455 }
4456
4457 if (sync != EGL_NO_SYNC_KHR) {
4458 // get the sync fd
4459 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4460 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4461 ALOGW("captureScreen: failed to dup sync khr object");
4462 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004463 }
Dan Stozaabcda352017-06-01 14:37:39 -07004464 eglDestroySyncKHR(mEGLDisplay, sync);
4465 } else {
4466 // fallback path
4467 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004468 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004469 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4470 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4471 EGLint eglErr = eglGetError();
4472 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4473 ALOGW("captureScreen: fence wait timed out");
4474 } else {
4475 ALOGW_IF(eglErr != EGL_SUCCESS,
4476 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004477 }
4478 eglDestroySyncKHR(mEGLDisplay, sync);
4479 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004480 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004481 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004482 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004483 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004484
4485 if (DEBUG_SCREENSHOTS) {
4486 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4487 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4488 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4489 hw, minLayerZ, maxLayerZ);
4490 delete [] pixels;
4491 }
4492
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004493 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004494 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004495
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004496 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004497}
4498
Mathias Agopiand5556842013-09-19 17:08:37 -07004499void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004500 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004501 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004502 for (size_t y=0 ; y<h ; y++) {
4503 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4504 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004505 if (p[x] != 0xFF000000) return;
4506 }
4507 }
4508 ALOGE("*** we just took a black screenshot ***\n"
4509 "requested minz=%d, maxz=%d, layerStack=%d",
4510 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004511
Robert Carr2047fae2016-11-28 14:09:09 -08004512 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004513 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004514 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004515 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004516 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004517 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004518 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4519 layer->isVisible() ? '+' : '-',
4520 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004521 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004522 i++;
4523 });
4524 }
4525 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004526 }
4527}
4528
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004529// ---------------------------------------------------------------------------
4530
Dan Stoza412903f2017-04-27 13:42:17 -07004531void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4532 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004533}
4534
Dan Stoza412903f2017-04-27 13:42:17 -07004535void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4536 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004537}
4538
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004539}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004540
4541
4542#if defined(__gl_h_)
4543#error "don't include gl/gl.h in this file"
4544#endif
4545
4546#if defined(__gl2_h_)
4547#error "don't include gl2/gl2.h in this file"
4548#endif