blob: 736346497d47e23ee100e7e32968d615038bfe71 [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;
609 signalTransaction();
610 };
611 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
612 vrFlingerRequestDisplayCallback);
613 if (!mVrFlinger) {
614 ALOGE("Failed to start vrflinger");
615 }
616 }
617
Jamie Gennisd1700752013-10-14 12:22:52 -0700618 mEventControlThread = new EventControlThread(this);
619 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
620
Mathias Agopian92a979a2012-08-02 18:32:23 -0700621 // initialize our drawing state
622 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700623
Andy McFadden13a082e2012-08-24 10:16:42 -0700624 // set initial conditions (e.g. unblank default device)
625 initializeDisplays();
626
Dan Stoza4e637772016-07-28 13:31:51 -0700627 mRenderEngine->primeCache();
628
Wei Wangf9b05ee2017-07-19 20:59:39 -0700629 // Inform native graphics APIs whether the present timestamp is supported:
630 if (getHwComposer().hasCapability(
631 HWC2::Capability::PresentFenceIsNotReliable)) {
632 mStartPropertySetThread = new StartPropertySetThread(false);
633 } else {
634 mStartPropertySetThread = new StartPropertySetThread(true);
635 }
636
637 if (mStartPropertySetThread->Start() != NO_ERROR) {
638 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800639 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800640
Dan Stoza9e56aa02015-11-02 13:00:03 -0800641 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700642}
643
Romain Guy11d63f42017-07-20 12:47:14 -0700644void SurfaceFlinger::readPersistentProperties() {
645 char value[PROPERTY_VALUE_MAX];
646
647 property_get("persist.sys.sf.color_saturation", value, "1.0");
648 mSaturation = atof(value);
649 ALOGV("Saturation is set to %.2f", mSaturation);
650}
651
Mathias Agopiana67e4182012-06-19 17:26:12 -0700652void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800653 // Start boot animation service by setting a property mailbox
654 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700655 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800656 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700657 if (mStartPropertySetThread->join() != NO_ERROR) {
658 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800659 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700660}
661
Mathias Agopian875d8e12013-06-07 15:35:48 -0700662size_t SurfaceFlinger::getMaxTextureSize() const {
663 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700664}
665
Mathias Agopian875d8e12013-06-07 15:35:48 -0700666size_t SurfaceFlinger::getMaxViewportDims() const {
667 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700668}
669
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800670// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800671
Jamie Gennis582270d2011-08-17 18:19:00 -0700672bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800673 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800674 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800675 return authenticateSurfaceTextureLocked(bufferProducer);
676}
677
678bool SurfaceFlinger::authenticateSurfaceTextureLocked(
679 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800680 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700681 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800682}
683
Brian Anderson6b376712017-04-04 10:51:39 -0700684status_t SurfaceFlinger::getSupportedFrameTimestamps(
685 std::vector<FrameEvent>* outSupported) const {
686 *outSupported = {
687 FrameEvent::REQUESTED_PRESENT,
688 FrameEvent::ACQUIRE,
689 FrameEvent::LATCH,
690 FrameEvent::FIRST_REFRESH_START,
691 FrameEvent::LAST_REFRESH_START,
692 FrameEvent::GPU_COMPOSITION_DONE,
693 FrameEvent::DEQUEUE_READY,
694 FrameEvent::RELEASE,
695 };
696 if (!getHwComposer().hasCapability(
697 HWC2::Capability::PresentFenceIsNotReliable)) {
698 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
699 }
700 return NO_ERROR;
701}
702
Dan Stoza7f7da322014-05-02 15:26:25 -0700703status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
704 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700705 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700706 return BAD_VALUE;
707 }
708
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500709 if (!display.get())
710 return NAME_NOT_FOUND;
711
Jesse Hall692c7232012-11-08 15:41:56 -0800712 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700713 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800714 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700715 type = i;
716 break;
717 }
718 }
719
720 if (type < 0) {
721 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700722 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700723
Mathias Agopian8b736f12012-08-13 17:54:26 -0700724 // TODO: Not sure if display density should handled by SF any longer
725 class Density {
726 static int getDensityFromProperty(char const* propName) {
727 char property[PROPERTY_VALUE_MAX];
728 int density = 0;
729 if (property_get(propName, property, NULL) > 0) {
730 density = atoi(property);
731 }
732 return density;
733 }
734 public:
735 static int getEmuDensity() {
736 return getDensityFromProperty("qemu.sf.lcd_density"); }
737 static int getBuildDensity() {
738 return getDensityFromProperty("ro.sf.lcd_density"); }
739 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700740
Dan Stoza7f7da322014-05-02 15:26:25 -0700741 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700742
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700744 DisplayInfo info = DisplayInfo();
745
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 float xdpi = hwConfig->getDpiX();
747 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700748
749 if (type == DisplayDevice::DISPLAY_PRIMARY) {
750 // The density of the device is provided by a build property
751 float density = Density::getBuildDensity() / 160.0f;
752 if (density == 0) {
753 // the build doesn't provide a density -- this is wrong!
754 // use xdpi instead
755 ALOGE("ro.sf.lcd_density must be defined as a build property");
756 density = xdpi / 160.0f;
757 }
758 if (Density::getEmuDensity()) {
759 // if "qemu.sf.lcd_density" is specified, it overrides everything
760 xdpi = ydpi = density = Density::getEmuDensity();
761 density /= 160.0f;
762 }
763 info.density = density;
764
765 // TODO: this needs to go away (currently needed only by webkit)
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000766 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
767 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700768 } else {
769 // TODO: where should this value come from?
770 static const int TV_DENSITY = 213;
771 info.density = TV_DENSITY / 160.0f;
772 info.orientation = 0;
773 }
774
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 info.w = hwConfig->getWidth();
776 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 info.xdpi = xdpi;
778 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800779 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900780 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781
Andy McFadden91b2ca82014-06-13 14:04:23 -0700782 // This is how far in advance a buffer must be queued for
783 // presentation at a given time. If you want a buffer to appear
784 // on the screen at time N, you must submit the buffer before
785 // (N - presentationDeadline).
786 //
787 // Normally it's one full refresh period (to give SF a chance to
788 // latch the buffer), but this can be reduced by configuring a
789 // DispSync offset. Any additional delays introduced by the hardware
790 // composer or panel must be accounted for here.
791 //
792 // We add an additional 1ms to allow for processing time and
793 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800794 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800795 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700796
797 // All non-virtual displays are currently considered secure.
798 info.secure = true;
799
Michael Wright28f24d02016-07-12 13:30:53 -0700800 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700801 }
802
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 return NO_ERROR;
804}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700805
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800806status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700807 DisplayStatInfo* stats) {
808 if (stats == NULL) {
809 return BAD_VALUE;
810 }
811
812 // FIXME for now we always return stats for the primary display
813 memset(stats, 0, sizeof(*stats));
814 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
815 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
816 return NO_ERROR;
817}
818
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700819int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800820 if (display == NULL) {
821 ALOGE("%s : display is NULL", __func__);
822 return BAD_VALUE;
823 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700824
825 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700826 if (device != NULL) {
827 return device->getActiveConfig();
828 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700829
Dan Stoza24a42e92015-03-09 10:04:11 -0700830 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700832
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700833void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
834 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
835 this);
836 int32_t type = hw->getDisplayType();
837 int currentMode = hw->getActiveConfig();
838
839 if (mode == currentMode) {
840 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
841 return;
842 }
843
844 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
845 ALOGW("Trying to set config for virtual display");
846 return;
847 }
848
849 hw->setActiveConfig(mode);
850 getHwComposer().setActiveConfig(type, mode);
851}
852
853status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
854 class MessageSetActiveConfig: public MessageBase {
855 SurfaceFlinger& mFlinger;
856 sp<IBinder> mDisplay;
857 int mMode;
858 public:
859 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
860 int mode) :
861 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
862 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700863 Vector<DisplayInfo> configs;
864 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700865 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700866 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700867 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700868 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700869 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700870 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
871 if (hw == NULL) {
872 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700873 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700874 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
875 ALOGW("Attempt to set active config = %d for virtual display",
876 mMode);
877 } else {
878 mFlinger.setActiveConfigInternal(hw, mMode);
879 }
880 return true;
881 }
882 };
883 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
884 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700885 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700886}
Michael Wright28f24d02016-07-12 13:30:53 -0700887status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
888 Vector<android_color_mode_t>* outColorModes) {
889 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
890 return BAD_VALUE;
891 }
892
893 if (!display.get()) {
894 return NAME_NOT_FOUND;
895 }
896
897 int32_t type = NAME_NOT_FOUND;
898 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
899 if (display == mBuiltinDisplays[i]) {
900 type = i;
901 break;
902 }
903 }
904
905 if (type < 0) {
906 return type;
907 }
908
909 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
910 outColorModes->clear();
911 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
912
913 return NO_ERROR;
914}
915
916android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700917 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700918 if (device != nullptr) {
919 return device->getActiveColorMode();
920 }
921 return static_cast<android_color_mode_t>(BAD_VALUE);
922}
923
924void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
925 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700926 int32_t type = hw->getDisplayType();
927 android_color_mode_t currentMode = hw->getActiveColorMode();
928
929 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700930 return;
931 }
932
933 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
934 ALOGW("Trying to set config for virtual display");
935 return;
936 }
937
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600938 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
939 hw->getDisplayType());
940
Michael Wright28f24d02016-07-12 13:30:53 -0700941 hw->setActiveColorMode(mode);
942 getHwComposer().setActiveColorMode(type, mode);
943}
944
945
946status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
947 android_color_mode_t colorMode) {
948 class MessageSetActiveColorMode: public MessageBase {
949 SurfaceFlinger& mFlinger;
950 sp<IBinder> mDisplay;
951 android_color_mode_t mMode;
952 public:
953 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
954 android_color_mode_t mode) :
955 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
956 virtual bool handler() {
957 Vector<android_color_mode_t> modes;
958 mFlinger.getDisplayColorModes(mDisplay, &modes);
959 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
960 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600961 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
962 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700963 return true;
964 }
965 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
966 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600967 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
968 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700969 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600970 ALOGW("Attempt to set active color mode %s %d for virtual display",
971 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700972 } else {
973 mFlinger.setActiveColorModeInternal(hw, mMode);
974 }
975 return true;
976 }
977 };
978 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
979 postMessageSync(msg);
980 return NO_ERROR;
981}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700982
Svetoslavd85084b2014-03-20 10:28:31 -0700983status_t SurfaceFlinger::clearAnimationFrameStats() {
984 Mutex::Autolock _l(mStateLock);
985 mAnimFrameTracker.clearStats();
986 return NO_ERROR;
987}
988
989status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
990 Mutex::Autolock _l(mStateLock);
991 mAnimFrameTracker.getStats(outStats);
992 return NO_ERROR;
993}
994
Dan Stozac4f471e2016-03-24 09:31:08 -0700995status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
996 HdrCapabilities* outCapabilities) const {
997 Mutex::Autolock _l(mStateLock);
998
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700999 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001000 if (displayDevice == nullptr) {
1001 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1002 return BAD_VALUE;
1003 }
1004
1005 std::unique_ptr<HdrCapabilities> capabilities =
1006 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1007 if (capabilities) {
1008 std::swap(*outCapabilities, *capabilities);
1009 } else {
1010 return BAD_VALUE;
1011 }
1012
1013 return NO_ERROR;
1014}
1015
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001016status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1017 if (enable == mInjectVSyncs) {
1018 return NO_ERROR;
1019 }
1020
1021 if (enable) {
1022 mInjectVSyncs = enable;
1023 ALOGV("VSync Injections enabled");
1024 if (mVSyncInjector.get() == nullptr) {
1025 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001026 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001027 }
1028 mEventQueue.setEventThread(mInjectorEventThread);
1029 } else {
1030 mInjectVSyncs = enable;
1031 ALOGV("VSync Injections disabled");
1032 mEventQueue.setEventThread(mSFEventThread);
1033 mVSyncInjector.clear();
1034 }
1035 return NO_ERROR;
1036}
1037
1038status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1039 if (!mInjectVSyncs) {
1040 ALOGE("VSync Injections not enabled");
1041 return BAD_VALUE;
1042 }
1043 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1044 ALOGV("Injecting VSync inside SurfaceFlinger");
1045 mVSyncInjector->onInjectSyncEvent(when);
1046 }
1047 return NO_ERROR;
1048}
1049
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001050// ----------------------------------------------------------------------------
1051
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001052sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1053 ISurfaceComposer::VsyncSource vsyncSource) {
1054 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1055 return mSFEventThread->createEventConnection();
1056 } else {
1057 return mEventThread->createEventConnection();
1058 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001059}
1060
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001061// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001062
1063void SurfaceFlinger::waitForEvent() {
1064 mEventQueue.waitMessage();
1065}
1066
1067void SurfaceFlinger::signalTransaction() {
1068 mEventQueue.invalidate();
1069}
1070
1071void SurfaceFlinger::signalLayerUpdate() {
1072 mEventQueue.invalidate();
1073}
1074
1075void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001076 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001077 mEventQueue.refresh();
1078}
1079
1080status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001081 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001082 return mEventQueue.postMessage(msg, reltime);
1083}
1084
1085status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001086 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001087 status_t res = mEventQueue.postMessage(msg, reltime);
1088 if (res == NO_ERROR) {
1089 msg->wait();
1090 }
1091 return res;
1092}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001093
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001094void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001095 do {
1096 waitForEvent();
1097 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001098}
1099
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001100void SurfaceFlinger::enableHardwareVsync() {
1101 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001102 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001103 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001104 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1105 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001106 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001107 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001108}
1109
Jesse Hall948fe0c2013-10-14 12:56:09 -07001110void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001111 Mutex::Autolock _l(mHWVsyncLock);
1112
Jesse Hall948fe0c2013-10-14 12:56:09 -07001113 if (makeAvailable) {
1114 mHWVsyncAvailable = true;
1115 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001116 // Hardware vsync is not currently available, so abort the resync
1117 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001118 return;
1119 }
1120
Dan Stoza9e56aa02015-11-02 13:00:03 -08001121 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1122 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001123
1124 mPrimaryDispSync.reset();
1125 mPrimaryDispSync.setPeriod(period);
1126
1127 if (!mPrimaryHWVsyncEnabled) {
1128 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001129 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1130 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001131 mPrimaryHWVsyncEnabled = true;
1132 }
1133}
1134
Jesse Hall948fe0c2013-10-14 12:56:09 -07001135void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001136 Mutex::Autolock _l(mHWVsyncLock);
1137 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001138 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1139 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001140 mPrimaryDispSync.endResync();
1141 mPrimaryHWVsyncEnabled = false;
1142 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001143 if (makeUnavailable) {
1144 mHWVsyncAvailable = false;
1145 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001146}
1147
Tim Murray4a4e4a22016-04-19 16:29:23 +00001148void SurfaceFlinger::resyncWithRateLimit() {
1149 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001150
1151 // No explicit locking is needed here since EventThread holds a lock while calling this method
1152 static nsecs_t sLastResyncAttempted = 0;
1153 const nsecs_t now = systemTime();
1154 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001155 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001156 }
Dan Stoza57164302017-05-08 14:03:54 -07001157 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001158}
1159
Steven Thomasd7f49c52017-07-26 18:48:28 -07001160void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1161 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001162 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001163 // Ignore any vsyncs from a previous hardware composer.
1164 if (sequenceId != mComposerSequenceId) {
1165 return;
1166 }
1167
1168 int32_t type;
1169 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001170 return;
1171 }
1172
Jamie Gennisd1700752013-10-14 12:22:52 -07001173 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001174
Jamie Gennisd1700752013-10-14 12:22:52 -07001175 { // Scope for the lock
1176 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001177 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001178 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001180 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001181
1182 if (needsHwVsync) {
1183 enableHardwareVsync();
1184 } else {
1185 disableHardwareVsync(false);
1186 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001187}
1188
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001189void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001190 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001191 *compositorTiming = mCompositorTiming;
1192}
1193
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001194void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001195 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001196 wp<IBinder> token = mBuiltinDisplays[type];
1197
1198 // All non-virtual displays are currently considered secure.
1199 const bool isSecure = true;
1200
1201 sp<IGraphicBufferProducer> producer;
1202 sp<IGraphicBufferConsumer> consumer;
1203 BufferQueue::createBufferQueue(&producer, &consumer);
1204
1205 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1206
1207 bool hasWideColorModes = false;
1208 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1209 for (android_color_mode_t colorMode : modes) {
1210 switch (colorMode) {
1211 case HAL_COLOR_MODE_DISPLAY_P3:
1212 case HAL_COLOR_MODE_ADOBE_RGB:
1213 case HAL_COLOR_MODE_DCI_P3:
1214 hasWideColorModes = true;
1215 break;
1216 default:
1217 break;
1218 }
1219 }
1220 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1221 token, fbs, producer, mRenderEngine->getEGLConfig(),
1222 hasWideColorModes && hasWideColorDisplay);
1223 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001224 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1225 if (hasWideColorModes && hasWideColorDisplay) {
1226 defaultColorMode = HAL_COLOR_MODE_SRGB;
1227 }
1228 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001229 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001230
1231 // Add the primary display token to mDrawingState so we don't try to
1232 // recreate the DisplayDevice for the primary display.
1233 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1234
1235 // make the GLContext current so that we can create textures when creating
1236 // Layers (which may happens before we render something)
1237 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001238}
1239
Steven Thomasd7f49c52017-07-26 18:48:28 -07001240void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1241 hwc2_display_t display, HWC2::Connection connection,
1242 bool primaryDisplay) {
1243 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1244 sequenceId, display,
1245 connection == HWC2::Connection::Connected ?
1246 "connected" : "disconnected",
1247 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001248
Steven Thomasd7f49c52017-07-26 18:48:28 -07001249 // Only lock if we're not on the main thread. This function is normally
1250 // called on a hwbinder thread, but for the primary display it's called on
1251 // the main thread with the state lock already held, so don't attempt to
1252 // acquire it here.
1253 ConditionalLock lock(mStateLock,
1254 std::this_thread::get_id() != mMainThreadId);
1255
1256 if (primaryDisplay) {
1257 mHwc->onHotplug(display, connection);
1258 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1259 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001260 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001261 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001262 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001263 if (sequenceId != mComposerSequenceId) {
1264 return;
1265 }
1266 if (mHwc->isUsingVrComposer()) {
1267 ALOGE("External displays are not supported by the vr hardware composer.");
1268 return;
1269 }
1270 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001271 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasd7f49c52017-07-26 18:48:28 -07001272 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001273 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001274 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001275 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1276 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001277 }
1278 setTransactionFlags(eDisplayTransactionNeeded);
1279
Andy McFadden9e9689c2012-10-10 18:17:51 -07001280 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001281 }
Mathias Agopian86303202012-07-24 22:46:10 -07001282}
1283
Steven Thomasd7f49c52017-07-26 18:48:28 -07001284void SurfaceFlinger::onRefreshReceived(int sequenceId,
1285 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001286 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001287 if (sequenceId != mComposerSequenceId) {
1288 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001289 }
Steven Thomasd7f49c52017-07-26 18:48:28 -07001290 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001291}
1292
Dan Stoza9e56aa02015-11-02 13:00:03 -08001293void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294 ATRACE_CALL();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001295 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296 getHwComposer().setVsyncEnabled(disp,
1297 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001298}
1299
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001300// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasd7f49c52017-07-26 18:48:28 -07001301void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001302 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001303 // Clear the drawing state so that the logic inside of
1304 // handleTransactionLocked will fire. It will determine the delta between
1305 // mCurrentState and mDrawingState and re-apply all changes when we make the
1306 // transition.
1307 mDrawingState.displays.clear();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001308 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001309 mDisplays.clear();
1310}
1311
Steven Thomas050b2c82017-03-06 11:45:16 -08001312void SurfaceFlinger::updateVrFlinger() {
1313 if (!mVrFlinger)
1314 return;
1315 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1316 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001317 return;
1318 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001319
Steven Thomasd7f49c52017-07-26 18:48:28 -07001320 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1321 ALOGE("Vr flinger is only supported for remote hardware composer"
1322 " service connections. Ignoring request to transition to vr"
1323 " flinger.");
1324 mVrFlingerRequestsDisplay = false;
1325 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001326 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001328 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001329
Steven Thomasd7f49c52017-07-26 18:48:28 -07001330 int currentDisplayPowerMode = getDisplayDeviceLocked(
1331 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001332
Steven Thomasd7f49c52017-07-26 18:48:28 -07001333 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001334 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001335 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001336
Steven Thomasd7f49c52017-07-26 18:48:28 -07001337 resetDisplayState();
1338 mHwc.reset(); // Delete the current instance before creating the new one
1339 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1340 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001341
Steven Thomasd7f49c52017-07-26 18:48:28 -07001342 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1343 "Switched to non-remote hardware composer");
1344
1345 if (vrFlingerRequestsDisplay) {
1346 mVrFlinger->GrantDisplayOwnership();
1347 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001348 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001350
1351 mVisibleRegionsDirty = true;
1352 invalidateHwcGeometry();
1353
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001354 // Re-enable default display.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001355 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1356 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1357 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001358
Steven Thomasd7f49c52017-07-26 18:48:28 -07001359 // Reset the timing values to account for the period of the swapped in HWC
1360 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1361 const nsecs_t period = activeConfig->getVsyncPeriod();
1362 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001363
Steven Thomasd7f49c52017-07-26 18:48:28 -07001364 // Use phase of 0 since phase is not known.
1365 // Use latency of 0, which will snap to the ideal latency.
1366 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001367
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368 android_atomic_or(1, &mRepaintEverything);
1369 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001370}
1371
Mathias Agopian4fec8732012-06-29 14:12:52 -07001372void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001373 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001374 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001375 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001376 bool frameMissed = !mHadClientComposition &&
1377 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001378 (mPreviousPresentFence->getSignalTime() ==
1379 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001380 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001381 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001382 signalLayerUpdate();
1383 break;
1384 }
1385
Steven Thomas050b2c82017-03-06 11:45:16 -08001386 // Now that we're going to make it to the handleMessageTransaction()
1387 // call below it's safe to call updateVrFlinger(), which will
1388 // potentially trigger a display handoff.
1389 updateVrFlinger();
1390
Dan Stoza6b9454d2014-11-07 16:00:59 -08001391 bool refreshNeeded = handleMessageTransaction();
1392 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001393 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001394 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001395 // Signal a refresh if a transaction modified the window state,
1396 // a new buffer was latched, or if HWC has requested a full
1397 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001398 signalRefresh();
1399 }
1400 break;
1401 }
1402 case MessageQueue::REFRESH: {
1403 handleMessageRefresh();
1404 break;
1405 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406 }
1407}
1408
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001410 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001411 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001412 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001413 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001414 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001415 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001416}
1417
Dan Stoza6b9454d2014-11-07 16:00:59 -08001418bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001419 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001420 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001421}
1422
1423void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001424 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001425
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001426 mRefreshPending = false;
1427
Pablo Ceballos40845df2016-01-25 17:41:15 -08001428 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001429
Brian Andersond6927fb2016-07-23 23:37:30 -07001430 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001431 rebuildLayerStacks();
1432 setUpHWComposer();
1433 doDebugFlashRegions();
1434 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001435 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001436
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001437 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001438
1439 mHadClientComposition = false;
1440 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1441 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1442 mHadClientComposition = mHadClientComposition ||
1443 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1444 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001445
Dan Stoza9e56aa02015-11-02 13:00:03 -08001446 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001448
Mathias Agopiancd60f992012-08-16 16:28:27 -07001449void SurfaceFlinger::doDebugFlashRegions()
1450{
1451 // is debugging enabled
1452 if (CC_LIKELY(!mDebugRegion))
1453 return;
1454
1455 const bool repaintEverything = mRepaintEverything;
1456 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1457 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001458 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001459 // transform the dirty region into this screen's coordinate space
1460 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1461 if (!dirtyRegion.isEmpty()) {
1462 // redraw the whole screen
1463 doComposeSurfaces(hw, Region(hw->bounds()));
1464
1465 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001466 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001467 RenderEngine& engine(getRenderEngine());
1468 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1469
Mathias Agopianda27af92012-09-13 18:17:13 -07001470 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001471 }
1472 }
1473 }
1474
1475 postFramebuffer();
1476
1477 if (mDebugRegion > 1) {
1478 usleep(mDebugRegion * 1000);
1479 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001480
Dan Stoza9e56aa02015-11-02 13:00:03 -08001481 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001482 auto& displayDevice = mDisplays[displayId];
1483 if (!displayDevice->isDisplayOn()) {
1484 continue;
1485 }
1486
1487 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001488 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1489 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001490 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491}
1492
Brian Andersond6927fb2016-07-23 23:37:30 -07001493void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001494{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001495 ATRACE_CALL();
1496 ALOGV("preComposition");
1497
Mathias Agopiancd60f992012-08-16 16:28:27 -07001498 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001499 mDrawingState.traverseInZOrder([&](Layer* layer) {
1500 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001501 needExtraInvalidate = true;
1502 }
Robert Carr2047fae2016-11-28 14:09:09 -08001503 });
1504
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505 if (needExtraInvalidate) {
1506 signalLayerUpdate();
1507 }
1508}
1509
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510void SurfaceFlinger::updateCompositorTiming(
1511 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1512 std::shared_ptr<FenceTime>& presentFenceTime) {
1513 // Update queue of past composite+present times and determine the
1514 // most recently known composite to present latency.
1515 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1516 nsecs_t compositeToPresentLatency = -1;
1517 while (!mCompositePresentTimes.empty()) {
1518 CompositePresentTime& cpt = mCompositePresentTimes.front();
1519 // Cached values should have been updated before calling this method,
1520 // which helps avoid duplicate syscalls.
1521 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1522 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1523 break;
1524 }
1525 compositeToPresentLatency = displayTime - cpt.composite;
1526 mCompositePresentTimes.pop();
1527 }
1528
1529 // Don't let mCompositePresentTimes grow unbounded, just in case.
1530 while (mCompositePresentTimes.size() > 16) {
1531 mCompositePresentTimes.pop();
1532 }
1533
Brian Andersond0010582017-03-07 13:20:31 -08001534 setCompositorTimingSnapped(
1535 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1536}
1537
1538void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1539 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001540 // Integer division and modulo round toward 0 not -inf, so we need to
1541 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001542 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001543 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1544 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1545
Brian Andersond0010582017-03-07 13:20:31 -08001546 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1547 if (idealLatency <= 0) {
1548 idealLatency = vsyncInterval;
1549 }
1550
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001551 // Snap the latency to a value that removes scheduling jitter from the
1552 // composition and present times, which often have >1ms of jitter.
1553 // Reducing jitter is important if an app attempts to extrapolate
1554 // something (such as user input) to an accurate diasplay time.
1555 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1556 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001557 nsecs_t bias = vsyncInterval / 2;
1558 int64_t extraVsyncs =
1559 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1560 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1561 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001562
Brian Andersond0010582017-03-07 13:20:31 -08001563 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001564 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1565 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001566 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001567}
1568
1569void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001570{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001571 ATRACE_CALL();
1572 ALOGV("postComposition");
1573
Brian Anderson3546a3f2016-07-14 11:51:14 -07001574 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001575 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001576 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001577 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001578 }
1579
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001580 // |mStateLock| not needed as we are on the main thread
1581 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001582
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001583 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001584 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1585 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1586 glCompositionDoneFenceTime =
1587 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1588 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1589 } else {
1590 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1591 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001592
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001593 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001594 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1595 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1596 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001597
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001598 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1599 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1600
1601 // We use the refreshStartTime which might be sampled a little later than
1602 // when we started doing work for this frame, but that should be okay
1603 // since updateCompositorTiming has snapping logic.
1604 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001605 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001606 CompositorTiming compositorTiming;
1607 {
1608 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1609 compositorTiming = mCompositorTiming;
1610 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001611
Robert Carr2047fae2016-11-28 14:09:09 -08001612 mDrawingState.traverseInZOrder([&](Layer* layer) {
1613 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001614 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001615 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001616 recordBufferingStats(layer->getName().string(),
1617 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001618 }
Robert Carr2047fae2016-11-28 14:09:09 -08001619 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001620
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001621 if (presentFenceTime->isValid()) {
1622 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001623 enableHardwareVsync();
1624 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001625 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001626 }
1627 }
1628
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001629 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001630 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001631 enableHardwareVsync();
1632 }
1633 }
1634
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001635 if (mAnimCompositionPending) {
1636 mAnimCompositionPending = false;
1637
Brian Anderson4e606e32017-03-16 15:34:57 -07001638 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001639 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001640 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001641 } else {
1642 // The HWC doesn't support present fences, so use the refresh
1643 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001644 nsecs_t presentTime =
1645 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001646 mAnimFrameTracker.setActualPresentTime(presentTime);
1647 }
1648 mAnimFrameTracker.advanceFrame();
1649 }
Dan Stozab90cf072015-03-05 11:05:59 -08001650
1651 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1652 return;
1653 }
1654
1655 nsecs_t currentTime = systemTime();
1656 if (mHasPoweredOff) {
1657 mHasPoweredOff = false;
1658 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001659 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001660 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001661 if (numPeriods < NUM_BUCKETS - 1) {
1662 mFrameBuckets[numPeriods] += elapsedTime;
1663 } else {
1664 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1665 }
1666 mTotalTime += elapsedTime;
1667 }
1668 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001669}
1670
1671void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 ATRACE_CALL();
1673 ALOGV("rebuildLayerStacks");
1674
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001676 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1677 ATRACE_CALL();
1678 mVisibleRegionsDirty = false;
1679 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001680
Jeff Sharkey76488112017-02-27 14:15:18 -07001681 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1682 Region opaqueRegion;
1683 Region dirtyRegion;
1684 Vector<sp<Layer>> layersSortedByZ;
1685 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1686 const Transform& tr(displayDevice->getTransform());
1687 const Rect bounds(displayDevice->getBounds());
1688 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001689 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001690
Jeff Sharkey76488112017-02-27 14:15:18 -07001691 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001692 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1693 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001694 Region drawRegion(tr.transform(
1695 layer->visibleNonTransparentRegion));
1696 drawRegion.andSelf(bounds);
1697 if (!drawRegion.isEmpty()) {
1698 layersSortedByZ.add(layer);
1699 } else {
1700 // Clear out the HWC layer if this layer was
1701 // previously visible, but no longer is
Steven Thomasd7f49c52017-07-26 18:48:28 -07001702 layer->destroyHwcLayer(
1703 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001704 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001705 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001706 // WM changes displayDevice->layerStack upon sleep/awake.
1707 // Here we make sure we delete the HWC layers even if
1708 // WM changed their layer stack.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001709 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001710 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001711 });
1712 }
1713 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1714 displayDevice->undefinedRegion.set(bounds);
1715 displayDevice->undefinedRegion.subtractSelf(
1716 tr.transform(opaqueRegion));
1717 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001718 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001719 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001720}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001721
Romain Guy0147a172017-06-01 13:53:56 -07001722mat4 SurfaceFlinger::computeSaturationMatrix() const {
1723 if (mSaturation == 1.0f) {
1724 return mat4();
1725 }
1726
1727 // Rec.709 luma coefficients
1728 float3 luminance{0.213f, 0.715f, 0.072f};
1729 luminance *= 1.0f - mSaturation;
1730 return mat4(
1731 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1732 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1733 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1734 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1735 );
1736}
1737
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001738// pickColorMode translates a given dataspace into the best available color mode.
1739// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001740android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001741 switch (dataSpace) {
1742 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1743 // system expects.
1744 case HAL_DATASPACE_UNKNOWN:
1745 case HAL_DATASPACE_SRGB:
1746 case HAL_DATASPACE_V0_SRGB:
1747 return HAL_COLOR_MODE_SRGB;
1748 break;
1749
1750 case HAL_DATASPACE_DISPLAY_P3:
1751 return HAL_COLOR_MODE_DISPLAY_P3;
1752 break;
1753
1754 default:
1755 // TODO (courtneygo): Do we want to assert an error here?
1756 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1757 dataSpace);
1758 return HAL_COLOR_MODE_SRGB;
1759 break;
1760 }
1761}
1762
Romain Guy0147a172017-06-01 13:53:56 -07001763android_dataspace SurfaceFlinger::bestTargetDataSpace(
1764 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001765 // Only support sRGB and Display-P3 right now.
1766 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1767 return HAL_DATASPACE_DISPLAY_P3;
1768 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001769 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1770 return HAL_DATASPACE_DISPLAY_P3;
1771 }
1772 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1773 return HAL_DATASPACE_DISPLAY_P3;
1774 }
1775
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001776 return HAL_DATASPACE_V0_SRGB;
1777}
1778
Mathias Agopiancd60f992012-08-16 16:28:27 -07001779void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001780 ATRACE_CALL();
1781 ALOGV("setUpHWComposer");
1782
Jesse Hall028dc8f2013-08-20 16:35:32 -07001783 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001784 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1785 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1786 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1787
1788 // If nothing has changed (!dirty), don't recompose.
1789 // If something changed, but we don't currently have any visible layers,
1790 // and didn't when we last did a composition, then skip it this time.
1791 // The second rule does two things:
1792 // - When all layers are removed from a display, we'll emit one black
1793 // frame, then nothing more until we get new layers.
1794 // - When a display is created with a private layer stack, we won't
1795 // emit any black frames until a layer is added to the layer stack.
1796 bool mustRecompose = dirty && !(empty && wasEmpty);
1797
1798 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1799 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1800 mustRecompose ? "doing" : "skipping",
1801 dirty ? "+" : "-",
1802 empty ? "+" : "-",
1803 wasEmpty ? "+" : "-");
1804
Dan Stoza71433162014-02-04 16:22:36 -08001805 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001806
1807 if (mustRecompose) {
1808 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1809 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001810 }
1811
Dan Stoza9e56aa02015-11-02 13:00:03 -08001812 // build the h/w work list
1813 if (CC_UNLIKELY(mGeometryInvalid)) {
1814 mGeometryInvalid = false;
1815 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1816 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1817 const auto hwcId = displayDevice->getHwcDisplayId();
1818 if (hwcId >= 0) {
1819 const Vector<sp<Layer>>& currentLayers(
1820 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001821 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001822 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001823 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001824 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001826 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001827 }
1828 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001829
Robert Carrae060832016-11-28 10:51:00 -08001830 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001831 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001832 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001833 }
1834 }
1835 }
1836 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001837 }
Riley Andrews03414a12014-07-01 14:22:59 -07001838
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001839
Romain Guy0147a172017-06-01 13:53:56 -07001840 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001841
Dan Stoza9e56aa02015-11-02 13:00:03 -08001842 // Set the per-frame data
1843 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1844 auto& displayDevice = mDisplays[displayId];
1845 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001846
Dan Stoza9e56aa02015-11-02 13:00:03 -08001847 if (hwcId < 0) {
1848 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001849 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001850 if (colorMatrix != mPreviousColorMatrix) {
1851 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1852 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1853 "display %zd: %d", displayId, result);
1854 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1856 layer->setPerFrameData(displayDevice);
1857 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001858
1859 if (hasWideColorDisplay) {
1860 android_color_mode newColorMode;
1861 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1862
1863 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1864 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1865 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1866 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1867 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1868 }
1869 newColorMode = pickColorMode(newDataSpace);
1870
Thierry Strudel2924d012017-08-14 15:19:37 -07001871 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001872 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 }
1874
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001875 mPreviousColorMatrix = colorMatrix;
1876
Dan Stoza9e56aa02015-11-02 13:00:03 -08001877 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001878 auto& displayDevice = mDisplays[displayId];
1879 if (!displayDevice->isDisplayOn()) {
1880 continue;
1881 }
1882
1883 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1885 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001886 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001887}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001888
Mathias Agopiancd60f992012-08-16 16:28:27 -07001889void SurfaceFlinger::doComposition() {
1890 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 ALOGV("doComposition");
1892
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001893 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001894 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001895 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001896 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001897 // transform the dirty region into this screen's coordinate space
1898 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001899
1900 // repaint the framebuffer (if needed)
1901 doDisplayComposition(hw, dirtyRegion);
1902
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903 hw->dirtyRegion.clear();
1904 hw->flip(hw->swapRegion);
1905 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001906 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001907 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001908 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001909}
1910
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001911void SurfaceFlinger::postFramebuffer()
1912{
Mathias Agopian841cde52012-03-01 15:44:37 -08001913 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001914 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001915
Mathias Agopiana44b0412011-10-16 18:46:35 -07001916 const nsecs_t now = systemTime();
1917 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001918
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1920 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001921 if (!displayDevice->isDisplayOn()) {
1922 continue;
1923 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001924 const auto hwcId = displayDevice->getHwcDisplayId();
1925 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001926 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001927 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001928 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001929 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001930 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1931 sp<Fence> releaseFence = Fence::NO_FENCE;
1932 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1933 releaseFence = displayDevice->getClientTargetAcquireFence();
1934 } else {
1935 auto hwcLayer = layer->getHwcLayer(hwcId);
1936 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001937 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 layer->onLayerDisplayed(releaseFence);
1939 }
1940 if (hwcId >= 0) {
1941 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001942 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001943 }
1944
Mathias Agopiana44b0412011-10-16 18:46:35 -07001945 mLastSwapBufferTime = systemTime() - now;
1946 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001947
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001948 // |mStateLock| not needed as we are on the main thread
1949 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001950 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1951 logFrameStats();
1952 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001953}
1954
Mathias Agopian87baae12012-07-31 12:38:26 -07001955void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001956{
Mathias Agopian841cde52012-03-01 15:44:37 -08001957 ATRACE_CALL();
1958
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001959 // here we keep a copy of the drawing state (that is the state that's
1960 // going to be overwritten by handleTransactionLocked()) outside of
1961 // mStateLock so that the side-effects of the State assignment
1962 // don't happen with mStateLock held (which can cause deadlocks).
1963 State drawingState(mDrawingState);
1964
Mathias Agopianca4d3602011-05-19 15:38:14 -07001965 Mutex::Autolock _l(mStateLock);
1966 const nsecs_t now = systemTime();
1967 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001968
Mathias Agopianca4d3602011-05-19 15:38:14 -07001969 // Here we're guaranteed that some transaction flags are set
1970 // so we can call handleTransactionLocked() unconditionally.
1971 // We call getTransactionFlags(), which will also clear the flags,
1972 // with mStateLock held to guarantee that mCurrentState won't change
1973 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001974
Mathias Agopiane57f2922012-08-09 16:29:12 -07001975 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001976 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001977
Mathias Agopianca4d3602011-05-19 15:38:14 -07001978 mLastTransactionTime = systemTime() - now;
1979 mDebugInTransaction = 0;
1980 invalidateHwcGeometry();
1981 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001982}
1983
Mathias Agopian87baae12012-07-31 12:38:26 -07001984void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001985{
Dan Stoza7dde5992015-05-22 09:51:44 -07001986 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001987 mCurrentState.traverseInZOrder([](Layer* layer) {
1988 layer->notifyAvailableFrames();
1989 });
Dan Stoza7dde5992015-05-22 09:51:44 -07001990
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001991 /*
1992 * Traversal of the children
1993 * (perform the transaction for each of them if needed)
1994 */
1995
Mathias Agopian3559b072012-08-15 13:46:03 -07001996 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001997 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001998 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001999 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002000
2001 const uint32_t flags = layer->doTransaction(0);
2002 if (flags & Layer::eVisibleRegion)
2003 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002004 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002005 }
2006
2007 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002008 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002009 */
2010
Mathias Agopiane57f2922012-08-09 16:29:12 -07002011 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002012 // here we take advantage of Vector's copy-on-write semantics to
2013 // improve performance by skipping the transaction entirely when
2014 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002015 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2016 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002017 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002019 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002020 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002021
2022 // find the displays that were removed
2023 // (ie: in drawing state but not in current state)
2024 // also handle displays that changed
2025 // (ie: displays that are in both lists)
2026 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002027 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2028 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002029 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002030 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002031 // Call makeCurrent() on the primary display so we can
2032 // be sure that nothing associated with this display
2033 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002034 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002035 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002036 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002037 if (hw != NULL)
2038 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002039 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002040 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002041 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002042 } else {
2043 ALOGW("trying to remove the main display");
2044 }
2045 } else {
2046 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002047 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002048 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002049 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2050 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002051 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002052 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002053 // recreating the DisplayDevice, so we just remove it
2054 // from the drawing state, so that it get re-added
2055 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002056 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002057 if (hw != NULL)
2058 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002059 mDisplays.removeItem(display);
2060 mDrawingState.displays.removeItemsAt(i);
2061 dc--; i--;
2062 // at this point we must loop to the next item
2063 continue;
2064 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002065
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002066 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002067 if (disp != NULL) {
2068 if (state.layerStack != draw[i].layerStack) {
2069 disp->setLayerStack(state.layerStack);
2070 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002071 if ((state.orientation != draw[i].orientation)
2072 || (state.viewport != draw[i].viewport)
2073 || (state.frame != draw[i].frame))
2074 {
2075 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002076 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002077 }
Michael Lentine47e45402014-07-18 15:34:25 -07002078 if (state.width != draw[i].width || state.height != draw[i].height) {
2079 disp->setDisplaySize(state.width, state.height);
2080 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002081 }
2082 }
2083 }
2084
2085 // find displays that were added
2086 // (ie: in current state but not in drawing state)
2087 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002088 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002089 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002090
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002091 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002092 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002093 sp<IGraphicBufferProducer> bqProducer;
2094 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002095 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002096
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002098 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002099 // Virtual displays without a surface are dormant:
2100 // they have external state (layer stack, projection,
2101 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002102 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002103
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002104 // Allow VR composer to use virtual displays.
Steven Thomasd7f49c52017-07-26 18:48:28 -07002105 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002106 int width = 0;
2107 int status = state.surface->query(
2108 NATIVE_WINDOW_WIDTH, &width);
2109 ALOGE_IF(status != NO_ERROR,
2110 "Unable to query width (%d)", status);
2111 int height = 0;
2112 status = state.surface->query(
2113 NATIVE_WINDOW_HEIGHT, &height);
2114 ALOGE_IF(status != NO_ERROR,
2115 "Unable to query height (%d)", status);
2116 int intFormat = 0;
2117 status = state.surface->query(
2118 NATIVE_WINDOW_FORMAT, &intFormat);
2119 ALOGE_IF(status != NO_ERROR,
2120 "Unable to query format (%d)", status);
2121 auto format = static_cast<android_pixel_format_t>(
2122 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002123
Dan Stoza8cf150a2016-08-02 10:27:31 -07002124 mHwc->allocateVirtualDisplay(width, height, &format,
2125 &hwcId);
2126 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002127
Dan Stoza5cf424b2016-05-20 14:02:39 -07002128 // TODO: Plumb requested format back up to consumer
2129
Dan Stoza9e56aa02015-11-02 13:00:03 -08002130 sp<VirtualDisplaySurface> vds =
2131 new VirtualDisplaySurface(*mHwc,
2132 hwcId, state.surface, bqProducer,
2133 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002134
2135 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002136 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002137 }
2138 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002139 ALOGE_IF(state.surface!=NULL,
2140 "adding a supported display, but rendering "
2141 "surface is provided (%p), ignoring it",
2142 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002143
2144 hwcId = state.type;
2145 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2146 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002147 }
2148
2149 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002150 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002151 sp<DisplayDevice> hw =
2152 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2153 dispSurface, producer,
2154 mRenderEngine->getEGLConfig(),
2155 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002156 hw->setLayerStack(state.layerStack);
2157 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002158 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002159 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002160 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002161 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002162 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002163 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002164 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002165 }
2166 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002167 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002169
Mathias Agopian84300952012-11-21 16:02:13 -08002170 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2171 // The transform hint might have changed for some layers
2172 // (either because a display has changed, or because a layer
2173 // as changed).
2174 //
2175 // Walk through all the layers in currentLayers,
2176 // and update their transform hint.
2177 //
2178 // If a layer is visible only on a single display, then that
2179 // display is used to calculate the hint, otherwise we use the
2180 // default display.
2181 //
2182 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2183 // the hint is set before we acquire a buffer from the surface texture.
2184 //
2185 // NOTE: layer transactions have taken place already, so we use their
2186 // drawing state. However, SurfaceFlinger's own transaction has not
2187 // happened yet, so we must use the current state layer list
2188 // (soon to become the drawing state list).
2189 //
2190 sp<const DisplayDevice> disp;
2191 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002192 bool first = true;
2193 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002194 // NOTE: we rely on the fact that layers are sorted by
2195 // layerStack first (so we don't have to traverse the list
2196 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002197 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002198 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002199 currentlayerStack = layerStack;
2200 // figure out if this layerstack is mirrored
2201 // (more than one display) if so, pick the default display,
2202 // if not, pick the only display it's on.
2203 disp.clear();
2204 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2205 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002206 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002207 if (disp == NULL) {
2208 disp = hw;
2209 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002210 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002211 break;
2212 }
2213 }
2214 }
2215 }
Chet Haase91d25932013-04-11 15:24:55 -07002216 if (disp == NULL) {
2217 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2218 // redraw after transform hint changes. See bug 8508397.
2219
2220 // could be null when this layer is using a layerStack
2221 // that is not visible on any display. Also can occur at
2222 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002223 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002224 }
Chet Haase91d25932013-04-11 15:24:55 -07002225 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002226
2227 first = false;
2228 });
Mathias Agopian84300952012-11-21 16:02:13 -08002229 }
2230
2231
Mathias Agopian3559b072012-08-15 13:46:03 -07002232 /*
2233 * Perform our own transaction if needed
2234 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002235
2236 if (mLayersAdded) {
2237 mLayersAdded = false;
2238 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002239 mVisibleRegionsDirty = true;
2240 }
2241
2242 // some layers might have been removed, so
2243 // we need to update the regions they're exposing.
2244 if (mLayersRemoved) {
2245 mLayersRemoved = false;
2246 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002247 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002248 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002249 // this layer is not visible anymore
2250 // TODO: we could traverse the tree from front to back and
2251 // compute the actual visible region
2252 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002253 Region visibleReg;
2254 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002255 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002256 }
Robert Carr2047fae2016-11-28 14:09:09 -08002257 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002258 }
2259
2260 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002261
2262 updateCursorAsync();
2263}
2264
2265void SurfaceFlinger::updateCursorAsync()
2266{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002267 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2268 auto& displayDevice = mDisplays[displayId];
2269 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002270 continue;
2271 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002272
2273 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2274 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002275 }
2276 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002277}
2278
2279void SurfaceFlinger::commitTransaction()
2280{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002281 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002282 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002283 for (const auto& l : mLayersPendingRemoval) {
2284 recordBufferingStats(l->getName().string(),
2285 l->getOccupancyHistory(true));
2286 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002287 }
2288 mLayersPendingRemoval.clear();
2289 }
2290
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002291 // If this transaction is part of a window animation then the next frame
2292 // we composite should be considered an animation as well.
2293 mAnimCompositionPending = mAnimTransactionPending;
2294
Mathias Agopian4fec8732012-06-29 14:12:52 -07002295 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002296 mDrawingState.traverseInZOrder([](Layer* layer) {
2297 layer->commitChildList();
2298 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002299 mTransactionPending = false;
2300 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002301 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302}
2303
Chia-I Wuab0c3192017-08-01 11:29:00 -07002304void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002305 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306{
Mathias Agopian841cde52012-03-01 15:44:37 -08002307 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002308 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002309
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310 Region aboveOpaqueLayers;
2311 Region aboveCoveredLayers;
2312 Region dirty;
2313
Mathias Agopian87baae12012-07-31 12:38:26 -07002314 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002315
Robert Carr2047fae2016-11-28 14:09:09 -08002316 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002317 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002318 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Jesse Hall01e29052013-02-19 16:13:35 -08002320 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002321 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002322 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002323
Mathias Agopianab028732010-03-16 16:41:46 -07002324 /*
2325 * opaqueRegion: area of a surface that is fully opaque.
2326 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002327 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002328
2329 /*
2330 * visibleRegion: area of a surface that is visible on screen
2331 * and not fully transparent. This is essentially the layer's
2332 * footprint minus the opaque regions above it.
2333 * Areas covered by a translucent surface are considered visible.
2334 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002336
2337 /*
2338 * coveredRegion: area of a surface that is covered by all
2339 * visible regions above it (which includes the translucent areas).
2340 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002342
Jesse Halla8026d22012-09-25 13:25:04 -07002343 /*
2344 * transparentRegion: area of a surface that is hinted to be completely
2345 * transparent. This is only used to tell when the layer has no visible
2346 * non-transparent regions and can be removed from the layer list. It
2347 * does not affect the visibleRegion of this layer or any layers
2348 * beneath it. The hint may not be correct if apps don't respect the
2349 * SurfaceView restrictions (which, sadly, some don't).
2350 */
2351 Region transparentRegion;
2352
Mathias Agopianab028732010-03-16 16:41:46 -07002353
2354 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002355 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002356 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002357 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002359 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002360 if (!visibleRegion.isEmpty()) {
2361 // Remove the transparent area from the visible region
2362 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002363 if (tr.preserveRects()) {
2364 // transform the transparent region
2365 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002366 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002367 // transformation too complex, can't do the
2368 // transparent region optimization.
2369 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002370 }
Mathias Agopianab028732010-03-16 16:41:46 -07002371 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002372
Mathias Agopianab028732010-03-16 16:41:46 -07002373 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002374 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002375 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002376 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2377 // the opaque region is the layer's footprint
2378 opaqueRegion = visibleRegion;
2379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002380 }
2381 }
2382
Mathias Agopianab028732010-03-16 16:41:46 -07002383 // Clip the covered region to the visible region
2384 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2385
2386 // Update aboveCoveredLayers for next (lower) layer
2387 aboveCoveredLayers.orSelf(visibleRegion);
2388
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002389 // subtract the opaque region covered by the layers above us
2390 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391
2392 // compute this layer's dirty region
2393 if (layer->contentDirty) {
2394 // we need to invalidate the whole region
2395 dirty = visibleRegion;
2396 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002397 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398 layer->contentDirty = false;
2399 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002400 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002401 * the exposed region consists of two components:
2402 * 1) what's VISIBLE now and was COVERED before
2403 * 2) what's EXPOSED now less what was EXPOSED before
2404 *
2405 * note that (1) is conservative, we start with the whole
2406 * visible region but only keep what used to be covered by
2407 * something -- which mean it may have been exposed.
2408 *
2409 * (2) handles areas that were not covered by anything but got
2410 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002411 */
Mathias Agopianab028732010-03-16 16:41:46 -07002412 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002413 const Region oldVisibleRegion = layer->visibleRegion;
2414 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002415 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2416 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002417 }
2418 dirty.subtractSelf(aboveOpaqueLayers);
2419
2420 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002421 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422
Mathias Agopianab028732010-03-16 16:41:46 -07002423 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002424 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002425
Jesse Halla8026d22012-09-25 13:25:04 -07002426 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427 layer->setVisibleRegion(visibleRegion);
2428 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002429 layer->setVisibleNonTransparentRegion(
2430 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002431 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002432
Mathias Agopian87baae12012-07-31 12:38:26 -07002433 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002434}
2435
Chia-I Wuab0c3192017-08-01 11:29:00 -07002436void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002437 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002438 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002439 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002440 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002441 }
2442 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002443}
2444
Dan Stoza6b9454d2014-11-07 16:00:59 -08002445bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002447 ALOGV("handlePageFlip");
2448
Brian Andersond6927fb2016-07-23 23:37:30 -07002449 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002452 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002453 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002454
2455 // Store the set of layers that need updates. This set must not change as
2456 // buffers are being latched, as this could result in a deadlock.
2457 // Example: Two producers share the same command stream and:
2458 // 1.) Layer 0 is latched
2459 // 2.) Layer 0 gets a new frame
2460 // 2.) Layer 1 gets a new frame
2461 // 3.) Layer 1 is latched.
2462 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2463 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002464 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002465 if (layer->hasQueuedFrame()) {
2466 frameQueued = true;
2467 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002468 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002469 } else {
2470 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002471 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002472 } else {
2473 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002474 }
Robert Carr2047fae2016-11-28 14:09:09 -08002475 });
2476
Dan Stoza9e56aa02015-11-02 13:00:03 -08002477 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002478 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002479 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002480 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002481 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002482 newDataLatched = true;
2483 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002484 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002485
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002486 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002487
2488 // If we will need to wake up at some time in the future to deal with a
2489 // queued frame that shouldn't be displayed during this vsync period, wake
2490 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002491 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002492 signalLayerUpdate();
2493 }
2494
2495 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002496 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497}
2498
Mathias Agopianad456f92011-01-13 17:53:01 -08002499void SurfaceFlinger::invalidateHwcGeometry()
2500{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002502}
2503
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002504
Fabien Sanglard830b8472016-11-30 16:35:58 -08002505void SurfaceFlinger::doDisplayComposition(
2506 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002507 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002508{
Dan Stoza71433162014-02-04 16:22:36 -08002509 // We only need to actually compose the display if:
2510 // 1) It is being handled by hardware composer, which may need this to
2511 // keep its virtual display state machine in sync, or
2512 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002513 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002514 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002515 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002516 return;
2517 }
2518
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 ALOGV("doDisplayComposition");
2520
Mathias Agopian87baae12012-07-31 12:38:26 -07002521 Region dirtyRegion(inDirtyRegion);
2522
Mathias Agopianb8a55602009-06-26 19:06:36 -07002523 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002524 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002525
Fabien Sanglard830b8472016-11-30 16:35:58 -08002526 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002527 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002528 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2529 // takes a rectangle, we must make sure to update that whole
2530 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002531 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002532 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002533 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002534 // We need to redraw the rectangle that will be updated
2535 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002536 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002537 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002538 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002539 } else {
2540 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002541 dirtyRegion.set(displayDevice->bounds());
2542 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543 }
2544 }
2545
Fabien Sanglard830b8472016-11-30 16:35:58 -08002546 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002548 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002549 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002550
2551 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002552 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553}
2554
Dan Stoza9e56aa02015-11-02 13:00:03 -08002555bool SurfaceFlinger::doComposeSurfaces(
2556 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002557{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002558 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002559
Dan Stoza9e56aa02015-11-02 13:00:03 -08002560 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002561
2562 mat4 oldColorMatrix;
2563 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2564 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2565 if (applyColorMatrix) {
2566 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2567 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2568 }
2569
Dan Stoza9e56aa02015-11-02 13:00:03 -08002570 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2571 if (hasClientComposition) {
2572 ALOGV("hasClientComposition");
2573
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002574#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002575 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002576 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002577#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002578 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002579 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002580 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002581 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002582
2583 // |mStateLock| not needed as we are on the main thread
2584 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002585 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2586 }
2587 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002588 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002589
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002590 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002591 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2592 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002593 // when using overlays, we assume a fully transparent framebuffer
2594 // NOTE: we could reduce how much we need to clear, for instance
2595 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002596 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002597 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002599 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002600 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002601 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002602
2603 // we remove the scissor part
2604 // we're left with the letterbox region
2605 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002606 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002607
2608 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002610
2611 // but limit it to the dirty region
2612 region.andSelf(dirty);
2613
Mathias Agopianb9494d52012-04-18 02:28:45 -07002614 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002615 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002616 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002617 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002618 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002619 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002620
Dan Stoza9e56aa02015-11-02 13:00:03 -08002621 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002622 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002623 // scissor on the main display. It should never be needed
2624 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002625 const Rect& bounds(displayDevice->getBounds());
2626 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002627 if (scissor != bounds) {
2628 // scissor doesn't match the screen's dimensions, so we
2629 // need to clear everything outside of it and enable
2630 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002631
Mathias Agopianf45c5102012-10-24 16:29:17 -07002632 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002633 const uint32_t height = displayDevice->getHeight();
2634 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002635 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002636 }
2637 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002638 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002639
Mathias Agopian85d751c2012-08-29 16:59:24 -07002640 /*
2641 * and then, render the layers targeted at the framebuffer
2642 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002643
Dan Stoza9e56aa02015-11-02 13:00:03 -08002644 ALOGV("Rendering client layers");
2645 const Transform& displayTransform = displayDevice->getTransform();
2646 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002647 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002648 bool firstLayer = true;
2649 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2650 const Region clip(dirty.intersect(
2651 displayTransform.transform(layer->visibleRegion)));
2652 ALOGV("Layer: %s", layer->getName().string());
2653 ALOGV(" Composition type: %s",
2654 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002655 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 switch (layer->getCompositionType(hwcId)) {
2657 case HWC2::Composition::Cursor:
2658 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002659 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002661 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2663 layer->isOpaque(state) && (state.alpha == 1.0f)
2664 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002665 // never clear the very first layer since we're
2666 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002667 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002668 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002669 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002670 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002671 case HWC2::Composition::Client: {
2672 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002673 break;
2674 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002676 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002677 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 } else {
2679 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002680 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002681 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002682 }
2683 } else {
2684 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002686 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002688 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002690 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002691 }
2692 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002693
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002694 if (applyColorMatrix) {
2695 getRenderEngine().setupColorTransform(oldColorMatrix);
2696 }
2697
Mathias Agopianf45c5102012-10-24 16:29:17 -07002698 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002700 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701}
2702
Fabien Sanglard830b8472016-11-30 16:35:58 -08002703void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2704 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002705 RenderEngine& engine(getRenderEngine());
2706 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002707}
2708
Dan Stoza7d89d062015-04-30 13:29:25 -07002709status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002710 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002711 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002712 const sp<Layer>& lbc,
2713 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002714{
Dan Stoza7d89d062015-04-30 13:29:25 -07002715 // add this layer to the current state list
2716 {
2717 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002719 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2720 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002721 return NO_MEMORY;
2722 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002723 if (parent == nullptr) {
2724 mCurrentState.layersSortedByZ.add(lbc);
2725 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002726 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2727 ALOGE("addClientLayer called with a removed parent");
2728 return NAME_NOT_FOUND;
2729 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002730 parent->addChild(lbc);
2731 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002732
Dan Stoza7d89d062015-04-30 13:29:25 -07002733 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 mLayersAdded = true;
2735 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002736 }
2737
Mathias Agopian96f08192010-06-02 23:28:45 -07002738 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002739 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002740
Dan Stoza7d89d062015-04-30 13:29:25 -07002741 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002742}
2743
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002744status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002745 Mutex::Autolock _l(mStateLock);
2746
Robert Carr1f0a16a2016-10-24 16:27:39 -07002747 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002748 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002749 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002750 if (topLevelOnly) {
2751 return NO_ERROR;
2752 }
2753
Chia-I Wu98f1c102017-05-30 14:54:08 -07002754 sp<Layer> ancestor = p;
2755 while (ancestor->getParent() != nullptr) {
2756 ancestor = ancestor->getParent();
2757 }
2758 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2759 ALOGE("removeLayer called with a layer whose parent has been removed");
2760 return NAME_NOT_FOUND;
2761 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002762
2763 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002764 } else {
2765 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002766 }
2767
Robert Carr136e2f62017-02-08 17:54:29 -08002768 // As a matter of normal operation, the LayerCleaner will produce a second
2769 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2770 // so we will succeed in promoting it, but it's already been removed
2771 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2772 // otherwise something has gone wrong and we are leaking the layer.
2773 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2775 layer->getName().string(),
2776 (p != nullptr) ? p->getName().string() : "no-parent");
2777 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002778 } else if (index < 0) {
2779 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002780 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781
Chia-I Wuc6657022017-08-15 11:18:17 -07002782 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 mLayersPendingRemoval.add(layer);
2784 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002785 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 setTransactionFlags(eTransactionNeeded);
2787 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002788}
2789
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002790uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002791 return android_atomic_release_load(&mTransactionFlags);
2792}
2793
Mathias Agopian3f844832013-08-07 21:24:32 -07002794uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2796}
2797
Mathias Agopian3f844832013-08-07 21:24:32 -07002798uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2800 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002801 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 }
2803 return old;
2804}
2805
Mathias Agopian8b33f032012-07-24 20:43:54 -07002806void SurfaceFlinger::setTransactionState(
2807 const Vector<ComposerState>& state,
2808 const Vector<DisplayState>& displays,
2809 uint32_t flags)
2810{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002811 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002812 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002813 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002814
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002815 if (flags & eAnimation) {
2816 // For window updates that are part of an animation we must wait for
2817 // previous animation "frames" to be handled.
2818 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002819 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002820 if (CC_UNLIKELY(err != NO_ERROR)) {
2821 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002822 // caller after a few seconds.
2823 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2824 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002825 mAnimTransactionPending = false;
2826 break;
2827 }
2828 }
2829 }
2830
Mathias Agopiane57f2922012-08-09 16:29:12 -07002831 size_t count = displays.size();
2832 for (size_t i=0 ; i<count ; i++) {
2833 const DisplayState& s(displays[i]);
2834 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002835 }
2836
Mathias Agopiane57f2922012-08-09 16:29:12 -07002837 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002838 for (size_t i=0 ; i<count ; i++) {
2839 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002840 // Here we need to check that the interface we're given is indeed
2841 // one of our own. A malicious client could give us a NULL
2842 // IInterface, or one of its own or even one of our own but a
2843 // different type. All these situations would cause us to crash.
2844 //
2845 // NOTE: it would be better to use RTTI as we could directly check
2846 // that we have a Client*. however, RTTI is disabled in Android.
2847 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002848 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002849 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002850 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002851 sp<Client> client( static_cast<Client *>(s.client.get()) );
2852 transactionFlags |= setClientStateLocked(client, s.state);
2853 }
2854 }
2855 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002856 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002857
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002858 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2859 // anyway. This can be used as a flush mechanism for previous async transactions.
2860 // Empty animation transaction can be used to simulate back-pressure, so also force a
2861 // transaction for empty animation transactions.
2862 if (transactionFlags == 0 &&
2863 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002864 transactionFlags = eTransactionNeeded;
2865 }
2866
Mathias Agopian386aa982011-11-07 21:58:03 -08002867 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002868 if (mInterceptor.isEnabled()) {
2869 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2870 }
Irvel468051e2016-06-13 16:44:44 -07002871
Mathias Agopian386aa982011-11-07 21:58:03 -08002872 // this triggers the transaction
2873 setTransactionFlags(transactionFlags);
2874
2875 // if this is a synchronous transaction, wait for it to take effect
2876 // before returning.
2877 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002878 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002879 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002880 if (flags & eAnimation) {
2881 mAnimTransactionPending = true;
2882 }
2883 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002884 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2885 if (CC_UNLIKELY(err != NO_ERROR)) {
2886 // just in case something goes wrong in SF, return to the
2887 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002888 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2889 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002890 break;
2891 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002892 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893 }
2894}
2895
Mathias Agopiane57f2922012-08-09 16:29:12 -07002896uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2897{
Jesse Hall9a143922012-10-04 16:29:19 -07002898 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2899 if (dpyIdx < 0)
2900 return 0;
2901
Mathias Agopiane57f2922012-08-09 16:29:12 -07002902 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002903 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002904 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002905 const uint32_t what = s.what;
2906 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002907 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002908 disp.surface = s.surface;
2909 flags |= eDisplayTransactionNeeded;
2910 }
2911 }
2912 if (what & DisplayState::eLayerStackChanged) {
2913 if (disp.layerStack != s.layerStack) {
2914 disp.layerStack = s.layerStack;
2915 flags |= eDisplayTransactionNeeded;
2916 }
2917 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002918 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002919 if (disp.orientation != s.orientation) {
2920 disp.orientation = s.orientation;
2921 flags |= eDisplayTransactionNeeded;
2922 }
2923 if (disp.frame != s.frame) {
2924 disp.frame = s.frame;
2925 flags |= eDisplayTransactionNeeded;
2926 }
2927 if (disp.viewport != s.viewport) {
2928 disp.viewport = s.viewport;
2929 flags |= eDisplayTransactionNeeded;
2930 }
2931 }
Michael Lentine47e45402014-07-18 15:34:25 -07002932 if (what & DisplayState::eDisplaySizeChanged) {
2933 if (disp.width != s.width) {
2934 disp.width = s.width;
2935 flags |= eDisplayTransactionNeeded;
2936 }
2937 if (disp.height != s.height) {
2938 disp.height = s.height;
2939 flags |= eDisplayTransactionNeeded;
2940 }
2941 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002942 }
2943 return flags;
2944}
2945
2946uint32_t SurfaceFlinger::setClientStateLocked(
2947 const sp<Client>& client,
2948 const layer_state_t& s)
2949{
2950 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002951 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002952 if (layer != 0) {
2953 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002954 bool geometryAppliesWithResize =
2955 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002956 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002957 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002958 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002959 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002960 }
2961 if (what & layer_state_t::eLayerChanged) {
2962 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002963 const auto& p = layer->getParent();
2964 if (p == nullptr) {
2965 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2966 if (layer->setLayer(s.z) && idx >= 0) {
2967 mCurrentState.layersSortedByZ.removeAt(idx);
2968 mCurrentState.layersSortedByZ.add(layer);
2969 // we need traversal (state changed)
2970 // AND transaction (list changed)
2971 flags |= eTransactionNeeded|eTraversalNeeded;
2972 }
2973 } else {
2974 if (p->setChildLayer(layer, s.z)) {
2975 flags |= eTransactionNeeded|eTraversalNeeded;
2976 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002977 }
2978 }
Robert Carrdb66e622017-04-10 16:55:57 -07002979 if (what & layer_state_t::eRelativeLayerChanged) {
2980 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2981 flags |= eTransactionNeeded|eTraversalNeeded;
2982 }
2983 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002984 if (what & layer_state_t::eSizeChanged) {
2985 if (layer->setSize(s.w, s.h)) {
2986 flags |= eTraversalNeeded;
2987 }
2988 }
2989 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002990 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 flags |= eTraversalNeeded;
2992 }
2993 if (what & layer_state_t::eMatrixChanged) {
2994 if (layer->setMatrix(s.matrix))
2995 flags |= eTraversalNeeded;
2996 }
2997 if (what & layer_state_t::eTransparentRegionChanged) {
2998 if (layer->setTransparentRegionHint(s.transparentRegion))
2999 flags |= eTraversalNeeded;
3000 }
Dan Stoza23116082015-06-18 14:58:39 -07003001 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 if (layer->setFlags(s.flags, s.mask))
3003 flags |= eTraversalNeeded;
3004 }
3005 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003006 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003007 flags |= eTraversalNeeded;
3008 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003009 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003010 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003011 flags |= eTraversalNeeded;
3012 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003013 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003014 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003015 // We only allow setting layer stacks for top level layers,
3016 // everything else inherits layer stack from its parent.
3017 if (layer->hasParent()) {
3018 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3019 layer->getName().string());
3020 } else if (idx < 0) {
3021 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3022 "that also does not appear in the top level layer list. Something"
3023 " has gone wrong.", layer->getName().string());
3024 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003025 mCurrentState.layersSortedByZ.removeAt(idx);
3026 mCurrentState.layersSortedByZ.add(layer);
3027 // we need traversal (state changed)
3028 // AND transaction (list changed)
3029 flags |= eTransactionNeeded|eTraversalNeeded;
3030 }
3031 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003032 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003033 if (s.barrierHandle != nullptr) {
3034 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3035 } else if (s.barrierGbp != nullptr) {
3036 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3037 if (authenticateSurfaceTextureLocked(gbp)) {
3038 const auto& otherLayer =
3039 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3040 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3041 } else {
3042 ALOGE("Attempt to defer transaction to to an"
3043 " unrecognized GraphicBufferProducer");
3044 }
3045 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003046 // We don't trigger a traversal here because if no other state is
3047 // changed, we don't want this to cause any more work
3048 }
Robert Carr1db73f62016-12-21 12:58:51 -08003049 if (what & layer_state_t::eReparentChildren) {
3050 if (layer->reparentChildren(s.reparentHandle)) {
3051 flags |= eTransactionNeeded|eTraversalNeeded;
3052 }
3053 }
Robert Carr9524cb32017-02-13 11:32:32 -08003054 if (what & layer_state_t::eDetachChildren) {
3055 layer->detachChildren();
3056 }
Robert Carrc3574f72016-03-24 12:19:32 -07003057 if (what & layer_state_t::eOverrideScalingModeChanged) {
3058 layer->setOverrideScalingMode(s.overrideScalingMode);
3059 // We don't trigger a traversal here because if no other state is
3060 // changed, we don't want this to cause any more work
3061 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003062 }
3063 return flags;
3064}
3065
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003066status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003067 const String8& name,
3068 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003069 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003070 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3071 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003072{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003073 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003074 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003075 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003076 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003077 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003078
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003079 status_t result = NO_ERROR;
3080
3081 sp<Layer> layer;
3082
Cody Northropbc755282017-03-31 12:00:08 -06003083 String8 uniqueName = getUniqueLayerName(name);
3084
Mathias Agopian3165cc22012-08-08 19:42:09 -07003085 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3086 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003087 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003088 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003089 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003091 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003092 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003093 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003094 handle, gbp, &layer);
3095 break;
3096 default:
3097 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 break;
3099 }
3100
Dan Stoza7d89d062015-04-30 13:29:25 -07003101 if (result != NO_ERROR) {
3102 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003104
Chia-I Wuab0c3192017-08-01 11:29:00 -07003105 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3106 // TODO b/64227542
3107 if (windowType == 441731) {
3108 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3109 layer->setPrimaryDisplayOnly();
3110 }
3111
Albert Chaulk479c60c2017-01-27 14:21:34 -05003112 layer->setInfo(windowType, ownerUid);
3113
Robert Carr1f0a16a2016-10-24 16:27:39 -07003114 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003115 if (result != NO_ERROR) {
3116 return result;
3117 }
Irvelffc9efc2016-07-27 15:16:37 -07003118 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003119
3120 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003121 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003122}
3123
Cody Northropbc755282017-03-31 12:00:08 -06003124String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3125{
3126 bool matchFound = true;
3127 uint32_t dupeCounter = 0;
3128
3129 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3130 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3131
3132 // Loop over layers until we're sure there is no matching name
3133 while (matchFound) {
3134 matchFound = false;
3135 mDrawingState.traverseInZOrder([&](Layer* layer) {
3136 if (layer->getName() == uniqueName) {
3137 matchFound = true;
3138 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3139 }
3140 });
3141 }
3142
3143 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3144
3145 return uniqueName;
3146}
3147
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003148status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3149 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3150 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151{
3152 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003153 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 case PIXEL_FORMAT_TRANSPARENT:
3155 case PIXEL_FORMAT_TRANSLUCENT:
3156 format = PIXEL_FORMAT_RGBA_8888;
3157 break;
3158 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003159 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 break;
3161 }
3162
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003163 *outLayer = new Layer(this, client, name, w, h, flags);
3164 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3165 if (err == NO_ERROR) {
3166 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003167 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003169
3170 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3171 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172}
3173
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003174status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3175 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3176 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003178 *outLayer = new LayerDim(this, client, name, w, h, flags);
3179 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003180 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003181 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003182}
3183
Mathias Agopianac9fa422013-02-11 16:40:36 -08003184status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185{
Robert Carr9524cb32017-02-13 11:32:32 -08003186 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003187 status_t err = NO_ERROR;
3188 sp<Layer> l(client->getLayerUser(handle));
3189 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003190 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003191 err = removeLayer(l);
3192 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3193 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003194 }
3195 return err;
3196}
3197
Mathias Agopian13127d82013-03-05 17:47:11 -08003198status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003199{
Mathias Agopian67106042013-03-14 19:18:13 -07003200 // called by ~LayerCleaner() when all references to the IBinder (handle)
3201 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003202 sp<Layer> l = layer.promote();
3203 if (l == nullptr) {
3204 // The layer has already been removed, carry on
3205 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003206 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003207 // If we have a parent, then we can continue to live as long as it does.
3208 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209}
3210
Mathias Agopianb60314a2012-04-10 22:09:54 -07003211// ---------------------------------------------------------------------------
3212
Andy McFadden13a082e2012-08-24 10:16:42 -07003213void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003214 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003215 Vector<ComposerState> state;
3216 Vector<DisplayState> displays;
3217 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003218 d.what = DisplayState::eDisplayProjectionChanged |
3219 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003220 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003221 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003222 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003223 d.frame.makeInvalid();
3224 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003225 d.width = 0;
3226 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003227 displays.add(d);
3228 setTransactionState(state, displays, 0);
Steven Thomasd7f49c52017-07-26 18:48:28 -07003229 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3230 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003231
Dan Stoza9e56aa02015-11-02 13:00:03 -08003232 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3233 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003234 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003235
Brian Andersond0010582017-03-07 13:20:31 -08003236 // Use phase of 0 since phase is not known.
3237 // Use latency of 0, which will snap to the ideal latency.
3238 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003239}
3240
3241void SurfaceFlinger::initializeDisplays() {
3242 class MessageScreenInitialized : public MessageBase {
3243 SurfaceFlinger* flinger;
3244 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003245 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003246 virtual bool handler() {
3247 flinger->onInitializeDisplays();
3248 return true;
3249 }
3250 };
3251 sp<MessageBase> msg = new MessageScreenInitialized(this);
3252 postMessageAsync(msg); // we may be called from main thread, use async message
3253}
3254
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003255void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasd7f49c52017-07-26 18:48:28 -07003256 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003257 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3258 this);
3259 int32_t type = hw->getDisplayType();
3260 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003261
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003262 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003263 return;
3264 }
3265
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003266 hw->setPowerMode(mode);
3267 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3268 ALOGW("Trying to set power mode for virtual display");
3269 return;
3270 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003271
Irvelffc9efc2016-07-27 15:16:37 -07003272 if (mInterceptor.isEnabled()) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003273 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003274 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3275 if (idx < 0) {
3276 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3277 return;
3278 }
3279 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3280 }
3281
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003282 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003283 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003284 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003285 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3286 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003287 // FIXME: eventthread only knows about the main display right now
3288 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003289 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003290 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003292 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003293 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003294 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003295
3296 struct sched_param param = {0};
3297 param.sched_priority = 1;
3298 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3299 ALOGW("Couldn't set SCHED_FIFO on display on");
3300 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003301 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003302 // Turn off the display
3303 struct sched_param param = {0};
3304 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3305 ALOGW("Couldn't set SCHED_OTHER on display off");
3306 }
3307
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003308 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003309 disableHardwareVsync(true); // also cancels any in-progress resync
3310
Mathias Agopiancde87a32012-09-13 14:09:01 -07003311 // FIXME: eventthread only knows about the main display right now
3312 mEventThread->onScreenReleased();
3313 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003314
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003315 getHwComposer().setPowerMode(type, mode);
3316 mVisibleRegionsDirty = true;
3317 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003318 } else if (mode == HWC_POWER_MODE_DOZE ||
3319 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003320 // Update display while dozing
3321 getHwComposer().setPowerMode(type, mode);
3322 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3323 // FIXME: eventthread only knows about the main display right now
3324 mEventThread->onScreenAcquired();
3325 resyncToHardwareVsync(true);
3326 }
3327 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3328 // Leave display going to doze
3329 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3330 disableHardwareVsync(true); // also cancels any in-progress resync
3331 // FIXME: eventthread only knows about the main display right now
3332 mEventThread->onScreenReleased();
3333 }
3334 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003335 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003336 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003337 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003338 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003339}
3340
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003341void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3342 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003343 SurfaceFlinger& mFlinger;
3344 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003345 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003346 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003347 MessageSetPowerMode(SurfaceFlinger& flinger,
3348 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3349 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003350 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003351 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003352 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003354 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003355 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003356 ALOGW("Attempt to set power mode = %d for virtual display",
3357 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003358 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003359 mFlinger.setPowerModeInternal(
3360 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003361 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003362 return true;
3363 }
3364 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003365 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003366 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003367}
3368
3369// ---------------------------------------------------------------------------
3370
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003371status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3372{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003373 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003374
Mathias Agopianbd115332013-04-18 16:41:04 -07003375 IPCThreadState* ipc = IPCThreadState::self();
3376 const int pid = ipc->getCallingPid();
3377 const int uid = ipc->getCallingUid();
3378 if ((uid != AID_SHELL) &&
3379 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003380 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003381 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003383 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003384 // (this would indicate SF is stuck, but we want to be able to
3385 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003386 status_t err = mStateLock.timedLock(s2ns(1));
3387 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003388 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003389 result.appendFormat(
3390 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3391 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003392 }
3393
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003394 bool dumpAll = true;
3395 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003396 size_t numArgs = args.size();
3397 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003398 if ((index < numArgs) &&
3399 (args[index] == String16("--list"))) {
3400 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003401 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003402 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003403 }
3404
3405 if ((index < numArgs) &&
3406 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003407 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003408 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003409 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003410 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003411
3412 if ((index < numArgs) &&
3413 (args[index] == String16("--latency-clear"))) {
3414 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003415 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003416 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003417 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003418
3419 if ((index < numArgs) &&
3420 (args[index] == String16("--dispsync"))) {
3421 index++;
3422 mPrimaryDispSync.dump(result);
3423 dumpAll = false;
3424 }
Dan Stozab90cf072015-03-05 11:05:59 -08003425
3426 if ((index < numArgs) &&
3427 (args[index] == String16("--static-screen"))) {
3428 index++;
3429 dumpStaticScreenStats(result);
3430 dumpAll = false;
3431 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003432
3433 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003434 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003435 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003436 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003437 dumpAll = false;
3438 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003439
3440 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3441 index++;
3442 dumpWideColorInfo(result);
3443 dumpAll = false;
3444 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003445 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003446
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003447 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003448 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003449 }
3450
Mathias Agopian9795c422009-08-26 16:36:26 -07003451 if (locked) {
3452 mStateLock.unlock();
3453 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003454 }
3455 write(fd, result.string(), result.size());
3456 return NO_ERROR;
3457}
3458
Dan Stozac7014012014-02-14 15:03:43 -08003459void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3460 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003461{
Robert Carr2047fae2016-11-28 14:09:09 -08003462 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003463 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003464 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003465}
3466
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003467void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003468 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003469{
3470 String8 name;
3471 if (index < args.size()) {
3472 name = String8(args[index]);
3473 index++;
3474 }
3475
Dan Stoza9e56aa02015-11-02 13:00:03 -08003476 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3477 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003478 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003479
3480 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003481 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003482 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003483 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003484 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003485 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003486 }
Robert Carr2047fae2016-11-28 14:09:09 -08003487 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003488 }
3489}
3490
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003491void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003492 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003493{
3494 String8 name;
3495 if (index < args.size()) {
3496 name = String8(args[index]);
3497 index++;
3498 }
3499
Robert Carr2047fae2016-11-28 14:09:09 -08003500 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003501 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003502 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003503 }
Robert Carr2047fae2016-11-28 14:09:09 -08003504 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003505
Svetoslavd85084b2014-03-20 10:28:31 -07003506 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003507}
3508
Jamie Gennis6547ff42013-07-16 20:12:42 -07003509// This should only be called from the main thread. Otherwise it would need
3510// the lock and should use mCurrentState rather than mDrawingState.
3511void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003512 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003513 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003514 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003515
3516 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3517}
3518
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003519void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003520{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003521 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003522 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3523
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003524 if (isLayerTripleBufferingDisabled())
3525 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003526
3527 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003528 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003529 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003530 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003531 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3532 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003533 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003534}
3535
Dan Stozab90cf072015-03-05 11:05:59 -08003536void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3537{
3538 result.appendFormat("Static screen stats:\n");
3539 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3540 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3541 float percent = 100.0f *
3542 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3543 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3544 b + 1, bucketTimeSec, percent);
3545 }
3546 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3547 float percent = 100.0f *
3548 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3549 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3550 NUM_BUCKETS - 1, bucketTimeSec, percent);
3551}
3552
Dan Stozae77c7662016-05-13 11:37:28 -07003553void SurfaceFlinger::recordBufferingStats(const char* layerName,
3554 std::vector<OccupancyTracker::Segment>&& history) {
3555 Mutex::Autolock lock(mBufferingStatsMutex);
3556 auto& stats = mBufferingStats[layerName];
3557 for (const auto& segment : history) {
3558 if (!segment.usedThirdBuffer) {
3559 stats.twoBufferTime += segment.totalTime;
3560 }
3561 if (segment.occupancyAverage < 1.0f) {
3562 stats.doubleBufferedTime += segment.totalTime;
3563 } else if (segment.occupancyAverage < 2.0f) {
3564 stats.tripleBufferedTime += segment.totalTime;
3565 }
3566 ++stats.numSegments;
3567 stats.totalTime += segment.totalTime;
3568 }
3569}
3570
Brian Andersond6927fb2016-07-23 23:37:30 -07003571void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3572 result.appendFormat("Layer frame timestamps:\n");
3573
3574 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3575 const size_t count = currentLayers.size();
3576 for (size_t i=0 ; i<count ; i++) {
3577 currentLayers[i]->dumpFrameEvents(result);
3578 }
3579}
3580
Dan Stozae77c7662016-05-13 11:37:28 -07003581void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3582 result.append("Buffering stats:\n");
3583 result.append(" [Layer name] <Active time> <Two buffer> "
3584 "<Double buffered> <Triple buffered>\n");
3585 Mutex::Autolock lock(mBufferingStatsMutex);
3586 typedef std::tuple<std::string, float, float, float> BufferTuple;
3587 std::map<float, BufferTuple, std::greater<float>> sorted;
3588 for (const auto& statsPair : mBufferingStats) {
3589 const char* name = statsPair.first.c_str();
3590 const BufferingStats& stats = statsPair.second;
3591 if (stats.numSegments == 0) {
3592 continue;
3593 }
3594 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3595 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3596 stats.totalTime;
3597 float doubleBufferRatio = static_cast<float>(
3598 stats.doubleBufferedTime) / stats.totalTime;
3599 float tripleBufferRatio = static_cast<float>(
3600 stats.tripleBufferedTime) / stats.totalTime;
3601 sorted.insert({activeTime, {name, twoBufferRatio,
3602 doubleBufferRatio, tripleBufferRatio}});
3603 }
3604 for (const auto& sortedPair : sorted) {
3605 float activeTime = sortedPair.first;
3606 const BufferTuple& values = sortedPair.second;
3607 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3608 std::get<0>(values).c_str(), activeTime,
3609 std::get<1>(values), std::get<2>(values),
3610 std::get<3>(values));
3611 }
3612 result.append("\n");
3613}
3614
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003615void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3616 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3617
3618 // TODO: print out if wide-color mode is active or not
3619
3620 for (size_t d = 0; d < mDisplays.size(); d++) {
3621 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3622 int32_t hwcId = displayDevice->getHwcDisplayId();
3623 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3624 continue;
3625 }
3626
3627 result.appendFormat("Display %d color modes:\n", hwcId);
3628 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3629 for (auto&& mode : modes) {
3630 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3631 }
3632
3633 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3634 result.appendFormat(" Current color mode: %s (%d)\n",
3635 decodeColorMode(currentMode).c_str(), currentMode);
3636 }
3637 result.append("\n");
3638}
3639
Mathias Agopian74d211a2013-04-22 16:55:35 +02003640void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3641 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003642{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003643 bool colorize = false;
3644 if (index < args.size()
3645 && (args[index] == String16("--color"))) {
3646 colorize = true;
3647 index++;
3648 }
3649
3650 Colorizer colorizer(colorize);
3651
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003652 // figure out if we're stuck somewhere
3653 const nsecs_t now = systemTime();
3654 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3655 const nsecs_t inTransaction(mDebugInTransaction);
3656 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3657 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3658
3659 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003660 * Dump library configuration.
3661 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003662
3663 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003664 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003665 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003666 appendSfConfigString(result);
3667 appendUiConfigString(result);
3668 appendGuiConfigString(result);
3669 result.append("\n");
3670
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003671 result.append("\nWide-Color information:\n");
3672 dumpWideColorInfo(result);
3673
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003674 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003675 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003676 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003677 result.append(SyncFeatures::getInstance().toString());
3678 result.append("\n");
3679
Dan Stoza9e56aa02015-11-02 13:00:03 -08003680 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3681
Andy McFadden41d67d72014-04-25 16:58:34 -07003682 colorizer.bold(result);
3683 result.append("DispSync configuration: ");
3684 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003685 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003686 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003687 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003688 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003689 result.append("\n");
3690
Dan Stozab90cf072015-03-05 11:05:59 -08003691 // Dump static screen stats
3692 result.append("\n");
3693 dumpStaticScreenStats(result);
3694 result.append("\n");
3695
Dan Stozae77c7662016-05-13 11:37:28 -07003696 dumpBufferingStats(result);
3697
Andy McFadden4803b742012-09-24 19:07:20 -07003698 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003699 * Dump the visible layer list
3700 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003701 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003702 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003703 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003704 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003705 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003706 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003707
3708 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003709 * Dump Display state
3710 */
3711
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003712 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003713 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003714 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003715 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3716 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003717 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003718 }
3719
3720 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003721 * Dump SurfaceFlinger global state
3722 */
3723
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003724 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003725 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003726 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003727
Mathias Agopian888c8222012-08-04 21:10:38 -07003728 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003729 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003730
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003731 colorizer.bold(result);
3732 result.appendFormat("EGL implementation : %s\n",
3733 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3734 colorizer.reset(result);
3735 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003736 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003737
Mathias Agopian875d8e12013-06-07 15:35:48 -07003738 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739
Mathias Agopian42977342012-08-05 00:40:46 -07003740 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003741 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3742 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003743 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003744 " last eglSwapBuffers() time: %f us\n"
3745 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003746 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003747 " refresh-rate : %f fps\n"
3748 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003749 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003750 " gpu_to_cpu_unsupported : %d\n"
3751 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752 mLastSwapBufferTime/1000.0,
3753 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003754 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003755 1e9 / activeConfig->getVsyncPeriod(),
3756 activeConfig->getDpiX(),
3757 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003758 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003759
Mathias Agopian74d211a2013-04-22 16:55:35 +02003760 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003761 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003762
Mathias Agopian74d211a2013-04-22 16:55:35 +02003763 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003764 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003765
3766 /*
3767 * VSYNC state
3768 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003769 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003770 result.append("\n");
3771
3772 /*
3773 * HWC layer minidump
3774 */
3775 for (size_t d = 0; d < mDisplays.size(); d++) {
3776 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3777 int32_t hwcId = displayDevice->getHwcDisplayId();
3778 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3779 continue;
3780 }
3781
3782 result.appendFormat("Display %d HWC layers:\n", hwcId);
3783 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003784 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003785 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003786 });
Dan Stozae22aec72016-08-01 13:20:59 -07003787 result.append("\n");
3788 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003789
3790 /*
3791 * Dump HWComposer state
3792 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003793 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003794 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003795 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003796 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003797 result.appendFormat(" h/w composer %s\n",
3798 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003799 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003800
3801 /*
3802 * Dump gralloc state
3803 */
3804 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3805 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003806
3807 /*
3808 * Dump VrFlinger state if in use.
3809 */
3810 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3811 result.append("VrFlinger state:\n");
3812 result.append(mVrFlinger->Dump().c_str());
3813 result.append("\n");
3814 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003815}
3816
Mathias Agopian13127d82013-03-05 17:47:11 -08003817const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003818SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003819 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003820 wp<IBinder> dpy;
3821 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3822 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3823 dpy = mDisplays.keyAt(i);
3824 break;
3825 }
3826 }
3827 if (dpy == NULL) {
3828 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3829 // Just use the primary display so we have something to return
3830 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3831 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003832 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003833}
3834
Keun young Park63f165f2012-08-31 10:53:36 -07003835bool SurfaceFlinger::startDdmConnection()
3836{
3837 void* libddmconnection_dso =
3838 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3839 if (!libddmconnection_dso) {
3840 return false;
3841 }
3842 void (*DdmConnection_start)(const char* name);
3843 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003844 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003845 if (!DdmConnection_start) {
3846 dlclose(libddmconnection_dso);
3847 return false;
3848 }
3849 (*DdmConnection_start)(getServiceName());
3850 return true;
3851}
3852
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003853status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854 switch (code) {
3855 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003856 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003858 case CLEAR_ANIMATION_FRAME_STATS:
3859 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003860 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003861 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003862 {
3863 // codes that require permission check
3864 IPCThreadState* ipc = IPCThreadState::self();
3865 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003866 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003867 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003868 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003869 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003870 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003871 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003872 break;
3873 }
Robert Carr1db73f62016-12-21 12:58:51 -08003874 /*
3875 * Calling setTransactionState is safe, because you need to have been
3876 * granted a reference to Client* and Handle* to do anything with it.
3877 *
3878 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3879 */
3880 case SET_TRANSACTION_STATE:
3881 case CREATE_SCOPED_CONNECTION:
3882 {
3883 return OK;
3884 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003885 case CAPTURE_SCREEN:
3886 {
3887 // codes that require permission check
3888 IPCThreadState* ipc = IPCThreadState::self();
3889 const int pid = ipc->getCallingPid();
3890 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003891 if ((uid != AID_GRAPHICS) &&
3892 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003893 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003894 return PERMISSION_DENIED;
3895 }
3896 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897 }
3898 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003899 return OK;
3900}
3901
3902status_t SurfaceFlinger::onTransact(
3903 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3904{
3905 status_t credentialCheck = CheckTransactCodeCredentials(code);
3906 if (credentialCheck != OK) {
3907 return credentialCheck;
3908 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003909
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3911 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003912 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003913 IPCThreadState* ipc = IPCThreadState::self();
3914 const int uid = ipc->getCallingUid();
3915 if (CC_UNLIKELY(uid != AID_SYSTEM
3916 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003917 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003918 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003919 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003920 return PERMISSION_DENIED;
3921 }
3922 int n;
3923 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003924 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003925 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 return NO_ERROR;
3927 case 1002: // SHOW_UPDATES
3928 n = data.readInt32();
3929 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003930 invalidateHwcGeometry();
3931 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003933 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003934 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003935 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003936 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003937 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003938 setTransactionFlags(
3939 eTransactionNeeded|
3940 eDisplayTransactionNeeded|
3941 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003942 return NO_ERROR;
3943 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003944 case 1006:{ // send empty update
3945 signalRefresh();
3946 return NO_ERROR;
3947 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003948 case 1008: // toggle use of hw composer
3949 n = data.readInt32();
3950 mDebugDisableHWC = n ? 1 : 0;
3951 invalidateHwcGeometry();
3952 repaintEverything();
3953 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003954 case 1009: // toggle use of transform hint
3955 n = data.readInt32();
3956 mDebugDisableTransformHint = n ? 1 : 0;
3957 invalidateHwcGeometry();
3958 repaintEverything();
3959 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003960 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003961 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 reply->writeInt32(0);
3963 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003964 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003965 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003966 return NO_ERROR;
3967 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003968 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003969 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003970 return NO_ERROR;
3971 }
3972 case 1014: {
3973 // daltonize
3974 n = data.readInt32();
3975 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003976 case 1:
3977 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3978 break;
3979 case 2:
3980 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3981 break;
3982 case 3:
3983 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3984 break;
3985 default:
3986 mDaltonizer.setType(ColorBlindnessType::None);
3987 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003988 }
3989 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003990 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003991 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003992 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003993 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003994 invalidateHwcGeometry();
3995 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003996 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003997 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003998 case 1015: {
3999 // apply a color matrix
4000 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004001 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004002 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004003 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004004 for (size_t j = 0; j < 4; j++) {
4005 mColorMatrix[i][j] = data.readFloat();
4006 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004007 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004008 } else {
4009 mColorMatrix = mat4();
4010 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004011
4012 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4013 // the division by w in the fragment shader
4014 float4 lastRow(transpose(mColorMatrix)[3]);
4015 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4016 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4017 }
4018
Alan Viverette9c5a3332013-09-12 20:04:35 -07004019 invalidateHwcGeometry();
4020 repaintEverything();
4021 return NO_ERROR;
4022 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004023 // This is an experimental interface
4024 // Needs to be shifted to proper binder interface when we productize
4025 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004026 n = data.readInt32();
4027 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004028 return NO_ERROR;
4029 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004030 case 1017: {
4031 n = data.readInt32();
4032 mForceFullDamage = static_cast<bool>(n);
4033 return NO_ERROR;
4034 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004035 case 1018: { // Modify Choreographer's phase offset
4036 n = data.readInt32();
4037 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4038 return NO_ERROR;
4039 }
4040 case 1019: { // Modify SurfaceFlinger's phase offset
4041 n = data.readInt32();
4042 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4043 return NO_ERROR;
4044 }
Irvel468051e2016-06-13 16:44:44 -07004045 case 1020: { // Layer updates interceptor
4046 n = data.readInt32();
4047 if (n) {
4048 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004049 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004050 }
4051 else{
4052 ALOGV("Interceptor disabled");
4053 mInterceptor.disable();
4054 }
4055 return NO_ERROR;
4056 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004057 case 1021: { // Disable HWC virtual displays
4058 n = data.readInt32();
4059 mUseHwcVirtualDisplays = !n;
4060 return NO_ERROR;
4061 }
Romain Guy0147a172017-06-01 13:53:56 -07004062 case 1022: { // Set saturation boost
4063 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4064
4065 invalidateHwcGeometry();
4066 repaintEverything();
4067 return NO_ERROR;
4068 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004069 }
4070 }
4071 return err;
4072}
4073
Mathias Agopian53331da2011-08-22 21:44:41 -07004074void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004075 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004076 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004077}
4078
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004079// Checks that the requested width and height are valid and updates them to the display dimensions
4080// if they are set to 0
4081static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4082 Transform::orientation_flags rotation,
4083 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4084 // get screen geometry
4085 uint32_t displayWidth = displayDevice->getWidth();
4086 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004087
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004088 if (rotation & Transform::ROT_90) {
4089 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004090 }
4091
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004092 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4093 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4094 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4095 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004096 }
4097
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004098 if (*requestedWidth == 0) {
4099 *requestedWidth = displayWidth;
4100 }
4101 if (*requestedHeight == 0) {
4102 *requestedHeight = displayHeight;
4103 }
4104
4105 return NO_ERROR;
4106}
4107
4108// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4109class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004110public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004111 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4112 ~WindowDisconnector() {
4113 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004114 }
4115
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004116private:
4117 ANativeWindow* mWindow;
4118 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004119};
4120
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004121static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4122 uint32_t requestedHeight, bool hasWideColorDisplay,
4123 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4124 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4125 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4126
4127 int err = 0;
4128 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4129 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4130 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4131 err |= native_window_set_usage(window, usage);
4132
4133 if (hasWideColorDisplay) {
4134 err |= native_window_set_buffers_data_space(window,
4135 renderEngineUsesWideColor
4136 ? HAL_DATASPACE_DISPLAY_P3
4137 : HAL_DATASPACE_V0_SRGB);
4138 }
4139
4140 if (err != NO_ERROR) {
4141 return BAD_VALUE;
4142 }
4143
4144 /* TODO: Once we have the sync framework everywhere this can use
4145 * server-side waits on the fence that dequeueBuffer returns.
4146 */
4147 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4148 if (err != NO_ERROR) {
4149 return err;
4150 }
4151
4152 return NO_ERROR;
4153}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004154
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004155status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4156 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004157 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004158 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004159 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004160 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004161
4162 if (CC_UNLIKELY(display == 0))
4163 return BAD_VALUE;
4164
4165 if (CC_UNLIKELY(producer == 0))
4166 return BAD_VALUE;
4167
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004168 // if we have secure windows on this display, never allow the screen capture
4169 // unless the producer interface is local (i.e.: we can take a screenshot for
4170 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004171 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004172
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004173 // Convert to surfaceflinger's internal rotation type.
4174 Transform::orientation_flags rotationFlags;
4175 switch (rotation) {
4176 case ISurfaceComposer::eRotateNone:
4177 rotationFlags = Transform::ROT_0;
4178 break;
4179 case ISurfaceComposer::eRotate90:
4180 rotationFlags = Transform::ROT_90;
4181 break;
4182 case ISurfaceComposer::eRotate180:
4183 rotationFlags = Transform::ROT_180;
4184 break;
4185 case ISurfaceComposer::eRotate270:
4186 rotationFlags = Transform::ROT_270;
4187 break;
4188 default:
4189 rotationFlags = Transform::ROT_0;
4190 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4191 break;
4192 }
4193
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004194 { // Autolock scope
4195 Mutex::Autolock lock(mStateLock);
4196 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4197 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004198 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004199
4200 // create a surface (because we're a producer, and we need to
4201 // dequeue/queue a buffer)
4202 sp<Surface> surface = new Surface(producer, false);
4203
4204 // Put the screenshot Surface into async mode so that
4205 // Layer::headFenceHasSignaled will always return true and we'll latch the
4206 // first buffer regardless of whether or not its acquire fence has
4207 // signaled. This is needed to avoid a race condition in the rotation
4208 // animation. See b/30209608
4209 surface->setAsyncMode(true);
4210
4211 ANativeWindow* window = surface.get();
4212
4213 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4214 if (result != NO_ERROR) {
4215 return result;
4216 }
4217 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4218
4219 ANativeWindowBuffer* buffer = nullptr;
4220 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4221 getRenderEngine().usesWideColor(), &buffer);
4222 if (result != NO_ERROR) {
4223 return result;
4224 }
4225
4226 // This mutex protects syncFd and captureResult for communication of the return values from the
4227 // main thread back to this Binder thread
4228 std::mutex captureMutex;
4229 std::condition_variable captureCondition;
4230 std::unique_lock<std::mutex> captureLock(captureMutex);
4231 int syncFd = -1;
4232 std::optional<status_t> captureResult;
4233
4234 sp<LambdaMessage> message = new LambdaMessage([&]() {
4235 // If there is a refresh pending, bug out early and tell the binder thread to try again
4236 // after the refresh.
4237 if (mRefreshPending) {
4238 ATRACE_NAME("Skipping screenshot for now");
4239 std::unique_lock<std::mutex> captureLock(captureMutex);
4240 captureResult = std::make_optional<status_t>(EAGAIN);
4241 captureCondition.notify_one();
4242 return;
4243 }
4244
4245 status_t result = NO_ERROR;
4246 int fd = -1;
4247 {
4248 Mutex::Autolock _l(mStateLock);
4249 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4250 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4251 minLayerZ, maxLayerZ, useIdentityTransform,
4252 rotationFlags, isLocalScreenshot, &fd);
4253 }
4254
4255 {
4256 std::unique_lock<std::mutex> captureLock(captureMutex);
4257 syncFd = fd;
4258 captureResult = std::make_optional<status_t>(result);
4259 captureCondition.notify_one();
4260 }
4261 });
4262
4263 result = postMessageAsync(message);
4264 if (result == NO_ERROR) {
4265 captureCondition.wait(captureLock, [&]() { return captureResult; });
4266 while (*captureResult == EAGAIN) {
4267 captureResult.reset();
4268 result = postMessageAsync(message);
4269 if (result != NO_ERROR) {
4270 return result;
4271 }
4272 captureCondition.wait(captureLock, [&]() { return captureResult; });
4273 }
4274 result = *captureResult;
4275 }
4276
4277 if (result == NO_ERROR) {
4278 // queueBuffer takes ownership of syncFd
4279 result = window->queueBuffer(window, buffer, syncFd);
4280 }
4281
4282 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004283}
4284
Mathias Agopian180f10d2013-04-10 22:55:41 -07004285
4286void SurfaceFlinger::renderScreenImplLocked(
4287 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004288 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004289 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004290 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004291{
4292 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004293 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004294
4295 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004296 const int32_t hw_w = hw->getWidth();
4297 const int32_t hw_h = hw->getHeight();
4298 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004299 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004300
Dan Stozac1879002014-05-22 15:59:05 -07004301 // if a default or invalid sourceCrop is passed in, set reasonable values
4302 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4303 !sourceCrop.isValid()) {
4304 sourceCrop.setLeftTop(Point(0, 0));
4305 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4306 }
4307
4308 // ensure that sourceCrop is inside screen
4309 if (sourceCrop.left < 0) {
4310 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4311 }
Dan Stozabe31f442014-06-11 11:20:54 -07004312 if (sourceCrop.right > hw_w) {
4313 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004314 }
4315 if (sourceCrop.top < 0) {
4316 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4317 }
Dan Stozabe31f442014-06-11 11:20:54 -07004318 if (sourceCrop.bottom > hw_h) {
4319 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004320 }
4321
Romain Guy88d37dd2017-05-26 17:57:05 -07004322#ifdef USE_HWC2
4323 engine.setWideColor(hw->getWideColorSupport());
4324 engine.setColorMode(hw->getActiveColorMode());
4325#endif
4326
Mathias Agopian180f10d2013-04-10 22:55:41 -07004327 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004328 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004329
4330 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004331 engine.setViewportAndProjection(
4332 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004333 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004334
4335 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004336 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004337
Robert Carr1f0a16a2016-10-24 16:27:39 -07004338 // We loop through the first level of layers without traversing,
4339 // as we need to interpret min/max layer Z in the top level Z space.
4340 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004341 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004342 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004343 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004344 const Layer::State& state(layer->getDrawingState());
4345 if (state.z < minLayerZ || state.z > maxLayerZ) {
4346 continue;
4347 }
Dan Stoza412903f2017-04-27 13:42:17 -07004348 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004349 if (!layer->isVisible()) {
4350 return;
4351 }
4352 if (filtering) layer->setFiltering(true);
4353 layer->draw(hw, useIdentityTransform);
4354 if (filtering) layer->setFiltering(false);
4355 });
4356 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004357
Mathias Agopian931bda12013-08-28 18:11:46 -07004358 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004359}
4360
Dan Stozaabcda352017-06-01 14:37:39 -07004361// A simple RAII class that holds an EGLImage and destroys it either:
4362// a) When the destroy() method is called
4363// b) When the object goes out of scope
4364class ImageHolder {
4365public:
4366 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4367 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004368
Dan Stozaabcda352017-06-01 14:37:39 -07004369 void destroy() {
4370 if (mImage != EGL_NO_IMAGE_KHR) {
4371 eglDestroyImageKHR(mDisplay, mImage);
4372 mImage = EGL_NO_IMAGE_KHR;
4373 }
4374 }
4375
4376private:
4377 const EGLDisplay mDisplay;
4378 EGLImageKHR mImage;
4379};
4380
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004381status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4382 ANativeWindowBuffer* buffer, Rect sourceCrop,
4383 uint32_t reqWidth, uint32_t reqHeight,
4384 int32_t minLayerZ, int32_t maxLayerZ,
4385 bool useIdentityTransform,
4386 Transform::orientation_flags rotation,
4387 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004388 ATRACE_CALL();
4389
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004390 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004391 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004392 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004393 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004394 (state.z < minLayerZ || state.z > maxLayerZ)) {
4395 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004396 }
Dan Stoza412903f2017-04-27 13:42:17 -07004397 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004398 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4399 layer->isSecure());
4400 });
4401 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004402
4403 if (!isLocalScreenshot && secureLayerIsVisible) {
4404 ALOGW("FB is protected: PERMISSION_DENIED");
4405 return PERMISSION_DENIED;
4406 }
4407
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004408 int syncFd = -1;
4409 // create an EGLImage from the buffer so we can later
4410 // turn it into a texture
4411 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4412 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4413 if (image == EGL_NO_IMAGE_KHR) {
4414 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004415 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004416
Dan Stozaabcda352017-06-01 14:37:39 -07004417 // This will automatically destroy the image if we return before calling its destroy method
4418 ImageHolder imageHolder(mEGLDisplay, image);
4419
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004420 // this binds the given EGLImage as a framebuffer for the
4421 // duration of this scope.
4422 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004423 if (imageBond.getStatus() != NO_ERROR) {
4424 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004425 return INVALID_OPERATION;
4426 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004427
Dan Stozaabcda352017-06-01 14:37:39 -07004428 // this will in fact render into our dequeued buffer
4429 // via an FBO, which means we didn't have to create
4430 // an EGLSurface and therefore we're not
4431 // dependent on the context's EGLConfig.
4432 renderScreenImplLocked(
4433 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4434 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004435
Dan Stozaabcda352017-06-01 14:37:39 -07004436 // Attempt to create a sync khr object that can produce a sync point. If that
4437 // isn't available, create a non-dupable sync object in the fallback path and
4438 // wait on it directly.
4439 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4440 if (!DEBUG_SCREENSHOTS) {
4441 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4442 // native fence fd will not be populated until flush() is done.
4443 getRenderEngine().flush();
4444 }
4445
4446 if (sync != EGL_NO_SYNC_KHR) {
4447 // get the sync fd
4448 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4449 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4450 ALOGW("captureScreen: failed to dup sync khr object");
4451 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004452 }
Dan Stozaabcda352017-06-01 14:37:39 -07004453 eglDestroySyncKHR(mEGLDisplay, sync);
4454 } else {
4455 // fallback path
4456 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004457 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004458 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4459 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4460 EGLint eglErr = eglGetError();
4461 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4462 ALOGW("captureScreen: fence wait timed out");
4463 } else {
4464 ALOGW_IF(eglErr != EGL_SUCCESS,
4465 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004466 }
4467 eglDestroySyncKHR(mEGLDisplay, sync);
4468 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004469 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004470 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004471 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004472 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004473
4474 if (DEBUG_SCREENSHOTS) {
4475 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4476 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4477 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4478 hw, minLayerZ, maxLayerZ);
4479 delete [] pixels;
4480 }
4481
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004482 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004483 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004484
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004485 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004486}
4487
Mathias Agopiand5556842013-09-19 17:08:37 -07004488void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004489 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004490 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004491 for (size_t y=0 ; y<h ; y++) {
4492 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4493 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004494 if (p[x] != 0xFF000000) return;
4495 }
4496 }
4497 ALOGE("*** we just took a black screenshot ***\n"
4498 "requested minz=%d, maxz=%d, layerStack=%d",
4499 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004500
Robert Carr2047fae2016-11-28 14:09:09 -08004501 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004502 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004503 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004504 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004505 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004506 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004507 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4508 layer->isVisible() ? '+' : '-',
4509 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004510 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004511 i++;
4512 });
4513 }
4514 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004515 }
4516}
4517
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004518// ---------------------------------------------------------------------------
4519
Dan Stoza412903f2017-04-27 13:42:17 -07004520void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4521 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004522}
4523
Dan Stoza412903f2017-04-27 13:42:17 -07004524void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4525 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004526}
4527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004529
4530
4531#if defined(__gl_h_)
4532#error "don't include gl/gl.h in this file"
4533#endif
4534
4535#if defined(__gl2_h_)
4536#error "don't include gl2/gl2.h in this file"
4537#endif