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