blob: 12205af91982a6d716cfb57ab0b77ef0211c70d4 [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
Thierry Strudel2924d012017-08-14 15:19:37 -0700394 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700395 readPersistentProperties();
396 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700397 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian3f844832013-08-07 21:24:32 -0700400void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700401 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700402 RenderEngine& engine;
403 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700405 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
406 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700407 }
408 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700409 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700410 return true;
411 }
412 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700413 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700414}
415
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416class DispSyncSource : public VSyncSource, private DispSync::Callback {
417public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700418 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000419 const char* name) :
420 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700421 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700422 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000423 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
424 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700425 mDispSync(dispSync),
426 mCallbackMutex(),
427 mCallback(),
428 mVsyncMutex(),
429 mPhaseOffset(phaseOffset),
430 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700431
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 virtual ~DispSyncSource() {}
433
434 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 static_cast<DispSync::Callback*>(this));
439 if (err != NO_ERROR) {
440 ALOGE("error registering vsync callback: %s (%d)",
441 strerror(-err), err);
442 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700443 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444 } else {
445 status_t err = mDispSync->removeEventListener(
446 static_cast<DispSync::Callback*>(this));
447 if (err != NO_ERROR) {
448 ALOGE("error unregistering vsync callback: %s (%d)",
449 strerror(-err), err);
450 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700451 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 }
455
456 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 mCallback = callback;
459 }
460
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 virtual void setPhaseOffset(nsecs_t phaseOffset) {
462 Mutex::Autolock lock(mVsyncMutex);
463
464 // Normalize phaseOffset to [0, period)
465 auto period = mDispSync->getPeriod();
466 phaseOffset %= period;
467 if (phaseOffset < 0) {
468 // If we're here, then phaseOffset is in (-period, 0). After this
469 // operation, it will be in (0, period)
470 phaseOffset += period;
471 }
472 mPhaseOffset = phaseOffset;
473
474 // If we're not enabled, we don't need to mess with the listeners
475 if (!mEnabled) {
476 return;
477 }
478
479 // Remove the listener with the old offset
480 status_t err = mDispSync->removeEventListener(
481 static_cast<DispSync::Callback*>(this));
482 if (err != NO_ERROR) {
483 ALOGE("error unregistering vsync callback: %s (%d)",
484 strerror(-err), err);
485 }
486
487 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000488 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 static_cast<DispSync::Callback*>(this));
490 if (err != NO_ERROR) {
491 ALOGE("error registering vsync callback: %s (%d)",
492 strerror(-err), err);
493 }
494 }
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496private:
497 virtual void onDispSyncEvent(nsecs_t when) {
498 sp<VSyncSource::Callback> callback;
499 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 callback = mCallback;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 if (mTraceVsync) {
504 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700505 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 }
508
509 if (callback != NULL) {
510 callback->onVSyncEvent(when);
511 }
512 }
513
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 const char* const mName;
515
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 int mValue;
517
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700518 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 const String8 mVsyncOnLabel;
520 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700523
524 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526
527 Mutex mVsyncMutex; // Protects the following
528 nsecs_t mPhaseOffset;
529 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530};
531
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700532class InjectVSyncSource : public VSyncSource {
533public:
534 InjectVSyncSource() {}
535
536 virtual ~InjectVSyncSource() {}
537
538 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
539 std::lock_guard<std::mutex> lock(mCallbackMutex);
540 mCallback = callback;
541 }
542
543 virtual void onInjectSyncEvent(nsecs_t when) {
544 std::lock_guard<std::mutex> lock(mCallbackMutex);
545 mCallback->onVSyncEvent(when);
546 }
547
548 virtual void setVSyncEnabled(bool) {}
549 virtual void setPhaseOffset(nsecs_t) {}
550
551private:
552 std::mutex mCallbackMutex; // Protects the following
553 sp<VSyncSource::Callback> mCallback;
554};
555
Wei Wangf9b05ee2017-07-19 20:59:39 -0700556// Do not call property_set on main thread which will be blocked by init
557// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700559 ALOGI( "SurfaceFlinger's main thread ready to run. "
560 "Initializing graphics H/W...");
561
Thierry Strudel2924d012017-08-14 15:19:37 -0700562 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900563
Steven Thomasd7f49c52017-07-26 18:48:28 -0700564 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565
Steven Thomasd7f49c52017-07-26 18:48:28 -0700566 // initialize EGL for the default display
567 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
568 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569
Steven Thomasd7f49c52017-07-26 18:48:28 -0700570 // start the EventThread
571 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
572 vsyncPhaseOffsetNs, true, "app");
573 mEventThread = new EventThread(vsyncSrc, *this, false);
574 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
575 sfVsyncPhaseOffsetNs, true, "sf");
576 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
577 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578
Steven Thomasd7f49c52017-07-26 18:48:28 -0700579 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
580 struct sched_param param = {0};
581 param.sched_priority = 2;
582 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
583 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
584 }
585 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
586 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587 }
588
Steven Thomasd7f49c52017-07-26 18:48:28 -0700589 // Get a RenderEngine for the given display / config (can't fail)
590 mRenderEngine = RenderEngine::create(mEGLDisplay,
591 HAL_PIXEL_FORMAT_RGBA_8888,
592 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
Steven Thomasd7f49c52017-07-26 18:48:28 -0700594 // retrieve the EGL context that was selected/created
595 mEGLContext = mRenderEngine->getEGLContext();
596
597 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
598 "couldn't create EGLContext");
599
600 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
601 "Starting with vr flinger active is not currently supported.");
602 mHwc.reset(new HWComposer(false));
603 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800604
Steven Thomas050b2c82017-03-06 11:45:16 -0800605 if (useVrFlinger) {
606 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700607 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
Steven Thomas050b2c82017-03-06 11:45:16 -0800608 mVrFlingerRequestsDisplay = requestDisplay;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700609 ConditionalLock _l(mStateLock,
610 std::this_thread::get_id() != mMainThreadId);
Steven Thomas050b2c82017-03-06 11:45:16 -0800611 signalTransaction();
612 };
613 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
614 vrFlingerRequestDisplayCallback);
615 if (!mVrFlinger) {
616 ALOGE("Failed to start vrflinger");
617 }
618 }
619
Jamie Gennisd1700752013-10-14 12:22:52 -0700620 mEventControlThread = new EventControlThread(this);
621 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
622
Mathias Agopian92a979a2012-08-02 18:32:23 -0700623 // initialize our drawing state
624 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700625
Andy McFadden13a082e2012-08-24 10:16:42 -0700626 // set initial conditions (e.g. unblank default device)
627 initializeDisplays();
628
Dan Stoza4e637772016-07-28 13:31:51 -0700629 mRenderEngine->primeCache();
630
Wei Wangf9b05ee2017-07-19 20:59:39 -0700631 // Inform native graphics APIs whether the present timestamp is supported:
632 if (getHwComposer().hasCapability(
633 HWC2::Capability::PresentFenceIsNotReliable)) {
634 mStartPropertySetThread = new StartPropertySetThread(false);
635 } else {
636 mStartPropertySetThread = new StartPropertySetThread(true);
637 }
638
639 if (mStartPropertySetThread->Start() != NO_ERROR) {
640 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800641 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800642
Dan Stoza9e56aa02015-11-02 13:00:03 -0800643 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700644}
645
Romain Guy11d63f42017-07-20 12:47:14 -0700646void SurfaceFlinger::readPersistentProperties() {
647 char value[PROPERTY_VALUE_MAX];
648
649 property_get("persist.sys.sf.color_saturation", value, "1.0");
650 mSaturation = atof(value);
651 ALOGV("Saturation is set to %.2f", mSaturation);
652}
653
Mathias Agopiana67e4182012-06-19 17:26:12 -0700654void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800655 // Start boot animation service by setting a property mailbox
656 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700657 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800658 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700659 if (mStartPropertySetThread->join() != NO_ERROR) {
660 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800661 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700662}
663
Mathias Agopian875d8e12013-06-07 15:35:48 -0700664size_t SurfaceFlinger::getMaxTextureSize() const {
665 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700666}
667
Mathias Agopian875d8e12013-06-07 15:35:48 -0700668size_t SurfaceFlinger::getMaxViewportDims() const {
669 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700670}
671
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800673
Jamie Gennis582270d2011-08-17 18:19:00 -0700674bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800675 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800676 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800677 return authenticateSurfaceTextureLocked(bufferProducer);
678}
679
680bool SurfaceFlinger::authenticateSurfaceTextureLocked(
681 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800682 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700683 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800684}
685
Brian Anderson6b376712017-04-04 10:51:39 -0700686status_t SurfaceFlinger::getSupportedFrameTimestamps(
687 std::vector<FrameEvent>* outSupported) const {
688 *outSupported = {
689 FrameEvent::REQUESTED_PRESENT,
690 FrameEvent::ACQUIRE,
691 FrameEvent::LATCH,
692 FrameEvent::FIRST_REFRESH_START,
693 FrameEvent::LAST_REFRESH_START,
694 FrameEvent::GPU_COMPOSITION_DONE,
695 FrameEvent::DEQUEUE_READY,
696 FrameEvent::RELEASE,
697 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700698 ConditionalLock _l(mStateLock,
699 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700700 if (!getHwComposer().hasCapability(
701 HWC2::Capability::PresentFenceIsNotReliable)) {
702 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
703 }
704 return NO_ERROR;
705}
706
Dan Stoza7f7da322014-05-02 15:26:25 -0700707status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
708 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700709 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700710 return BAD_VALUE;
711 }
712
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500713 if (!display.get())
714 return NAME_NOT_FOUND;
715
Jesse Hall692c7232012-11-08 15:41:56 -0800716 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700717 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800718 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700719 type = i;
720 break;
721 }
722 }
723
724 if (type < 0) {
725 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700726 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700727
Mathias Agopian8b736f12012-08-13 17:54:26 -0700728 // TODO: Not sure if display density should handled by SF any longer
729 class Density {
730 static int getDensityFromProperty(char const* propName) {
731 char property[PROPERTY_VALUE_MAX];
732 int density = 0;
733 if (property_get(propName, property, NULL) > 0) {
734 density = atoi(property);
735 }
736 return density;
737 }
738 public:
739 static int getEmuDensity() {
740 return getDensityFromProperty("qemu.sf.lcd_density"); }
741 static int getBuildDensity() {
742 return getDensityFromProperty("ro.sf.lcd_density"); }
743 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700744
Dan Stoza7f7da322014-05-02 15:26:25 -0700745 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700746
Steven Thomas6d8110b2017-08-31 18:24:21 -0700747 ConditionalLock _l(mStateLock,
748 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700750 DisplayInfo info = DisplayInfo();
751
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 float xdpi = hwConfig->getDpiX();
753 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700754
755 if (type == DisplayDevice::DISPLAY_PRIMARY) {
756 // The density of the device is provided by a build property
757 float density = Density::getBuildDensity() / 160.0f;
758 if (density == 0) {
759 // the build doesn't provide a density -- this is wrong!
760 // use xdpi instead
761 ALOGE("ro.sf.lcd_density must be defined as a build property");
762 density = xdpi / 160.0f;
763 }
764 if (Density::getEmuDensity()) {
765 // if "qemu.sf.lcd_density" is specified, it overrides everything
766 xdpi = ydpi = density = Density::getEmuDensity();
767 density /= 160.0f;
768 }
769 info.density = density;
770
771 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700772 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000773 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 } else {
775 // TODO: where should this value come from?
776 static const int TV_DENSITY = 213;
777 info.density = TV_DENSITY / 160.0f;
778 info.orientation = 0;
779 }
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 info.w = hwConfig->getWidth();
782 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783 info.xdpi = xdpi;
784 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900786 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800787
Andy McFadden91b2ca82014-06-13 14:04:23 -0700788 // This is how far in advance a buffer must be queued for
789 // presentation at a given time. If you want a buffer to appear
790 // on the screen at time N, you must submit the buffer before
791 // (N - presentationDeadline).
792 //
793 // Normally it's one full refresh period (to give SF a chance to
794 // latch the buffer), but this can be reduced by configuring a
795 // DispSync offset. Any additional delays introduced by the hardware
796 // composer or panel must be accounted for here.
797 //
798 // We add an additional 1ms to allow for processing time and
799 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800801 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700802
803 // All non-virtual displays are currently considered secure.
804 info.secure = true;
805
Michael Wright28f24d02016-07-12 13:30:53 -0700806 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 }
808
Dan Stoza7f7da322014-05-02 15:26:25 -0700809 return NO_ERROR;
810}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700811
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800812status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700813 DisplayStatInfo* stats) {
814 if (stats == NULL) {
815 return BAD_VALUE;
816 }
817
818 // FIXME for now we always return stats for the primary display
819 memset(stats, 0, sizeof(*stats));
820 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
821 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
822 return NO_ERROR;
823}
824
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700825int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800826 if (display == NULL) {
827 ALOGE("%s : display is NULL", __func__);
828 return BAD_VALUE;
829 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700830
831 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700832 if (device != NULL) {
833 return device->getActiveConfig();
834 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700835
Dan Stoza24a42e92015-03-09 10:04:11 -0700836 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700837}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700838
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700839void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
840 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
841 this);
842 int32_t type = hw->getDisplayType();
843 int currentMode = hw->getActiveConfig();
844
845 if (mode == currentMode) {
846 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
847 return;
848 }
849
850 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
851 ALOGW("Trying to set config for virtual display");
852 return;
853 }
854
855 hw->setActiveConfig(mode);
856 getHwComposer().setActiveConfig(type, mode);
857}
858
859status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
860 class MessageSetActiveConfig: public MessageBase {
861 SurfaceFlinger& mFlinger;
862 sp<IBinder> mDisplay;
863 int mMode;
864 public:
865 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
866 int mode) :
867 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
868 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700869 Vector<DisplayInfo> configs;
870 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700871 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700872 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700873 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700874 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700875 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700876 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
877 if (hw == NULL) {
878 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700879 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700880 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
881 ALOGW("Attempt to set active config = %d for virtual display",
882 mMode);
883 } else {
884 mFlinger.setActiveConfigInternal(hw, mMode);
885 }
886 return true;
887 }
888 };
889 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
890 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700891 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700892}
Michael Wright28f24d02016-07-12 13:30:53 -0700893status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
894 Vector<android_color_mode_t>* outColorModes) {
895 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
896 return BAD_VALUE;
897 }
898
899 if (!display.get()) {
900 return NAME_NOT_FOUND;
901 }
902
903 int32_t type = NAME_NOT_FOUND;
904 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
905 if (display == mBuiltinDisplays[i]) {
906 type = i;
907 break;
908 }
909 }
910
911 if (type < 0) {
912 return type;
913 }
914
Steven Thomas6d8110b2017-08-31 18:24:21 -0700915 std::vector<android_color_mode_t> modes;
916 {
917 ConditionalLock _l(mStateLock,
918 std::this_thread::get_id() != mMainThreadId);
919 modes = getHwComposer().getColorModes(type);
920 }
Michael Wright28f24d02016-07-12 13:30:53 -0700921 outColorModes->clear();
922 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
923
924 return NO_ERROR;
925}
926
927android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700928 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700929 if (device != nullptr) {
930 return device->getActiveColorMode();
931 }
932 return static_cast<android_color_mode_t>(BAD_VALUE);
933}
934
935void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
936 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700937 int32_t type = hw->getDisplayType();
938 android_color_mode_t currentMode = hw->getActiveColorMode();
939
940 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700941 return;
942 }
943
944 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
945 ALOGW("Trying to set config for virtual display");
946 return;
947 }
948
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600949 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
950 hw->getDisplayType());
951
Michael Wright28f24d02016-07-12 13:30:53 -0700952 hw->setActiveColorMode(mode);
953 getHwComposer().setActiveColorMode(type, mode);
954}
955
956
957status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
958 android_color_mode_t colorMode) {
959 class MessageSetActiveColorMode: public MessageBase {
960 SurfaceFlinger& mFlinger;
961 sp<IBinder> mDisplay;
962 android_color_mode_t mMode;
963 public:
964 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
965 android_color_mode_t mode) :
966 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
967 virtual bool handler() {
968 Vector<android_color_mode_t> modes;
969 mFlinger.getDisplayColorModes(mDisplay, &modes);
970 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
971 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600972 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
973 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700974 return true;
975 }
976 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
977 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600978 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
979 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700980 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600981 ALOGW("Attempt to set active color mode %s %d for virtual display",
982 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700983 } else {
984 mFlinger.setActiveColorModeInternal(hw, mMode);
985 }
986 return true;
987 }
988 };
989 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
990 postMessageSync(msg);
991 return NO_ERROR;
992}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700993
Svetoslavd85084b2014-03-20 10:28:31 -0700994status_t SurfaceFlinger::clearAnimationFrameStats() {
995 Mutex::Autolock _l(mStateLock);
996 mAnimFrameTracker.clearStats();
997 return NO_ERROR;
998}
999
1000status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1001 Mutex::Autolock _l(mStateLock);
1002 mAnimFrameTracker.getStats(outStats);
1003 return NO_ERROR;
1004}
1005
Dan Stozac4f471e2016-03-24 09:31:08 -07001006status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1007 HdrCapabilities* outCapabilities) const {
1008 Mutex::Autolock _l(mStateLock);
1009
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001010 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001011 if (displayDevice == nullptr) {
1012 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1013 return BAD_VALUE;
1014 }
1015
1016 std::unique_ptr<HdrCapabilities> capabilities =
1017 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1018 if (capabilities) {
1019 std::swap(*outCapabilities, *capabilities);
1020 } else {
1021 return BAD_VALUE;
1022 }
1023
1024 return NO_ERROR;
1025}
1026
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001027status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1028 if (enable == mInjectVSyncs) {
1029 return NO_ERROR;
1030 }
1031
1032 if (enable) {
1033 mInjectVSyncs = enable;
1034 ALOGV("VSync Injections enabled");
1035 if (mVSyncInjector.get() == nullptr) {
1036 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001037 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001038 }
1039 mEventQueue.setEventThread(mInjectorEventThread);
1040 } else {
1041 mInjectVSyncs = enable;
1042 ALOGV("VSync Injections disabled");
1043 mEventQueue.setEventThread(mSFEventThread);
1044 mVSyncInjector.clear();
1045 }
1046 return NO_ERROR;
1047}
1048
1049status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1050 if (!mInjectVSyncs) {
1051 ALOGE("VSync Injections not enabled");
1052 return BAD_VALUE;
1053 }
1054 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1055 ALOGV("Injecting VSync inside SurfaceFlinger");
1056 mVSyncInjector->onInjectSyncEvent(when);
1057 }
1058 return NO_ERROR;
1059}
1060
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001061// ----------------------------------------------------------------------------
1062
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001063sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1064 ISurfaceComposer::VsyncSource vsyncSource) {
1065 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1066 return mSFEventThread->createEventConnection();
1067 } else {
1068 return mEventThread->createEventConnection();
1069 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001070}
1071
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001072// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001073
1074void SurfaceFlinger::waitForEvent() {
1075 mEventQueue.waitMessage();
1076}
1077
1078void SurfaceFlinger::signalTransaction() {
1079 mEventQueue.invalidate();
1080}
1081
1082void SurfaceFlinger::signalLayerUpdate() {
1083 mEventQueue.invalidate();
1084}
1085
1086void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001087 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001088 mEventQueue.refresh();
1089}
1090
1091status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001092 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001093 return mEventQueue.postMessage(msg, reltime);
1094}
1095
1096status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001097 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001098 status_t res = mEventQueue.postMessage(msg, reltime);
1099 if (res == NO_ERROR) {
1100 msg->wait();
1101 }
1102 return res;
1103}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001104
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001105void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001106 do {
1107 waitForEvent();
1108 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001109}
1110
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111void SurfaceFlinger::enableHardwareVsync() {
1112 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001113 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001114 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001115 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1116 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001117 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001118 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001119}
1120
Jesse Hall948fe0c2013-10-14 12:56:09 -07001121void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001122 Mutex::Autolock _l(mHWVsyncLock);
1123
Jesse Hall948fe0c2013-10-14 12:56:09 -07001124 if (makeAvailable) {
1125 mHWVsyncAvailable = true;
1126 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001127 // Hardware vsync is not currently available, so abort the resync
1128 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001129 return;
1130 }
1131
Dan Stoza9e56aa02015-11-02 13:00:03 -08001132 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1133 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001134
1135 mPrimaryDispSync.reset();
1136 mPrimaryDispSync.setPeriod(period);
1137
1138 if (!mPrimaryHWVsyncEnabled) {
1139 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001140 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1141 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001142 mPrimaryHWVsyncEnabled = true;
1143 }
1144}
1145
Jesse Hall948fe0c2013-10-14 12:56:09 -07001146void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001147 Mutex::Autolock _l(mHWVsyncLock);
1148 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001149 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1150 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001151 mPrimaryDispSync.endResync();
1152 mPrimaryHWVsyncEnabled = false;
1153 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001154 if (makeUnavailable) {
1155 mHWVsyncAvailable = false;
1156 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001157}
1158
Tim Murray4a4e4a22016-04-19 16:29:23 +00001159void SurfaceFlinger::resyncWithRateLimit() {
1160 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001161
1162 // No explicit locking is needed here since EventThread holds a lock while calling this method
1163 static nsecs_t sLastResyncAttempted = 0;
1164 const nsecs_t now = systemTime();
1165 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001166 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001167 }
Dan Stoza57164302017-05-08 14:03:54 -07001168 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001169}
1170
Steven Thomasd7f49c52017-07-26 18:48:28 -07001171void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1172 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001173 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001174 // Ignore any vsyncs from a previous hardware composer.
1175 if (sequenceId != mComposerSequenceId) {
1176 return;
1177 }
1178
1179 int32_t type;
1180 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001181 return;
1182 }
1183
Jamie Gennisd1700752013-10-14 12:22:52 -07001184 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185
Jamie Gennisd1700752013-10-14 12:22:52 -07001186 { // Scope for the lock
1187 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001188 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001189 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001190 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001191 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001192
1193 if (needsHwVsync) {
1194 enableHardwareVsync();
1195 } else {
1196 disableHardwareVsync(false);
1197 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001198}
1199
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001200void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001201 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001202 *compositorTiming = mCompositorTiming;
1203}
1204
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001205void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001206 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001207 wp<IBinder> token = mBuiltinDisplays[type];
1208
1209 // All non-virtual displays are currently considered secure.
1210 const bool isSecure = true;
1211
1212 sp<IGraphicBufferProducer> producer;
1213 sp<IGraphicBufferConsumer> consumer;
1214 BufferQueue::createBufferQueue(&producer, &consumer);
1215
1216 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1217
1218 bool hasWideColorModes = false;
1219 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1220 for (android_color_mode_t colorMode : modes) {
1221 switch (colorMode) {
1222 case HAL_COLOR_MODE_DISPLAY_P3:
1223 case HAL_COLOR_MODE_ADOBE_RGB:
1224 case HAL_COLOR_MODE_DCI_P3:
1225 hasWideColorModes = true;
1226 break;
1227 default:
1228 break;
1229 }
1230 }
1231 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1232 token, fbs, producer, mRenderEngine->getEGLConfig(),
1233 hasWideColorModes && hasWideColorDisplay);
1234 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001235 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1236 if (hasWideColorModes && hasWideColorDisplay) {
1237 defaultColorMode = HAL_COLOR_MODE_SRGB;
1238 }
1239 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001240 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001241
1242 // Add the primary display token to mDrawingState so we don't try to
1243 // recreate the DisplayDevice for the primary display.
1244 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1245
1246 // make the GLContext current so that we can create textures when creating
1247 // Layers (which may happens before we render something)
1248 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001249}
1250
Steven Thomasd7f49c52017-07-26 18:48:28 -07001251void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1252 hwc2_display_t display, HWC2::Connection connection,
1253 bool primaryDisplay) {
1254 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1255 sequenceId, display,
1256 connection == HWC2::Connection::Connected ?
1257 "connected" : "disconnected",
1258 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001259
Steven Thomasd7f49c52017-07-26 18:48:28 -07001260 // Only lock if we're not on the main thread. This function is normally
1261 // called on a hwbinder thread, but for the primary display it's called on
1262 // the main thread with the state lock already held, so don't attempt to
1263 // acquire it here.
1264 ConditionalLock lock(mStateLock,
1265 std::this_thread::get_id() != mMainThreadId);
1266
1267 if (primaryDisplay) {
1268 mHwc->onHotplug(display, connection);
1269 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1270 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001271 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001272 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001273 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001274 if (sequenceId != mComposerSequenceId) {
1275 return;
1276 }
1277 if (mHwc->isUsingVrComposer()) {
1278 ALOGE("External displays are not supported by the vr hardware composer.");
1279 return;
1280 }
1281 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001282 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasd7f49c52017-07-26 18:48:28 -07001283 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001284 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001285 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001286 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1287 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001288 }
1289 setTransactionFlags(eDisplayTransactionNeeded);
1290
Andy McFadden9e9689c2012-10-10 18:17:51 -07001291 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001292 }
Mathias Agopian86303202012-07-24 22:46:10 -07001293}
1294
Steven Thomasd7f49c52017-07-26 18:48:28 -07001295void SurfaceFlinger::onRefreshReceived(int sequenceId,
1296 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001297 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001298 if (sequenceId != mComposerSequenceId) {
1299 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001300 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001301 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001302}
1303
Dan Stoza9e56aa02015-11-02 13:00:03 -08001304void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001305 ATRACE_CALL();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001306 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001307 getHwComposer().setVsyncEnabled(disp,
1308 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001309}
1310
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001311// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasd7f49c52017-07-26 18:48:28 -07001312void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001313 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001314 // Clear the drawing state so that the logic inside of
1315 // handleTransactionLocked will fire. It will determine the delta between
1316 // mCurrentState and mDrawingState and re-apply all changes when we make the
1317 // transition.
1318 mDrawingState.displays.clear();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001319 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320 mDisplays.clear();
1321}
1322
Steven Thomas050b2c82017-03-06 11:45:16 -08001323void SurfaceFlinger::updateVrFlinger() {
1324 if (!mVrFlinger)
1325 return;
1326 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1327 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001328 return;
1329 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001330
Steven Thomasd7f49c52017-07-26 18:48:28 -07001331 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1332 ALOGE("Vr flinger is only supported for remote hardware composer"
1333 " service connections. Ignoring request to transition to vr"
1334 " flinger.");
1335 mVrFlingerRequestsDisplay = false;
1336 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001337 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001338
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001339 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001340
Steven Thomasd7f49c52017-07-26 18:48:28 -07001341 int currentDisplayPowerMode = getDisplayDeviceLocked(
1342 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001343
Steven Thomasd7f49c52017-07-26 18:48:28 -07001344 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001345 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001346 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347
Steven Thomasd7f49c52017-07-26 18:48:28 -07001348 resetDisplayState();
1349 mHwc.reset(); // Delete the current instance before creating the new one
1350 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1351 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352
Steven Thomasd7f49c52017-07-26 18:48:28 -07001353 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1354 "Switched to non-remote hardware composer");
1355
1356 if (vrFlingerRequestsDisplay) {
1357 mVrFlinger->GrantDisplayOwnership();
1358 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001360 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001361
1362 mVisibleRegionsDirty = true;
1363 invalidateHwcGeometry();
1364
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001365 // Re-enable default display.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001366 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1367 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1368 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001369
Steven Thomasd7f49c52017-07-26 18:48:28 -07001370 // Reset the timing values to account for the period of the swapped in HWC
1371 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1372 const nsecs_t period = activeConfig->getVsyncPeriod();
1373 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001374
Steven Thomasd7f49c52017-07-26 18:48:28 -07001375 // Use phase of 0 since phase is not known.
1376 // Use latency of 0, which will snap to the ideal latency.
1377 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001378
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001379 android_atomic_or(1, &mRepaintEverything);
1380 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001381}
1382
Mathias Agopian4fec8732012-06-29 14:12:52 -07001383void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001384 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001385 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001386 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001387 bool frameMissed = !mHadClientComposition &&
1388 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001389 (mPreviousPresentFence->getSignalTime() ==
1390 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001391 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001392 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001393 signalLayerUpdate();
1394 break;
1395 }
1396
Steven Thomas050b2c82017-03-06 11:45:16 -08001397 // Now that we're going to make it to the handleMessageTransaction()
1398 // call below it's safe to call updateVrFlinger(), which will
1399 // potentially trigger a display handoff.
1400 updateVrFlinger();
1401
Dan Stoza6b9454d2014-11-07 16:00:59 -08001402 bool refreshNeeded = handleMessageTransaction();
1403 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001404 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001405 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001406 // Signal a refresh if a transaction modified the window state,
1407 // a new buffer was latched, or if HWC has requested a full
1408 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 signalRefresh();
1410 }
1411 break;
1412 }
1413 case MessageQueue::REFRESH: {
1414 handleMessageRefresh();
1415 break;
1416 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001417 }
1418}
1419
Dan Stoza6b9454d2014-11-07 16:00:59 -08001420bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001421 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001422 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001423 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001424 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001425 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001426 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001427}
1428
Dan Stoza6b9454d2014-11-07 16:00:59 -08001429bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001430 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001431 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432}
1433
1434void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001435 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001436
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001437 mRefreshPending = false;
1438
Pablo Ceballos40845df2016-01-25 17:41:15 -08001439 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001440
Brian Andersond6927fb2016-07-23 23:37:30 -07001441 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001442 rebuildLayerStacks();
1443 setUpHWComposer();
1444 doDebugFlashRegions();
1445 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001446 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001447
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001448 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001449
1450 mHadClientComposition = false;
1451 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1452 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1453 mHadClientComposition = mHadClientComposition ||
1454 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1455 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001456
Dan Stoza9e56aa02015-11-02 13:00:03 -08001457 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001458}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001459
Mathias Agopiancd60f992012-08-16 16:28:27 -07001460void SurfaceFlinger::doDebugFlashRegions()
1461{
1462 // is debugging enabled
1463 if (CC_LIKELY(!mDebugRegion))
1464 return;
1465
1466 const bool repaintEverything = mRepaintEverything;
1467 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1468 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001469 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 // transform the dirty region into this screen's coordinate space
1471 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1472 if (!dirtyRegion.isEmpty()) {
1473 // redraw the whole screen
1474 doComposeSurfaces(hw, Region(hw->bounds()));
1475
1476 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001478 RenderEngine& engine(getRenderEngine());
1479 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1480
Mathias Agopianda27af92012-09-13 18:17:13 -07001481 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001482 }
1483 }
1484 }
1485
1486 postFramebuffer();
1487
1488 if (mDebugRegion > 1) {
1489 usleep(mDebugRegion * 1000);
1490 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001491
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001493 auto& displayDevice = mDisplays[displayId];
1494 if (!displayDevice->isDisplayOn()) {
1495 continue;
1496 }
1497
1498 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1500 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001501 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001502}
1503
Brian Andersond6927fb2016-07-23 23:37:30 -07001504void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 ATRACE_CALL();
1507 ALOGV("preComposition");
1508
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001510 mDrawingState.traverseInZOrder([&](Layer* layer) {
1511 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 needExtraInvalidate = true;
1513 }
Robert Carr2047fae2016-11-28 14:09:09 -08001514 });
1515
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 if (needExtraInvalidate) {
1517 signalLayerUpdate();
1518 }
1519}
1520
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001521void SurfaceFlinger::updateCompositorTiming(
1522 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1523 std::shared_ptr<FenceTime>& presentFenceTime) {
1524 // Update queue of past composite+present times and determine the
1525 // most recently known composite to present latency.
1526 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1527 nsecs_t compositeToPresentLatency = -1;
1528 while (!mCompositePresentTimes.empty()) {
1529 CompositePresentTime& cpt = mCompositePresentTimes.front();
1530 // Cached values should have been updated before calling this method,
1531 // which helps avoid duplicate syscalls.
1532 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1533 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1534 break;
1535 }
1536 compositeToPresentLatency = displayTime - cpt.composite;
1537 mCompositePresentTimes.pop();
1538 }
1539
1540 // Don't let mCompositePresentTimes grow unbounded, just in case.
1541 while (mCompositePresentTimes.size() > 16) {
1542 mCompositePresentTimes.pop();
1543 }
1544
Brian Andersond0010582017-03-07 13:20:31 -08001545 setCompositorTimingSnapped(
1546 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1547}
1548
1549void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1550 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 // Integer division and modulo round toward 0 not -inf, so we need to
1552 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001553 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001554 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1555 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1556
Brian Andersond0010582017-03-07 13:20:31 -08001557 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1558 if (idealLatency <= 0) {
1559 idealLatency = vsyncInterval;
1560 }
1561
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562 // Snap the latency to a value that removes scheduling jitter from the
1563 // composition and present times, which often have >1ms of jitter.
1564 // Reducing jitter is important if an app attempts to extrapolate
1565 // something (such as user input) to an accurate diasplay time.
1566 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1567 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001568 nsecs_t bias = vsyncInterval / 2;
1569 int64_t extraVsyncs =
1570 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1571 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1572 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001573
Brian Andersond0010582017-03-07 13:20:31 -08001574 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001575 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1576 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001577 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001578}
1579
1580void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001582 ATRACE_CALL();
1583 ALOGV("postComposition");
1584
Brian Anderson3546a3f2016-07-14 11:51:14 -07001585 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001586 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001587 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001588 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001589 }
1590
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591 // |mStateLock| not needed as we are on the main thread
1592 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001593
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001594 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001595 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1596 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1597 glCompositionDoneFenceTime =
1598 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1599 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1600 } else {
1601 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1602 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001603
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001604 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001605 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1606 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1607 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001608
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1610 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1611
1612 // We use the refreshStartTime which might be sampled a little later than
1613 // when we started doing work for this frame, but that should be okay
1614 // since updateCompositorTiming has snapping logic.
1615 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001616 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001617 CompositorTiming compositorTiming;
1618 {
1619 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1620 compositorTiming = mCompositorTiming;
1621 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001622
Robert Carr2047fae2016-11-28 14:09:09 -08001623 mDrawingState.traverseInZOrder([&](Layer* layer) {
1624 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001625 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001626 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001627 recordBufferingStats(layer->getName().string(),
1628 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001629 }
Robert Carr2047fae2016-11-28 14:09:09 -08001630 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001631
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001632 if (presentFenceTime->isValid()) {
1633 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001634 enableHardwareVsync();
1635 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001636 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001637 }
1638 }
1639
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001640 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001641 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001642 enableHardwareVsync();
1643 }
1644 }
1645
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001646 if (mAnimCompositionPending) {
1647 mAnimCompositionPending = false;
1648
Brian Anderson4e606e32017-03-16 15:34:57 -07001649 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001650 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001651 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001652 } else {
1653 // The HWC doesn't support present fences, so use the refresh
1654 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 nsecs_t presentTime =
1656 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001657 mAnimFrameTracker.setActualPresentTime(presentTime);
1658 }
1659 mAnimFrameTracker.advanceFrame();
1660 }
Dan Stozab90cf072015-03-05 11:05:59 -08001661
1662 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1663 return;
1664 }
1665
1666 nsecs_t currentTime = systemTime();
1667 if (mHasPoweredOff) {
1668 mHasPoweredOff = false;
1669 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001670 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001671 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001672 if (numPeriods < NUM_BUCKETS - 1) {
1673 mFrameBuckets[numPeriods] += elapsedTime;
1674 } else {
1675 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1676 }
1677 mTotalTime += elapsedTime;
1678 }
1679 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001680}
1681
1682void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001683 ATRACE_CALL();
1684 ALOGV("rebuildLayerStacks");
1685
Mathias Agopiancd60f992012-08-16 16:28:27 -07001686 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001687 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1688 ATRACE_CALL();
1689 mVisibleRegionsDirty = false;
1690 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001691
Jeff Sharkey76488112017-02-27 14:15:18 -07001692 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1693 Region opaqueRegion;
1694 Region dirtyRegion;
1695 Vector<sp<Layer>> layersSortedByZ;
1696 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1697 const Transform& tr(displayDevice->getTransform());
1698 const Rect bounds(displayDevice->getBounds());
1699 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001700 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001701
Jeff Sharkey76488112017-02-27 14:15:18 -07001702 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001703 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1704 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001705 Region drawRegion(tr.transform(
1706 layer->visibleNonTransparentRegion));
1707 drawRegion.andSelf(bounds);
1708 if (!drawRegion.isEmpty()) {
1709 layersSortedByZ.add(layer);
1710 } else {
1711 // Clear out the HWC layer if this layer was
1712 // previously visible, but no longer is
Steven Thomasd7f49c52017-07-26 18:48:28 -07001713 layer->destroyHwcLayer(
1714 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001715 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001716 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001717 // WM changes displayDevice->layerStack upon sleep/awake.
1718 // Here we make sure we delete the HWC layers even if
1719 // WM changed their layer stack.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001720 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001721 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 });
1723 }
1724 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1725 displayDevice->undefinedRegion.set(bounds);
1726 displayDevice->undefinedRegion.subtractSelf(
1727 tr.transform(opaqueRegion));
1728 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001729 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001730 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001731}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001732
Romain Guy0147a172017-06-01 13:53:56 -07001733mat4 SurfaceFlinger::computeSaturationMatrix() const {
1734 if (mSaturation == 1.0f) {
1735 return mat4();
1736 }
1737
1738 // Rec.709 luma coefficients
1739 float3 luminance{0.213f, 0.715f, 0.072f};
1740 luminance *= 1.0f - mSaturation;
1741 return mat4(
1742 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1743 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1744 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1745 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1746 );
1747}
1748
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001749// pickColorMode translates a given dataspace into the best available color mode.
1750// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001751android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001752 switch (dataSpace) {
1753 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1754 // system expects.
1755 case HAL_DATASPACE_UNKNOWN:
1756 case HAL_DATASPACE_SRGB:
1757 case HAL_DATASPACE_V0_SRGB:
1758 return HAL_COLOR_MODE_SRGB;
1759 break;
1760
1761 case HAL_DATASPACE_DISPLAY_P3:
1762 return HAL_COLOR_MODE_DISPLAY_P3;
1763 break;
1764
1765 default:
1766 // TODO (courtneygo): Do we want to assert an error here?
1767 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1768 dataSpace);
1769 return HAL_COLOR_MODE_SRGB;
1770 break;
1771 }
1772}
1773
Romain Guy0147a172017-06-01 13:53:56 -07001774android_dataspace SurfaceFlinger::bestTargetDataSpace(
1775 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001776 // Only support sRGB and Display-P3 right now.
1777 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1778 return HAL_DATASPACE_DISPLAY_P3;
1779 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001780 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1781 return HAL_DATASPACE_DISPLAY_P3;
1782 }
1783 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1784 return HAL_DATASPACE_DISPLAY_P3;
1785 }
1786
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001787 return HAL_DATASPACE_V0_SRGB;
1788}
1789
Mathias Agopiancd60f992012-08-16 16:28:27 -07001790void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001791 ATRACE_CALL();
1792 ALOGV("setUpHWComposer");
1793
Jesse Hall028dc8f2013-08-20 16:35:32 -07001794 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001795 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1796 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1797 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1798
1799 // If nothing has changed (!dirty), don't recompose.
1800 // If something changed, but we don't currently have any visible layers,
1801 // and didn't when we last did a composition, then skip it this time.
1802 // The second rule does two things:
1803 // - When all layers are removed from a display, we'll emit one black
1804 // frame, then nothing more until we get new layers.
1805 // - When a display is created with a private layer stack, we won't
1806 // emit any black frames until a layer is added to the layer stack.
1807 bool mustRecompose = dirty && !(empty && wasEmpty);
1808
1809 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1810 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1811 mustRecompose ? "doing" : "skipping",
1812 dirty ? "+" : "-",
1813 empty ? "+" : "-",
1814 wasEmpty ? "+" : "-");
1815
Dan Stoza71433162014-02-04 16:22:36 -08001816 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001817
1818 if (mustRecompose) {
1819 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1820 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001821 }
1822
Dan Stoza9e56aa02015-11-02 13:00:03 -08001823 // build the h/w work list
1824 if (CC_UNLIKELY(mGeometryInvalid)) {
1825 mGeometryInvalid = false;
1826 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1827 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1828 const auto hwcId = displayDevice->getHwcDisplayId();
1829 if (hwcId >= 0) {
1830 const Vector<sp<Layer>>& currentLayers(
1831 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001832 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001833 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001834 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001835 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001836 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001837 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001838 }
1839 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001840
Robert Carrae060832016-11-28 10:51:00 -08001841 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001842 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001844 }
1845 }
1846 }
1847 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001848 }
Riley Andrews03414a12014-07-01 14:22:59 -07001849
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001850
Romain Guy0147a172017-06-01 13:53:56 -07001851 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001852
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 // Set the per-frame data
1854 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1855 auto& displayDevice = mDisplays[displayId];
1856 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001857
Dan Stoza9e56aa02015-11-02 13:00:03 -08001858 if (hwcId < 0) {
1859 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001860 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001861 if (colorMatrix != mPreviousColorMatrix) {
1862 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1863 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1864 "display %zd: %d", displayId, result);
1865 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1867 layer->setPerFrameData(displayDevice);
1868 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001869
1870 if (hasWideColorDisplay) {
1871 android_color_mode newColorMode;
1872 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1873
1874 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1875 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1876 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1877 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1878 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1879 }
1880 newColorMode = pickColorMode(newDataSpace);
1881
Thierry Strudel2924d012017-08-14 15:19:37 -07001882 setActiveColorModeInternal(displayDevice, newColorMode);
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;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003305 repaintEverythingLocked();
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
Steven Thomas6d8110b2017-08-31 18:24:21 -07003949 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003950 setTransactionFlags(
3951 eTransactionNeeded|
3952 eDisplayTransactionNeeded|
3953 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003954 return NO_ERROR;
3955 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003956 case 1006:{ // send empty update
3957 signalRefresh();
3958 return NO_ERROR;
3959 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003960 case 1008: // toggle use of hw composer
3961 n = data.readInt32();
3962 mDebugDisableHWC = n ? 1 : 0;
3963 invalidateHwcGeometry();
3964 repaintEverything();
3965 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003966 case 1009: // toggle use of transform hint
3967 n = data.readInt32();
3968 mDebugDisableTransformHint = n ? 1 : 0;
3969 invalidateHwcGeometry();
3970 repaintEverything();
3971 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003972 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003973 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003974 reply->writeInt32(0);
3975 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003976 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003977 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003978 return NO_ERROR;
3979 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003980 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003981 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003982 return NO_ERROR;
3983 }
3984 case 1014: {
3985 // daltonize
3986 n = data.readInt32();
3987 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003988 case 1:
3989 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3990 break;
3991 case 2:
3992 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3993 break;
3994 case 3:
3995 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3996 break;
3997 default:
3998 mDaltonizer.setType(ColorBlindnessType::None);
3999 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004000 }
4001 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004002 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004003 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004004 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004005 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004006 invalidateHwcGeometry();
4007 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004008 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004010 case 1015: {
4011 // apply a color matrix
4012 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004013 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004014 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004015 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004016 for (size_t j = 0; j < 4; j++) {
4017 mColorMatrix[i][j] = data.readFloat();
4018 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004019 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004020 } else {
4021 mColorMatrix = mat4();
4022 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004023
4024 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4025 // the division by w in the fragment shader
4026 float4 lastRow(transpose(mColorMatrix)[3]);
4027 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4028 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4029 }
4030
Alan Viverette9c5a3332013-09-12 20:04:35 -07004031 invalidateHwcGeometry();
4032 repaintEverything();
4033 return NO_ERROR;
4034 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004035 // This is an experimental interface
4036 // Needs to be shifted to proper binder interface when we productize
4037 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004038 n = data.readInt32();
4039 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004040 return NO_ERROR;
4041 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004042 case 1017: {
4043 n = data.readInt32();
4044 mForceFullDamage = static_cast<bool>(n);
4045 return NO_ERROR;
4046 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004047 case 1018: { // Modify Choreographer's phase offset
4048 n = data.readInt32();
4049 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4050 return NO_ERROR;
4051 }
4052 case 1019: { // Modify SurfaceFlinger's phase offset
4053 n = data.readInt32();
4054 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4055 return NO_ERROR;
4056 }
Irvel468051e2016-06-13 16:44:44 -07004057 case 1020: { // Layer updates interceptor
4058 n = data.readInt32();
4059 if (n) {
4060 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004061 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004062 }
4063 else{
4064 ALOGV("Interceptor disabled");
4065 mInterceptor.disable();
4066 }
4067 return NO_ERROR;
4068 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004069 case 1021: { // Disable HWC virtual displays
4070 n = data.readInt32();
4071 mUseHwcVirtualDisplays = !n;
4072 return NO_ERROR;
4073 }
Romain Guy0147a172017-06-01 13:53:56 -07004074 case 1022: { // Set saturation boost
4075 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4076
4077 invalidateHwcGeometry();
4078 repaintEverything();
4079 return NO_ERROR;
4080 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004081 }
4082 }
4083 return err;
4084}
4085
Steven Thomas6d8110b2017-08-31 18:24:21 -07004086void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004087 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004088 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004089}
4090
Steven Thomas6d8110b2017-08-31 18:24:21 -07004091void SurfaceFlinger::repaintEverything() {
4092 ConditionalLock _l(mStateLock,
4093 std::this_thread::get_id() != mMainThreadId);
4094 repaintEverythingLocked();
4095}
4096
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004097// Checks that the requested width and height are valid and updates them to the display dimensions
4098// if they are set to 0
4099static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4100 Transform::orientation_flags rotation,
4101 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4102 // get screen geometry
4103 uint32_t displayWidth = displayDevice->getWidth();
4104 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004105
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004106 if (rotation & Transform::ROT_90) {
4107 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004108 }
4109
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004110 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4111 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4112 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4113 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004114 }
4115
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004116 if (*requestedWidth == 0) {
4117 *requestedWidth = displayWidth;
4118 }
4119 if (*requestedHeight == 0) {
4120 *requestedHeight = displayHeight;
4121 }
4122
4123 return NO_ERROR;
4124}
4125
4126// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4127class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004128public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004129 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4130 ~WindowDisconnector() {
4131 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004132 }
4133
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004134private:
4135 ANativeWindow* mWindow;
4136 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004137};
4138
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004139static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4140 uint32_t requestedHeight, bool hasWideColorDisplay,
4141 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4142 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4143 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4144
4145 int err = 0;
4146 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4147 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4148 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4149 err |= native_window_set_usage(window, usage);
4150
4151 if (hasWideColorDisplay) {
4152 err |= native_window_set_buffers_data_space(window,
4153 renderEngineUsesWideColor
4154 ? HAL_DATASPACE_DISPLAY_P3
4155 : HAL_DATASPACE_V0_SRGB);
4156 }
4157
4158 if (err != NO_ERROR) {
4159 return BAD_VALUE;
4160 }
4161
4162 /* TODO: Once we have the sync framework everywhere this can use
4163 * server-side waits on the fence that dequeueBuffer returns.
4164 */
4165 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4166 if (err != NO_ERROR) {
4167 return err;
4168 }
4169
4170 return NO_ERROR;
4171}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004172
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004173status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4174 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004175 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004176 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004177 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004178 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004179
4180 if (CC_UNLIKELY(display == 0))
4181 return BAD_VALUE;
4182
4183 if (CC_UNLIKELY(producer == 0))
4184 return BAD_VALUE;
4185
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004186 // if we have secure windows on this display, never allow the screen capture
4187 // unless the producer interface is local (i.e.: we can take a screenshot for
4188 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004189 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004190
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004191 // Convert to surfaceflinger's internal rotation type.
4192 Transform::orientation_flags rotationFlags;
4193 switch (rotation) {
4194 case ISurfaceComposer::eRotateNone:
4195 rotationFlags = Transform::ROT_0;
4196 break;
4197 case ISurfaceComposer::eRotate90:
4198 rotationFlags = Transform::ROT_90;
4199 break;
4200 case ISurfaceComposer::eRotate180:
4201 rotationFlags = Transform::ROT_180;
4202 break;
4203 case ISurfaceComposer::eRotate270:
4204 rotationFlags = Transform::ROT_270;
4205 break;
4206 default:
4207 rotationFlags = Transform::ROT_0;
4208 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4209 break;
4210 }
4211
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004212 { // Autolock scope
4213 Mutex::Autolock lock(mStateLock);
4214 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4215 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004216 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004217
4218 // create a surface (because we're a producer, and we need to
4219 // dequeue/queue a buffer)
4220 sp<Surface> surface = new Surface(producer, false);
4221
4222 // Put the screenshot Surface into async mode so that
4223 // Layer::headFenceHasSignaled will always return true and we'll latch the
4224 // first buffer regardless of whether or not its acquire fence has
4225 // signaled. This is needed to avoid a race condition in the rotation
4226 // animation. See b/30209608
4227 surface->setAsyncMode(true);
4228
4229 ANativeWindow* window = surface.get();
4230
4231 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4232 if (result != NO_ERROR) {
4233 return result;
4234 }
4235 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4236
4237 ANativeWindowBuffer* buffer = nullptr;
4238 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4239 getRenderEngine().usesWideColor(), &buffer);
4240 if (result != NO_ERROR) {
4241 return result;
4242 }
4243
4244 // This mutex protects syncFd and captureResult for communication of the return values from the
4245 // main thread back to this Binder thread
4246 std::mutex captureMutex;
4247 std::condition_variable captureCondition;
4248 std::unique_lock<std::mutex> captureLock(captureMutex);
4249 int syncFd = -1;
4250 std::optional<status_t> captureResult;
4251
4252 sp<LambdaMessage> message = new LambdaMessage([&]() {
4253 // If there is a refresh pending, bug out early and tell the binder thread to try again
4254 // after the refresh.
4255 if (mRefreshPending) {
4256 ATRACE_NAME("Skipping screenshot for now");
4257 std::unique_lock<std::mutex> captureLock(captureMutex);
4258 captureResult = std::make_optional<status_t>(EAGAIN);
4259 captureCondition.notify_one();
4260 return;
4261 }
4262
4263 status_t result = NO_ERROR;
4264 int fd = -1;
4265 {
4266 Mutex::Autolock _l(mStateLock);
4267 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4268 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4269 minLayerZ, maxLayerZ, useIdentityTransform,
4270 rotationFlags, isLocalScreenshot, &fd);
4271 }
4272
4273 {
4274 std::unique_lock<std::mutex> captureLock(captureMutex);
4275 syncFd = fd;
4276 captureResult = std::make_optional<status_t>(result);
4277 captureCondition.notify_one();
4278 }
4279 });
4280
4281 result = postMessageAsync(message);
4282 if (result == NO_ERROR) {
4283 captureCondition.wait(captureLock, [&]() { return captureResult; });
4284 while (*captureResult == EAGAIN) {
4285 captureResult.reset();
4286 result = postMessageAsync(message);
4287 if (result != NO_ERROR) {
4288 return result;
4289 }
4290 captureCondition.wait(captureLock, [&]() { return captureResult; });
4291 }
4292 result = *captureResult;
4293 }
4294
4295 if (result == NO_ERROR) {
4296 // queueBuffer takes ownership of syncFd
4297 result = window->queueBuffer(window, buffer, syncFd);
4298 }
4299
4300 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004301}
4302
Mathias Agopian180f10d2013-04-10 22:55:41 -07004303
4304void SurfaceFlinger::renderScreenImplLocked(
4305 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004306 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004307 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004308 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004309{
4310 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004311 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004312
4313 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004314 const int32_t hw_w = hw->getWidth();
4315 const int32_t hw_h = hw->getHeight();
4316 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004317 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004318
Dan Stozac1879002014-05-22 15:59:05 -07004319 // if a default or invalid sourceCrop is passed in, set reasonable values
4320 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4321 !sourceCrop.isValid()) {
4322 sourceCrop.setLeftTop(Point(0, 0));
4323 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4324 }
4325
4326 // ensure that sourceCrop is inside screen
4327 if (sourceCrop.left < 0) {
4328 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4329 }
Dan Stozabe31f442014-06-11 11:20:54 -07004330 if (sourceCrop.right > hw_w) {
4331 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004332 }
4333 if (sourceCrop.top < 0) {
4334 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4335 }
Dan Stozabe31f442014-06-11 11:20:54 -07004336 if (sourceCrop.bottom > hw_h) {
4337 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004338 }
4339
Romain Guy88d37dd2017-05-26 17:57:05 -07004340#ifdef USE_HWC2
4341 engine.setWideColor(hw->getWideColorSupport());
4342 engine.setColorMode(hw->getActiveColorMode());
4343#endif
4344
Mathias Agopian180f10d2013-04-10 22:55:41 -07004345 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004346 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004347
4348 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004349 engine.setViewportAndProjection(
4350 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004351 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004352
4353 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004354 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004355
Robert Carr1f0a16a2016-10-24 16:27:39 -07004356 // We loop through the first level of layers without traversing,
4357 // as we need to interpret min/max layer Z in the top level Z space.
4358 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004359 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004360 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004361 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004362 const Layer::State& state(layer->getDrawingState());
4363 if (state.z < minLayerZ || state.z > maxLayerZ) {
4364 continue;
4365 }
Dan Stoza412903f2017-04-27 13:42:17 -07004366 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004367 if (!layer->isVisible()) {
4368 return;
4369 }
4370 if (filtering) layer->setFiltering(true);
4371 layer->draw(hw, useIdentityTransform);
4372 if (filtering) layer->setFiltering(false);
4373 });
4374 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004375
Mathias Agopian931bda12013-08-28 18:11:46 -07004376 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004377}
4378
Dan Stozaabcda352017-06-01 14:37:39 -07004379// A simple RAII class that holds an EGLImage and destroys it either:
4380// a) When the destroy() method is called
4381// b) When the object goes out of scope
4382class ImageHolder {
4383public:
4384 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4385 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004386
Dan Stozaabcda352017-06-01 14:37:39 -07004387 void destroy() {
4388 if (mImage != EGL_NO_IMAGE_KHR) {
4389 eglDestroyImageKHR(mDisplay, mImage);
4390 mImage = EGL_NO_IMAGE_KHR;
4391 }
4392 }
4393
4394private:
4395 const EGLDisplay mDisplay;
4396 EGLImageKHR mImage;
4397};
4398
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004399status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4400 ANativeWindowBuffer* buffer, Rect sourceCrop,
4401 uint32_t reqWidth, uint32_t reqHeight,
4402 int32_t minLayerZ, int32_t maxLayerZ,
4403 bool useIdentityTransform,
4404 Transform::orientation_flags rotation,
4405 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004406 ATRACE_CALL();
4407
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004408 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004409 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004410 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004411 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004412 (state.z < minLayerZ || state.z > maxLayerZ)) {
4413 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004414 }
Dan Stoza412903f2017-04-27 13:42:17 -07004415 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004416 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4417 layer->isSecure());
4418 });
4419 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004420
4421 if (!isLocalScreenshot && secureLayerIsVisible) {
4422 ALOGW("FB is protected: PERMISSION_DENIED");
4423 return PERMISSION_DENIED;
4424 }
4425
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004426 int syncFd = -1;
4427 // create an EGLImage from the buffer so we can later
4428 // turn it into a texture
4429 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4430 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4431 if (image == EGL_NO_IMAGE_KHR) {
4432 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004433 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004434
Dan Stozaabcda352017-06-01 14:37:39 -07004435 // This will automatically destroy the image if we return before calling its destroy method
4436 ImageHolder imageHolder(mEGLDisplay, image);
4437
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004438 // this binds the given EGLImage as a framebuffer for the
4439 // duration of this scope.
4440 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004441 if (imageBond.getStatus() != NO_ERROR) {
4442 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004443 return INVALID_OPERATION;
4444 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004445
Dan Stozaabcda352017-06-01 14:37:39 -07004446 // this will in fact render into our dequeued buffer
4447 // via an FBO, which means we didn't have to create
4448 // an EGLSurface and therefore we're not
4449 // dependent on the context's EGLConfig.
4450 renderScreenImplLocked(
4451 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4452 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004453
Dan Stozaabcda352017-06-01 14:37:39 -07004454 // Attempt to create a sync khr object that can produce a sync point. If that
4455 // isn't available, create a non-dupable sync object in the fallback path and
4456 // wait on it directly.
4457 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4458 if (!DEBUG_SCREENSHOTS) {
4459 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4460 // native fence fd will not be populated until flush() is done.
4461 getRenderEngine().flush();
4462 }
4463
4464 if (sync != EGL_NO_SYNC_KHR) {
4465 // get the sync fd
4466 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4467 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4468 ALOGW("captureScreen: failed to dup sync khr object");
4469 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004470 }
Dan Stozaabcda352017-06-01 14:37:39 -07004471 eglDestroySyncKHR(mEGLDisplay, sync);
4472 } else {
4473 // fallback path
4474 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004475 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004476 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4477 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4478 EGLint eglErr = eglGetError();
4479 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4480 ALOGW("captureScreen: fence wait timed out");
4481 } else {
4482 ALOGW_IF(eglErr != EGL_SUCCESS,
4483 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004484 }
4485 eglDestroySyncKHR(mEGLDisplay, sync);
4486 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004487 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004488 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004489 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004490 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004491
4492 if (DEBUG_SCREENSHOTS) {
4493 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4494 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4495 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4496 hw, minLayerZ, maxLayerZ);
4497 delete [] pixels;
4498 }
4499
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004500 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004501 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004502
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004503 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004504}
4505
Mathias Agopiand5556842013-09-19 17:08:37 -07004506void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004507 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004508 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004509 for (size_t y=0 ; y<h ; y++) {
4510 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4511 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004512 if (p[x] != 0xFF000000) return;
4513 }
4514 }
4515 ALOGE("*** we just took a black screenshot ***\n"
4516 "requested minz=%d, maxz=%d, layerStack=%d",
4517 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004518
Robert Carr2047fae2016-11-28 14:09:09 -08004519 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004520 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004521 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004522 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004523 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004524 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004525 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4526 layer->isVisible() ? '+' : '-',
4527 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004528 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004529 i++;
4530 });
4531 }
4532 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004533 }
4534}
4535
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004536// ---------------------------------------------------------------------------
4537
Dan Stoza412903f2017-04-27 13:42:17 -07004538void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4539 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004540}
4541
Dan Stoza412903f2017-04-27 13:42:17 -07004542void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4543 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004544}
4545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004546}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004547
4548
4549#if defined(__gl_h_)
4550#error "don't include gl/gl.h in this file"
4551#endif
4552
4553#if defined(__gl2_h_)
4554#error "don't include gl2/gl2.h in this file"
4555#endif