blob: 4055693e453944d327fd181e34a06d278eea179d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasd7f49c52017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Jiyong Park00b15b82017-08-10 20:30:56 +0900100extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Steven Thomasd7f49c52017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700132bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700142 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700144 mTransactionPending(false),
145 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700146 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700147 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700148 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800149 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800151 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800154 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700156 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700157 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700158 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700159 mDebugInSwapBuffers(0),
160 mLastSwapBufferTime(0),
161 mDebugInTransaction(0),
162 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700163 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700164 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800165 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000166 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700167 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700168 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700169 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800170 mHasPoweredOff(false),
171 mFrameBuckets(),
172 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700173 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800174 mNumLayers(0),
Steven Thomasd7f49c52017-07-26 18:48:28 -0700175 mVrFlingerRequestsDisplay(false),
176 mMainThreadId(std::this_thread::get_id()),
177 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800179 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800180
181 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
183
184 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
186
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700190 useContextPriority = getBool< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::useContextPriority>(false);
192
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700193 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
194 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
195
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700196 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
197 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
198
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800199 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
200 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
201
Steven Thomas050b2c82017-03-06 11:45:16 -0800202 // Vr flinger is only enabled on Daydream ready devices.
203 useVrFlinger = getBool< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::useVrFlinger>(false);
205
Fabien Sanglard1971b632017-03-10 14:50:03 -0800206 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
208
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600209 hasWideColorDisplay =
210 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
211
Saurabh Shahf4174532017-07-13 10:45:07 -0700212 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 // debugging stuff...
215 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700216
Mathias Agopianb4b17302013-03-20 18:36:41 -0700217 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700218 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 property_get("debug.sf.showupdates", value, "0");
221 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700222
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700223 property_get("debug.sf.ddms", value, "0");
224 mDebugDDMS = atoi(value);
225 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700226 if (!startDdmConnection()) {
227 // start failed, and DDMS debugging not enabled
228 mDebugDDMS = 0;
229 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700230 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700231 ALOGI_IF(mDebugRegion, "showupdates enabled");
232 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700233
234 property_get("debug.sf.disable_backpressure", value, "0");
235 mPropagateBackpressure = !atoi(value);
236 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700237
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800238 property_get("debug.sf.enable_hwc_vds", value, "0");
239 mUseHwcVirtualDisplays = atoi(value);
240 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800241
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800242 property_get("ro.sf.disable_triple_buffer", value, "1");
243 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800244 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700245
Romain Guy11d63f42017-07-20 12:47:14 -0700246 // We should be reading 'persist.sys.sf.color_saturation' here
247 // but since /data may be encrypted, we need to wait until after vold
248 // comes online to attempt to read the property. The property is
249 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250}
251
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252void SurfaceFlinger::onFirstRef()
253{
254 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800255}
256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257SurfaceFlinger::~SurfaceFlinger()
258{
Mathias Agopiana4912602012-07-12 14:25:33 -0700259 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
260 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
261 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262}
263
Dan Stozac7014012014-02-14 15:03:43 -0800264void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800265{
266 // the window manager died on us. prepare its eulogy.
267
Andy McFadden13a082e2012-08-24 10:16:42 -0700268 // restore initial conditions (default device unblank, etc)
269 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800270
271 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700272 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800273}
274
Robert Carr1db73f62016-12-21 12:58:51 -0800275static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700276 status_t err = client->initCheck();
277 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800278 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279 }
Robert Carr1db73f62016-12-21 12:58:51 -0800280 return nullptr;
281}
282
283sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
284 return initClient(new Client(this));
285}
286
287sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
288 const sp<IGraphicBufferProducer>& gbp) {
289 if (authenticateSurfaceTexture(gbp) == false) {
290 return nullptr;
291 }
292 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
293 if (layer == nullptr) {
294 return nullptr;
295 }
296
297 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298}
299
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700300sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
301 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302{
303 class DisplayToken : public BBinder {
304 sp<SurfaceFlinger> flinger;
305 virtual ~DisplayToken() {
306 // no more references, this display must be terminated
307 Mutex::Autolock _l(flinger->mStateLock);
308 flinger->mCurrentState.displays.removeItem(this);
309 flinger->setTransactionFlags(eDisplayTransactionNeeded);
310 }
311 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700312 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700313 : flinger(flinger) {
314 }
315 };
316
317 sp<BBinder> token = new DisplayToken(this);
318
319 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700320 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700321 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700322 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700323 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324 return token;
325}
326
Jesse Hall6c913be2013-08-08 12:15:49 -0700327void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
328 Mutex::Autolock _l(mStateLock);
329
330 ssize_t idx = mCurrentState.displays.indexOfKey(display);
331 if (idx < 0) {
332 ALOGW("destroyDisplay: invalid display token");
333 return;
334 }
335
336 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
337 if (!info.isVirtualDisplay()) {
338 ALOGE("destroyDisplay called for non-virtual display");
339 return;
340 }
Irvelffc9efc2016-07-27 15:16:37 -0700341 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700342 mCurrentState.displays.removeItemsAt(idx);
343 setTransactionFlags(eDisplayTransactionNeeded);
344}
345
Jesse Hall692c7232012-11-08 15:41:56 -0800346void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800347 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800348 ALOGW_IF(mBuiltinDisplays[type],
349 "Overwriting display token for display type %d", type);
350 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800351 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700352 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800353 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700354 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800355}
356
Mathias Agopiane57f2922012-08-09 16:29:12 -0700357sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700358 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700359 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
360 return NULL;
361 }
Jesse Hall692c7232012-11-08 15:41:56 -0800362 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700363}
364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365void SurfaceFlinger::bootFinished()
366{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700367 if (mStartPropertySetThread->join() != NO_ERROR) {
368 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 const nsecs_t now = systemTime();
371 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000372 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700373
374 // wait patiently for the window manager death
375 const String16 name("window");
376 sp<IBinder> window(defaultServiceManager()->getService(name));
377 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700379 }
380
Steven Thomas050b2c82017-03-06 11:45:16 -0800381 if (mVrFlinger) {
382 mVrFlinger->OnBootFinished();
383 }
384
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700385 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700386 // formerly we would just kill the process, but we now ask it to exit so it
387 // can choose where to stop the animation.
388 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700389
390 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
391 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
392 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700393
Thierry Strudel2924d012017-08-14 15:19:37 -0700394 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700395 readPersistentProperties();
396 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700397 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian3f844832013-08-07 21:24:32 -0700400void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700401 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700402 RenderEngine& engine;
403 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700405 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
406 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700407 }
408 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700409 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700410 return true;
411 }
412 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700413 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700414}
415
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416class DispSyncSource : public VSyncSource, private DispSync::Callback {
417public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700418 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000419 const char* name) :
420 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700421 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700422 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000423 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
424 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700425 mDispSync(dispSync),
426 mCallbackMutex(),
427 mCallback(),
428 mVsyncMutex(),
429 mPhaseOffset(phaseOffset),
430 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700431
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 virtual ~DispSyncSource() {}
433
434 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 static_cast<DispSync::Callback*>(this));
439 if (err != NO_ERROR) {
440 ALOGE("error registering vsync callback: %s (%d)",
441 strerror(-err), err);
442 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700443 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444 } else {
445 status_t err = mDispSync->removeEventListener(
446 static_cast<DispSync::Callback*>(this));
447 if (err != NO_ERROR) {
448 ALOGE("error unregistering vsync callback: %s (%d)",
449 strerror(-err), err);
450 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700451 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 }
455
456 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 mCallback = callback;
459 }
460
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 virtual void setPhaseOffset(nsecs_t phaseOffset) {
462 Mutex::Autolock lock(mVsyncMutex);
463
464 // Normalize phaseOffset to [0, period)
465 auto period = mDispSync->getPeriod();
466 phaseOffset %= period;
467 if (phaseOffset < 0) {
468 // If we're here, then phaseOffset is in (-period, 0). After this
469 // operation, it will be in (0, period)
470 phaseOffset += period;
471 }
472 mPhaseOffset = phaseOffset;
473
474 // If we're not enabled, we don't need to mess with the listeners
475 if (!mEnabled) {
476 return;
477 }
478
479 // Remove the listener with the old offset
480 status_t err = mDispSync->removeEventListener(
481 static_cast<DispSync::Callback*>(this));
482 if (err != NO_ERROR) {
483 ALOGE("error unregistering vsync callback: %s (%d)",
484 strerror(-err), err);
485 }
486
487 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000488 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 static_cast<DispSync::Callback*>(this));
490 if (err != NO_ERROR) {
491 ALOGE("error registering vsync callback: %s (%d)",
492 strerror(-err), err);
493 }
494 }
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496private:
497 virtual void onDispSyncEvent(nsecs_t when) {
498 sp<VSyncSource::Callback> callback;
499 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 callback = mCallback;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 if (mTraceVsync) {
504 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700505 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 }
508
509 if (callback != NULL) {
510 callback->onVSyncEvent(when);
511 }
512 }
513
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 const char* const mName;
515
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 int mValue;
517
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700518 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 const String8 mVsyncOnLabel;
520 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700523
524 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526
527 Mutex mVsyncMutex; // Protects the following
528 nsecs_t mPhaseOffset;
529 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530};
531
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700532class InjectVSyncSource : public VSyncSource {
533public:
534 InjectVSyncSource() {}
535
536 virtual ~InjectVSyncSource() {}
537
538 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
539 std::lock_guard<std::mutex> lock(mCallbackMutex);
540 mCallback = callback;
541 }
542
543 virtual void onInjectSyncEvent(nsecs_t when) {
544 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu6200eac2017-10-05 14:24:41 -0700545 if (mCallback != nullptr) {
546 mCallback->onVSyncEvent(when);
547 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700548 }
549
550 virtual void setVSyncEnabled(bool) {}
551 virtual void setPhaseOffset(nsecs_t) {}
552
553private:
554 std::mutex mCallbackMutex; // Protects the following
555 sp<VSyncSource::Callback> mCallback;
556};
557
Wei Wangf9b05ee2017-07-19 20:59:39 -0700558// Do not call property_set on main thread which will be blocked by init
559// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700560void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700561 ALOGI( "SurfaceFlinger's main thread ready to run. "
562 "Initializing graphics H/W...");
563
Thierry Strudel2924d012017-08-14 15:19:37 -0700564 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900565
Steven Thomasd7f49c52017-07-26 18:48:28 -0700566 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800567
Steven Thomasd7f49c52017-07-26 18:48:28 -0700568 // initialize EGL for the default display
569 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
570 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800571
Steven Thomasd7f49c52017-07-26 18:48:28 -0700572 // start the EventThread
573 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
574 vsyncPhaseOffsetNs, true, "app");
575 mEventThread = new EventThread(vsyncSrc, *this, false);
576 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
577 sfVsyncPhaseOffsetNs, true, "sf");
578 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
579 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800580
Steven Thomasd7f49c52017-07-26 18:48:28 -0700581 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
582 struct sched_param param = {0};
583 param.sched_priority = 2;
584 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
585 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
586 }
587 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
588 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800589 }
590
Steven Thomasd7f49c52017-07-26 18:48:28 -0700591 // Get a RenderEngine for the given display / config (can't fail)
592 mRenderEngine = RenderEngine::create(mEGLDisplay,
593 HAL_PIXEL_FORMAT_RGBA_8888,
594 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595
Steven Thomasd7f49c52017-07-26 18:48:28 -0700596 // retrieve the EGL context that was selected/created
597 mEGLContext = mRenderEngine->getEGLContext();
598
599 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
600 "couldn't create EGLContext");
601
602 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
603 "Starting with vr flinger active is not currently supported.");
604 mHwc.reset(new HWComposer(false));
605 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800606
Steven Thomas050b2c82017-03-06 11:45:16 -0800607 if (useVrFlinger) {
608 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700609 // This callback is called from the vr flinger dispatch thread. We
610 // need to call signalTransaction(), which requires holding
611 // mStateLock when we're not on the main thread. Acquiring
612 // mStateLock from the vr flinger dispatch thread might trigger a
613 // deadlock in surface flinger (see b/66916578), so post a message
614 // to be handled on the main thread instead.
615 sp<LambdaMessage> message = new LambdaMessage([=]() {
616 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
617 mVrFlingerRequestsDisplay = requestDisplay;
618 signalTransaction();
619 });
620 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800621 };
622 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
623 vrFlingerRequestDisplayCallback);
624 if (!mVrFlinger) {
625 ALOGE("Failed to start vrflinger");
626 }
627 }
628
Jamie Gennisd1700752013-10-14 12:22:52 -0700629 mEventControlThread = new EventControlThread(this);
630 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
631
Mathias Agopian92a979a2012-08-02 18:32:23 -0700632 // initialize our drawing state
633 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700634
Andy McFadden13a082e2012-08-24 10:16:42 -0700635 // set initial conditions (e.g. unblank default device)
636 initializeDisplays();
637
Dan Stoza4e637772016-07-28 13:31:51 -0700638 mRenderEngine->primeCache();
639
Wei Wangf9b05ee2017-07-19 20:59:39 -0700640 // Inform native graphics APIs whether the present timestamp is supported:
641 if (getHwComposer().hasCapability(
642 HWC2::Capability::PresentFenceIsNotReliable)) {
643 mStartPropertySetThread = new StartPropertySetThread(false);
644 } else {
645 mStartPropertySetThread = new StartPropertySetThread(true);
646 }
647
648 if (mStartPropertySetThread->Start() != NO_ERROR) {
649 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800650 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800651
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700653}
654
Romain Guy11d63f42017-07-20 12:47:14 -0700655void SurfaceFlinger::readPersistentProperties() {
656 char value[PROPERTY_VALUE_MAX];
657
658 property_get("persist.sys.sf.color_saturation", value, "1.0");
659 mSaturation = atof(value);
660 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100661
662 property_get("persist.sys.sf.native_mode", value, "0");
663 mForceNativeColorMode = atoi(value) == 1;
664 if (mForceNativeColorMode) {
665 ALOGV("Forcing native color mode");
666 }
Romain Guy11d63f42017-07-20 12:47:14 -0700667}
668
Mathias Agopiana67e4182012-06-19 17:26:12 -0700669void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800670 // Start boot animation service by setting a property mailbox
671 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700672 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800673 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700674 if (mStartPropertySetThread->join() != NO_ERROR) {
675 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800676 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700677}
678
Mathias Agopian875d8e12013-06-07 15:35:48 -0700679size_t SurfaceFlinger::getMaxTextureSize() const {
680 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700681}
682
Mathias Agopian875d8e12013-06-07 15:35:48 -0700683size_t SurfaceFlinger::getMaxViewportDims() const {
684 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700685}
686
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800687// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800688
Jamie Gennis582270d2011-08-17 18:19:00 -0700689bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800690 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800691 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800692 return authenticateSurfaceTextureLocked(bufferProducer);
693}
694
695bool SurfaceFlinger::authenticateSurfaceTextureLocked(
696 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800697 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700698 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800699}
700
Brian Anderson6b376712017-04-04 10:51:39 -0700701status_t SurfaceFlinger::getSupportedFrameTimestamps(
702 std::vector<FrameEvent>* outSupported) const {
703 *outSupported = {
704 FrameEvent::REQUESTED_PRESENT,
705 FrameEvent::ACQUIRE,
706 FrameEvent::LATCH,
707 FrameEvent::FIRST_REFRESH_START,
708 FrameEvent::LAST_REFRESH_START,
709 FrameEvent::GPU_COMPOSITION_DONE,
710 FrameEvent::DEQUEUE_READY,
711 FrameEvent::RELEASE,
712 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700713 ConditionalLock _l(mStateLock,
714 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700715 if (!getHwComposer().hasCapability(
716 HWC2::Capability::PresentFenceIsNotReliable)) {
717 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
718 }
719 return NO_ERROR;
720}
721
Dan Stoza7f7da322014-05-02 15:26:25 -0700722status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
723 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700724 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700725 return BAD_VALUE;
726 }
727
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500728 if (!display.get())
729 return NAME_NOT_FOUND;
730
Jesse Hall692c7232012-11-08 15:41:56 -0800731 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700732 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800733 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700734 type = i;
735 break;
736 }
737 }
738
739 if (type < 0) {
740 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700741 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700742
Mathias Agopian8b736f12012-08-13 17:54:26 -0700743 // TODO: Not sure if display density should handled by SF any longer
744 class Density {
745 static int getDensityFromProperty(char const* propName) {
746 char property[PROPERTY_VALUE_MAX];
747 int density = 0;
748 if (property_get(propName, property, NULL) > 0) {
749 density = atoi(property);
750 }
751 return density;
752 }
753 public:
754 static int getEmuDensity() {
755 return getDensityFromProperty("qemu.sf.lcd_density"); }
756 static int getBuildDensity() {
757 return getDensityFromProperty("ro.sf.lcd_density"); }
758 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700759
Dan Stoza7f7da322014-05-02 15:26:25 -0700760 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700761
Steven Thomas6d8110b2017-08-31 18:24:21 -0700762 ConditionalLock _l(mStateLock,
763 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800764 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 DisplayInfo info = DisplayInfo();
766
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 float xdpi = hwConfig->getDpiX();
768 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700769
770 if (type == DisplayDevice::DISPLAY_PRIMARY) {
771 // The density of the device is provided by a build property
772 float density = Density::getBuildDensity() / 160.0f;
773 if (density == 0) {
774 // the build doesn't provide a density -- this is wrong!
775 // use xdpi instead
776 ALOGE("ro.sf.lcd_density must be defined as a build property");
777 density = xdpi / 160.0f;
778 }
779 if (Density::getEmuDensity()) {
780 // if "qemu.sf.lcd_density" is specified, it overrides everything
781 xdpi = ydpi = density = Density::getEmuDensity();
782 density /= 160.0f;
783 }
784 info.density = density;
785
786 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700787 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000788 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 } else {
790 // TODO: where should this value come from?
791 static const int TV_DENSITY = 213;
792 info.density = TV_DENSITY / 160.0f;
793 info.orientation = 0;
794 }
795
Dan Stoza9e56aa02015-11-02 13:00:03 -0800796 info.w = hwConfig->getWidth();
797 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 info.xdpi = xdpi;
799 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900801 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802
Andy McFadden91b2ca82014-06-13 14:04:23 -0700803 // This is how far in advance a buffer must be queued for
804 // presentation at a given time. If you want a buffer to appear
805 // on the screen at time N, you must submit the buffer before
806 // (N - presentationDeadline).
807 //
808 // Normally it's one full refresh period (to give SF a chance to
809 // latch the buffer), but this can be reduced by configuring a
810 // DispSync offset. Any additional delays introduced by the hardware
811 // composer or panel must be accounted for here.
812 //
813 // We add an additional 1ms to allow for processing time and
814 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800816 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700817
818 // All non-virtual displays are currently considered secure.
819 info.secure = true;
820
Michael Wright28f24d02016-07-12 13:30:53 -0700821 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 }
823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 return NO_ERROR;
825}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700826
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800827status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700828 DisplayStatInfo* stats) {
829 if (stats == NULL) {
830 return BAD_VALUE;
831 }
832
833 // FIXME for now we always return stats for the primary display
834 memset(stats, 0, sizeof(*stats));
835 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
836 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
837 return NO_ERROR;
838}
839
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700840int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800841 if (display == NULL) {
842 ALOGE("%s : display is NULL", __func__);
843 return BAD_VALUE;
844 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700845
846 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700847 if (device != NULL) {
848 return device->getActiveConfig();
849 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700850
Dan Stoza24a42e92015-03-09 10:04:11 -0700851 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700852}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700853
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700854void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
855 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
856 this);
857 int32_t type = hw->getDisplayType();
858 int currentMode = hw->getActiveConfig();
859
860 if (mode == currentMode) {
861 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
862 return;
863 }
864
865 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
866 ALOGW("Trying to set config for virtual display");
867 return;
868 }
869
870 hw->setActiveConfig(mode);
871 getHwComposer().setActiveConfig(type, mode);
872}
873
874status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
875 class MessageSetActiveConfig: public MessageBase {
876 SurfaceFlinger& mFlinger;
877 sp<IBinder> mDisplay;
878 int mMode;
879 public:
880 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
881 int mode) :
882 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
883 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700884 Vector<DisplayInfo> configs;
885 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700886 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700887 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700888 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700889 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700890 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700891 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
892 if (hw == NULL) {
893 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700894 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700895 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
896 ALOGW("Attempt to set active config = %d for virtual display",
897 mMode);
898 } else {
899 mFlinger.setActiveConfigInternal(hw, mMode);
900 }
901 return true;
902 }
903 };
904 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
905 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700906 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700907}
Michael Wright28f24d02016-07-12 13:30:53 -0700908status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
909 Vector<android_color_mode_t>* outColorModes) {
910 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
911 return BAD_VALUE;
912 }
913
914 if (!display.get()) {
915 return NAME_NOT_FOUND;
916 }
917
918 int32_t type = NAME_NOT_FOUND;
919 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
920 if (display == mBuiltinDisplays[i]) {
921 type = i;
922 break;
923 }
924 }
925
926 if (type < 0) {
927 return type;
928 }
929
Steven Thomas6d8110b2017-08-31 18:24:21 -0700930 std::vector<android_color_mode_t> modes;
931 {
932 ConditionalLock _l(mStateLock,
933 std::this_thread::get_id() != mMainThreadId);
934 modes = getHwComposer().getColorModes(type);
935 }
Michael Wright28f24d02016-07-12 13:30:53 -0700936 outColorModes->clear();
937 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
938
939 return NO_ERROR;
940}
941
942android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700943 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700944 if (device != nullptr) {
945 return device->getActiveColorMode();
946 }
947 return static_cast<android_color_mode_t>(BAD_VALUE);
948}
949
950void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
951 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700952 int32_t type = hw->getDisplayType();
953 android_color_mode_t currentMode = hw->getActiveColorMode();
954
955 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700956 return;
957 }
958
959 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
960 ALOGW("Trying to set config for virtual display");
961 return;
962 }
963
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600964 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
965 hw->getDisplayType());
966
Michael Wright28f24d02016-07-12 13:30:53 -0700967 hw->setActiveColorMode(mode);
968 getHwComposer().setActiveColorMode(type, mode);
969}
970
971
972status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
973 android_color_mode_t colorMode) {
974 class MessageSetActiveColorMode: public MessageBase {
975 SurfaceFlinger& mFlinger;
976 sp<IBinder> mDisplay;
977 android_color_mode_t mMode;
978 public:
979 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
980 android_color_mode_t mode) :
981 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
982 virtual bool handler() {
983 Vector<android_color_mode_t> modes;
984 mFlinger.getDisplayColorModes(mDisplay, &modes);
985 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
986 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600987 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
988 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700989 return true;
990 }
991 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
992 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600993 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
994 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700995 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600996 ALOGW("Attempt to set active color mode %s %d for virtual display",
997 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700998 } else {
999 mFlinger.setActiveColorModeInternal(hw, mMode);
1000 }
1001 return true;
1002 }
1003 };
1004 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1005 postMessageSync(msg);
1006 return NO_ERROR;
1007}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001008
Svetoslavd85084b2014-03-20 10:28:31 -07001009status_t SurfaceFlinger::clearAnimationFrameStats() {
1010 Mutex::Autolock _l(mStateLock);
1011 mAnimFrameTracker.clearStats();
1012 return NO_ERROR;
1013}
1014
1015status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1016 Mutex::Autolock _l(mStateLock);
1017 mAnimFrameTracker.getStats(outStats);
1018 return NO_ERROR;
1019}
1020
Dan Stozac4f471e2016-03-24 09:31:08 -07001021status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1022 HdrCapabilities* outCapabilities) const {
1023 Mutex::Autolock _l(mStateLock);
1024
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001025 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001026 if (displayDevice == nullptr) {
1027 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1028 return BAD_VALUE;
1029 }
1030
1031 std::unique_ptr<HdrCapabilities> capabilities =
1032 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1033 if (capabilities) {
1034 std::swap(*outCapabilities, *capabilities);
1035 } else {
1036 return BAD_VALUE;
1037 }
1038
1039 return NO_ERROR;
1040}
1041
Chia-I Wu6200eac2017-10-05 14:24:41 -07001042void SurfaceFlinger::enableVSyncInjectionsInternal(bool enable) {
1043 Mutex::Autolock _l(mStateLock);
1044
1045 if (mInjectVSyncs == enable) {
1046 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001047 }
1048
1049 if (enable) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001050 ALOGV("VSync Injections enabled");
1051 if (mVSyncInjector.get() == nullptr) {
1052 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001053 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001054 }
1055 mEventQueue.setEventThread(mInjectorEventThread);
1056 } else {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001057 ALOGV("VSync Injections disabled");
1058 mEventQueue.setEventThread(mSFEventThread);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001059 }
Chia-I Wu6200eac2017-10-05 14:24:41 -07001060
1061 mInjectVSyncs = enable;
1062}
1063
1064status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1065 class MessageEnableVSyncInjections : public MessageBase {
1066 SurfaceFlinger* mFlinger;
1067 bool mEnable;
1068 public:
1069 MessageEnableVSyncInjections(SurfaceFlinger* flinger, bool enable)
1070 : mFlinger(flinger), mEnable(enable) { }
1071 virtual bool handler() {
1072 mFlinger->enableVSyncInjectionsInternal(mEnable);
1073 return true;
1074 }
1075 };
1076 sp<MessageBase> msg = new MessageEnableVSyncInjections(this, enable);
1077 postMessageSync(msg);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001078 return NO_ERROR;
1079}
1080
1081status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu6200eac2017-10-05 14:24:41 -07001082 Mutex::Autolock _l(mStateLock);
1083
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001084 if (!mInjectVSyncs) {
1085 ALOGE("VSync Injections not enabled");
1086 return BAD_VALUE;
1087 }
1088 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1089 ALOGV("Injecting VSync inside SurfaceFlinger");
1090 mVSyncInjector->onInjectSyncEvent(when);
1091 }
1092 return NO_ERROR;
1093}
1094
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001095// ----------------------------------------------------------------------------
1096
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001097sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1098 ISurfaceComposer::VsyncSource vsyncSource) {
1099 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1100 return mSFEventThread->createEventConnection();
1101 } else {
1102 return mEventThread->createEventConnection();
1103 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001104}
1105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001106// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001107
1108void SurfaceFlinger::waitForEvent() {
1109 mEventQueue.waitMessage();
1110}
1111
1112void SurfaceFlinger::signalTransaction() {
1113 mEventQueue.invalidate();
1114}
1115
1116void SurfaceFlinger::signalLayerUpdate() {
1117 mEventQueue.invalidate();
1118}
1119
1120void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001121 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001122 mEventQueue.refresh();
1123}
1124
1125status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001126 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001127 return mEventQueue.postMessage(msg, reltime);
1128}
1129
1130status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001131 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001132 status_t res = mEventQueue.postMessage(msg, reltime);
1133 if (res == NO_ERROR) {
1134 msg->wait();
1135 }
1136 return res;
1137}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001138
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001139void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001140 do {
1141 waitForEvent();
1142 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001143}
1144
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001145void SurfaceFlinger::enableHardwareVsync() {
1146 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001147 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001148 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001149 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1150 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001151 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001152 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001153}
1154
Jesse Hall948fe0c2013-10-14 12:56:09 -07001155void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001156 Mutex::Autolock _l(mHWVsyncLock);
1157
Jesse Hall948fe0c2013-10-14 12:56:09 -07001158 if (makeAvailable) {
1159 mHWVsyncAvailable = true;
1160 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001161 // Hardware vsync is not currently available, so abort the resync
1162 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001163 return;
1164 }
1165
Dan Stoza9e56aa02015-11-02 13:00:03 -08001166 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1167 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001168
1169 mPrimaryDispSync.reset();
1170 mPrimaryDispSync.setPeriod(period);
1171
1172 if (!mPrimaryHWVsyncEnabled) {
1173 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001174 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1175 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001176 mPrimaryHWVsyncEnabled = true;
1177 }
1178}
1179
Jesse Hall948fe0c2013-10-14 12:56:09 -07001180void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001181 Mutex::Autolock _l(mHWVsyncLock);
1182 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001183 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1184 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 mPrimaryDispSync.endResync();
1186 mPrimaryHWVsyncEnabled = false;
1187 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001188 if (makeUnavailable) {
1189 mHWVsyncAvailable = false;
1190 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001191}
1192
Tim Murray4a4e4a22016-04-19 16:29:23 +00001193void SurfaceFlinger::resyncWithRateLimit() {
1194 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001195
1196 // No explicit locking is needed here since EventThread holds a lock while calling this method
1197 static nsecs_t sLastResyncAttempted = 0;
1198 const nsecs_t now = systemTime();
1199 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001200 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001201 }
Dan Stoza57164302017-05-08 14:03:54 -07001202 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001203}
1204
Steven Thomasd7f49c52017-07-26 18:48:28 -07001205void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1206 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001207 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001208 // Ignore any vsyncs from a previous hardware composer.
1209 if (sequenceId != mComposerSequenceId) {
1210 return;
1211 }
1212
1213 int32_t type;
1214 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001215 return;
1216 }
1217
Jamie Gennisd1700752013-10-14 12:22:52 -07001218 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001219
Jamie Gennisd1700752013-10-14 12:22:52 -07001220 { // Scope for the lock
1221 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001222 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001223 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001224 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001225 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001226
1227 if (needsHwVsync) {
1228 enableHardwareVsync();
1229 } else {
1230 disableHardwareVsync(false);
1231 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001232}
1233
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001234void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001235 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001236 *compositorTiming = mCompositorTiming;
1237}
1238
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001239void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001240 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001241 wp<IBinder> token = mBuiltinDisplays[type];
1242
1243 // All non-virtual displays are currently considered secure.
1244 const bool isSecure = true;
1245
1246 sp<IGraphicBufferProducer> producer;
1247 sp<IGraphicBufferConsumer> consumer;
1248 BufferQueue::createBufferQueue(&producer, &consumer);
1249
1250 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1251
1252 bool hasWideColorModes = false;
1253 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1254 for (android_color_mode_t colorMode : modes) {
1255 switch (colorMode) {
1256 case HAL_COLOR_MODE_DISPLAY_P3:
1257 case HAL_COLOR_MODE_ADOBE_RGB:
1258 case HAL_COLOR_MODE_DCI_P3:
1259 hasWideColorModes = true;
1260 break;
1261 default:
1262 break;
1263 }
1264 }
Romain Guy54f154a2017-10-24 21:40:32 +01001265 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001266 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1267 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001268 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001269 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001270 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001271 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001272 defaultColorMode = HAL_COLOR_MODE_SRGB;
1273 }
1274 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001275 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001276
1277 // Add the primary display token to mDrawingState so we don't try to
1278 // recreate the DisplayDevice for the primary display.
1279 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1280
1281 // make the GLContext current so that we can create textures when creating
1282 // Layers (which may happens before we render something)
1283 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001284}
1285
Steven Thomasd7f49c52017-07-26 18:48:28 -07001286void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1287 hwc2_display_t display, HWC2::Connection connection,
1288 bool primaryDisplay) {
1289 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1290 sequenceId, display,
1291 connection == HWC2::Connection::Connected ?
1292 "connected" : "disconnected",
1293 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001294
Steven Thomasd7f49c52017-07-26 18:48:28 -07001295 // Only lock if we're not on the main thread. This function is normally
1296 // called on a hwbinder thread, but for the primary display it's called on
1297 // the main thread with the state lock already held, so don't attempt to
1298 // acquire it here.
1299 ConditionalLock lock(mStateLock,
1300 std::this_thread::get_id() != mMainThreadId);
1301
1302 if (primaryDisplay) {
1303 mHwc->onHotplug(display, connection);
1304 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1305 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001306 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001307 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001308 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001309 if (sequenceId != mComposerSequenceId) {
1310 return;
1311 }
1312 if (mHwc->isUsingVrComposer()) {
1313 ALOGE("External displays are not supported by the vr hardware composer.");
1314 return;
1315 }
1316 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasd7f49c52017-07-26 18:48:28 -07001318 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001319 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001320 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001321 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1322 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001323 }
1324 setTransactionFlags(eDisplayTransactionNeeded);
1325
Andy McFadden9e9689c2012-10-10 18:17:51 -07001326 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001327 }
Mathias Agopian86303202012-07-24 22:46:10 -07001328}
1329
Steven Thomasd7f49c52017-07-26 18:48:28 -07001330void SurfaceFlinger::onRefreshReceived(int sequenceId,
1331 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001332 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001333 if (sequenceId != mComposerSequenceId) {
1334 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001335 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001336 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001337}
1338
Dan Stoza9e56aa02015-11-02 13:00:03 -08001339void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001340 ATRACE_CALL();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001341 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001342 getHwComposer().setVsyncEnabled(disp,
1343 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001344}
1345
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001346// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasd7f49c52017-07-26 18:48:28 -07001347void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001348 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001349 // Clear the drawing state so that the logic inside of
1350 // handleTransactionLocked will fire. It will determine the delta between
1351 // mCurrentState and mDrawingState and re-apply all changes when we make the
1352 // transition.
1353 mDrawingState.displays.clear();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001354 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001355 mDisplays.clear();
1356}
1357
Steven Thomas050b2c82017-03-06 11:45:16 -08001358void SurfaceFlinger::updateVrFlinger() {
1359 if (!mVrFlinger)
1360 return;
1361 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1362 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001363 return;
1364 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001365
Steven Thomasd7f49c52017-07-26 18:48:28 -07001366 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1367 ALOGE("Vr flinger is only supported for remote hardware composer"
1368 " service connections. Ignoring request to transition to vr"
1369 " flinger.");
1370 mVrFlingerRequestsDisplay = false;
1371 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001372 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001373
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001374 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001375
Steven Thomasd7f49c52017-07-26 18:48:28 -07001376 int currentDisplayPowerMode = getDisplayDeviceLocked(
1377 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378
Steven Thomasd7f49c52017-07-26 18:48:28 -07001379 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001380 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001381 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001382
Steven Thomasd7f49c52017-07-26 18:48:28 -07001383 resetDisplayState();
1384 mHwc.reset(); // Delete the current instance before creating the new one
1385 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1386 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001387
Steven Thomasd7f49c52017-07-26 18:48:28 -07001388 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1389 "Switched to non-remote hardware composer");
1390
1391 if (vrFlingerRequestsDisplay) {
1392 mVrFlinger->GrantDisplayOwnership();
1393 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001396
1397 mVisibleRegionsDirty = true;
1398 invalidateHwcGeometry();
1399
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001400 // Re-enable default display.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001401 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1402 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1403 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001404
Steven Thomasd7f49c52017-07-26 18:48:28 -07001405 // Reset the timing values to account for the period of the swapped in HWC
1406 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1407 const nsecs_t period = activeConfig->getVsyncPeriod();
1408 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001409
Steven Thomasd7f49c52017-07-26 18:48:28 -07001410 // Use phase of 0 since phase is not known.
1411 // Use latency of 0, which will snap to the ideal latency.
1412 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001413
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414 android_atomic_or(1, &mRepaintEverything);
1415 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416}
1417
Mathias Agopian4fec8732012-06-29 14:12:52 -07001418void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001419 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001420 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001421 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001422 bool frameMissed = !mHadClientComposition &&
1423 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001424 (mPreviousPresentFence->getSignalTime() ==
1425 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001426 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001427 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001428 signalLayerUpdate();
1429 break;
1430 }
1431
Steven Thomas050b2c82017-03-06 11:45:16 -08001432 // Now that we're going to make it to the handleMessageTransaction()
1433 // call below it's safe to call updateVrFlinger(), which will
1434 // potentially trigger a display handoff.
1435 updateVrFlinger();
1436
Dan Stoza6b9454d2014-11-07 16:00:59 -08001437 bool refreshNeeded = handleMessageTransaction();
1438 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001439 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001441 // Signal a refresh if a transaction modified the window state,
1442 // a new buffer was latched, or if HWC has requested a full
1443 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001444 signalRefresh();
1445 }
1446 break;
1447 }
1448 case MessageQueue::REFRESH: {
1449 handleMessageRefresh();
1450 break;
1451 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001452 }
1453}
1454
Dan Stoza6b9454d2014-11-07 16:00:59 -08001455bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001456 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001457 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001458 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001459 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001460 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001462}
1463
Dan Stoza6b9454d2014-11-07 16:00:59 -08001464bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001466 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001467}
1468
1469void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001470 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001471
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001472 mRefreshPending = false;
1473
Pablo Ceballos40845df2016-01-25 17:41:15 -08001474 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001475
Brian Andersond6927fb2016-07-23 23:37:30 -07001476 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001477 rebuildLayerStacks();
1478 setUpHWComposer();
1479 doDebugFlashRegions();
1480 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001481 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001482
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001483 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001484
1485 mHadClientComposition = false;
1486 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1487 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1488 mHadClientComposition = mHadClientComposition ||
1489 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1490 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001491
Dan Stoza9e56aa02015-11-02 13:00:03 -08001492 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001493}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001494
Mathias Agopiancd60f992012-08-16 16:28:27 -07001495void SurfaceFlinger::doDebugFlashRegions()
1496{
1497 // is debugging enabled
1498 if (CC_LIKELY(!mDebugRegion))
1499 return;
1500
1501 const bool repaintEverything = mRepaintEverything;
1502 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1503 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001504 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001505 // transform the dirty region into this screen's coordinate space
1506 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1507 if (!dirtyRegion.isEmpty()) {
1508 // redraw the whole screen
1509 doComposeSurfaces(hw, Region(hw->bounds()));
1510
1511 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001513 RenderEngine& engine(getRenderEngine());
1514 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1515
Mathias Agopianda27af92012-09-13 18:17:13 -07001516 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001517 }
1518 }
1519 }
1520
1521 postFramebuffer();
1522
1523 if (mDebugRegion > 1) {
1524 usleep(mDebugRegion * 1000);
1525 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001526
Dan Stoza9e56aa02015-11-02 13:00:03 -08001527 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001528 auto& displayDevice = mDisplays[displayId];
1529 if (!displayDevice->isDisplayOn()) {
1530 continue;
1531 }
1532
1533 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001534 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1535 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001536 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001537}
1538
Brian Andersond6927fb2016-07-23 23:37:30 -07001539void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001540{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001541 ATRACE_CALL();
1542 ALOGV("preComposition");
1543
Mathias Agopiancd60f992012-08-16 16:28:27 -07001544 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001545 mDrawingState.traverseInZOrder([&](Layer* layer) {
1546 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001547 needExtraInvalidate = true;
1548 }
Robert Carr2047fae2016-11-28 14:09:09 -08001549 });
1550
Mathias Agopiancd60f992012-08-16 16:28:27 -07001551 if (needExtraInvalidate) {
1552 signalLayerUpdate();
1553 }
1554}
1555
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001556void SurfaceFlinger::updateCompositorTiming(
1557 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1558 std::shared_ptr<FenceTime>& presentFenceTime) {
1559 // Update queue of past composite+present times and determine the
1560 // most recently known composite to present latency.
1561 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1562 nsecs_t compositeToPresentLatency = -1;
1563 while (!mCompositePresentTimes.empty()) {
1564 CompositePresentTime& cpt = mCompositePresentTimes.front();
1565 // Cached values should have been updated before calling this method,
1566 // which helps avoid duplicate syscalls.
1567 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1568 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1569 break;
1570 }
1571 compositeToPresentLatency = displayTime - cpt.composite;
1572 mCompositePresentTimes.pop();
1573 }
1574
1575 // Don't let mCompositePresentTimes grow unbounded, just in case.
1576 while (mCompositePresentTimes.size() > 16) {
1577 mCompositePresentTimes.pop();
1578 }
1579
Brian Andersond0010582017-03-07 13:20:31 -08001580 setCompositorTimingSnapped(
1581 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1582}
1583
1584void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1585 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001586 // Integer division and modulo round toward 0 not -inf, so we need to
1587 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001588 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1590 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1591
Brian Andersond0010582017-03-07 13:20:31 -08001592 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1593 if (idealLatency <= 0) {
1594 idealLatency = vsyncInterval;
1595 }
1596
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001597 // Snap the latency to a value that removes scheduling jitter from the
1598 // composition and present times, which often have >1ms of jitter.
1599 // Reducing jitter is important if an app attempts to extrapolate
1600 // something (such as user input) to an accurate diasplay time.
1601 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1602 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001603 nsecs_t bias = vsyncInterval / 2;
1604 int64_t extraVsyncs =
1605 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1606 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1607 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001608
Brian Andersond0010582017-03-07 13:20:31 -08001609 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001610 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1611 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001612 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001613}
1614
1615void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001617 ATRACE_CALL();
1618 ALOGV("postComposition");
1619
Brian Anderson3546a3f2016-07-14 11:51:14 -07001620 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001621 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001622 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001623 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001624 }
1625
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001626 // |mStateLock| not needed as we are on the main thread
1627 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001628
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001629 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001630 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1631 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1632 glCompositionDoneFenceTime =
1633 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1634 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1635 } else {
1636 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1637 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001638
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001639 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001640 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1641 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1642 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001643
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001644 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1645 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1646
1647 // We use the refreshStartTime which might be sampled a little later than
1648 // when we started doing work for this frame, but that should be okay
1649 // since updateCompositorTiming has snapping logic.
1650 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001651 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001652 CompositorTiming compositorTiming;
1653 {
1654 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1655 compositorTiming = mCompositorTiming;
1656 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001657
Robert Carr2047fae2016-11-28 14:09:09 -08001658 mDrawingState.traverseInZOrder([&](Layer* layer) {
1659 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001660 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001661 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001662 recordBufferingStats(layer->getName().string(),
1663 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001664 }
Robert Carr2047fae2016-11-28 14:09:09 -08001665 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001666
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001667 if (presentFenceTime->isValid()) {
1668 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001669 enableHardwareVsync();
1670 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001671 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001672 }
1673 }
1674
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001675 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001676 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001677 enableHardwareVsync();
1678 }
1679 }
1680
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001681 if (mAnimCompositionPending) {
1682 mAnimCompositionPending = false;
1683
Brian Anderson4e606e32017-03-16 15:34:57 -07001684 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001685 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001686 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001687 } else {
1688 // The HWC doesn't support present fences, so use the refresh
1689 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690 nsecs_t presentTime =
1691 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001692 mAnimFrameTracker.setActualPresentTime(presentTime);
1693 }
1694 mAnimFrameTracker.advanceFrame();
1695 }
Dan Stozab90cf072015-03-05 11:05:59 -08001696
1697 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1698 return;
1699 }
1700
1701 nsecs_t currentTime = systemTime();
1702 if (mHasPoweredOff) {
1703 mHasPoweredOff = false;
1704 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001705 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001706 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001707 if (numPeriods < NUM_BUCKETS - 1) {
1708 mFrameBuckets[numPeriods] += elapsedTime;
1709 } else {
1710 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1711 }
1712 mTotalTime += elapsedTime;
1713 }
1714 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715}
1716
1717void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 ATRACE_CALL();
1719 ALOGV("rebuildLayerStacks");
1720
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1723 ATRACE_CALL();
1724 mVisibleRegionsDirty = false;
1725 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001726
Jeff Sharkey76488112017-02-27 14:15:18 -07001727 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1728 Region opaqueRegion;
1729 Region dirtyRegion;
1730 Vector<sp<Layer>> layersSortedByZ;
1731 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1732 const Transform& tr(displayDevice->getTransform());
1733 const Rect bounds(displayDevice->getBounds());
1734 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001735 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001736
Jeff Sharkey76488112017-02-27 14:15:18 -07001737 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001738 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1739 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001740 Region drawRegion(tr.transform(
1741 layer->visibleNonTransparentRegion));
1742 drawRegion.andSelf(bounds);
1743 if (!drawRegion.isEmpty()) {
1744 layersSortedByZ.add(layer);
1745 } else {
1746 // Clear out the HWC layer if this layer was
1747 // previously visible, but no longer is
Steven Thomasd7f49c52017-07-26 18:48:28 -07001748 layer->destroyHwcLayer(
1749 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001750 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001751 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001752 // WM changes displayDevice->layerStack upon sleep/awake.
1753 // Here we make sure we delete the HWC layers even if
1754 // WM changed their layer stack.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001755 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001756 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001757 });
1758 }
1759 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1760 displayDevice->undefinedRegion.set(bounds);
1761 displayDevice->undefinedRegion.subtractSelf(
1762 tr.transform(opaqueRegion));
1763 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001764 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001765 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001766}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001767
Romain Guy0147a172017-06-01 13:53:56 -07001768mat4 SurfaceFlinger::computeSaturationMatrix() const {
1769 if (mSaturation == 1.0f) {
1770 return mat4();
1771 }
1772
1773 // Rec.709 luma coefficients
1774 float3 luminance{0.213f, 0.715f, 0.072f};
1775 luminance *= 1.0f - mSaturation;
1776 return mat4(
1777 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1778 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1779 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1780 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1781 );
1782}
1783
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001784// pickColorMode translates a given dataspace into the best available color mode.
1785// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001786android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001787 if (mForceNativeColorMode) {
1788 return HAL_COLOR_MODE_NATIVE;
1789 }
1790
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001791 switch (dataSpace) {
1792 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1793 // system expects.
1794 case HAL_DATASPACE_UNKNOWN:
1795 case HAL_DATASPACE_SRGB:
1796 case HAL_DATASPACE_V0_SRGB:
1797 return HAL_COLOR_MODE_SRGB;
1798 break;
1799
1800 case HAL_DATASPACE_DISPLAY_P3:
1801 return HAL_COLOR_MODE_DISPLAY_P3;
1802 break;
1803
1804 default:
1805 // TODO (courtneygo): Do we want to assert an error here?
1806 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1807 dataSpace);
1808 return HAL_COLOR_MODE_SRGB;
1809 break;
1810 }
1811}
1812
Romain Guy0147a172017-06-01 13:53:56 -07001813android_dataspace SurfaceFlinger::bestTargetDataSpace(
1814 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001815 // Only support sRGB and Display-P3 right now.
1816 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1817 return HAL_DATASPACE_DISPLAY_P3;
1818 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001819 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1820 return HAL_DATASPACE_DISPLAY_P3;
1821 }
1822 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1823 return HAL_DATASPACE_DISPLAY_P3;
1824 }
1825
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001826 return HAL_DATASPACE_V0_SRGB;
1827}
1828
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 ATRACE_CALL();
1831 ALOGV("setUpHWComposer");
1832
Jesse Hall028dc8f2013-08-20 16:35:32 -07001833 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001834 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1835 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1836 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1837
1838 // If nothing has changed (!dirty), don't recompose.
1839 // If something changed, but we don't currently have any visible layers,
1840 // and didn't when we last did a composition, then skip it this time.
1841 // The second rule does two things:
1842 // - When all layers are removed from a display, we'll emit one black
1843 // frame, then nothing more until we get new layers.
1844 // - When a display is created with a private layer stack, we won't
1845 // emit any black frames until a layer is added to the layer stack.
1846 bool mustRecompose = dirty && !(empty && wasEmpty);
1847
1848 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1849 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1850 mustRecompose ? "doing" : "skipping",
1851 dirty ? "+" : "-",
1852 empty ? "+" : "-",
1853 wasEmpty ? "+" : "-");
1854
Dan Stoza71433162014-02-04 16:22:36 -08001855 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001856
1857 if (mustRecompose) {
1858 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1859 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001860 }
1861
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 // build the h/w work list
1863 if (CC_UNLIKELY(mGeometryInvalid)) {
1864 mGeometryInvalid = false;
1865 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1866 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1867 const auto hwcId = displayDevice->getHwcDisplayId();
1868 if (hwcId >= 0) {
1869 const Vector<sp<Layer>>& currentLayers(
1870 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001871 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001872 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001874 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001875 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001877 }
1878 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001879
Robert Carrae060832016-11-28 10:51:00 -08001880 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001881 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001882 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001883 }
1884 }
1885 }
1886 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001887 }
Riley Andrews03414a12014-07-01 14:22:59 -07001888
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001889
Romain Guy0147a172017-06-01 13:53:56 -07001890 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001891
Dan Stoza9e56aa02015-11-02 13:00:03 -08001892 // Set the per-frame data
1893 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1894 auto& displayDevice = mDisplays[displayId];
1895 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001896
Dan Stoza9e56aa02015-11-02 13:00:03 -08001897 if (hwcId < 0) {
1898 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001899 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001900 if (colorMatrix != mPreviousColorMatrix) {
1901 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1902 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1903 "display %zd: %d", displayId, result);
1904 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001905 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1906 layer->setPerFrameData(displayDevice);
1907 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001908
1909 if (hasWideColorDisplay) {
1910 android_color_mode newColorMode;
1911 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1912
1913 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1914 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1915 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1916 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1917 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1918 }
1919 newColorMode = pickColorMode(newDataSpace);
1920
Thierry Strudel2924d012017-08-14 15:19:37 -07001921 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001922 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 }
1924
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001925 mPreviousColorMatrix = colorMatrix;
1926
Dan Stoza9e56aa02015-11-02 13:00:03 -08001927 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001928 auto& displayDevice = mDisplays[displayId];
1929 if (!displayDevice->isDisplayOn()) {
1930 continue;
1931 }
1932
1933 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1935 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001936 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001938
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939void SurfaceFlinger::doComposition() {
1940 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001941 ALOGV("doComposition");
1942
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001943 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001944 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001945 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001946 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947 // transform the dirty region into this screen's coordinate space
1948 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001949
1950 // repaint the framebuffer (if needed)
1951 doDisplayComposition(hw, dirtyRegion);
1952
Mathias Agopiancd60f992012-08-16 16:28:27 -07001953 hw->dirtyRegion.clear();
1954 hw->flip(hw->swapRegion);
1955 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001956 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001957 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001958 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001959}
1960
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001961void SurfaceFlinger::postFramebuffer()
1962{
Mathias Agopian841cde52012-03-01 15:44:37 -08001963 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001965
Mathias Agopiana44b0412011-10-16 18:46:35 -07001966 const nsecs_t now = systemTime();
1967 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001968
Dan Stoza9e56aa02015-11-02 13:00:03 -08001969 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1970 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001971 if (!displayDevice->isDisplayOn()) {
1972 continue;
1973 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 const auto hwcId = displayDevice->getHwcDisplayId();
1975 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001976 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001977 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001978 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001979 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1981 sp<Fence> releaseFence = Fence::NO_FENCE;
1982 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1983 releaseFence = displayDevice->getClientTargetAcquireFence();
1984 } else {
1985 auto hwcLayer = layer->getHwcLayer(hwcId);
1986 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001987 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001988 layer->onLayerDisplayed(releaseFence);
1989 }
1990 if (hwcId >= 0) {
1991 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001992 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001993 }
1994
Mathias Agopiana44b0412011-10-16 18:46:35 -07001995 mLastSwapBufferTime = systemTime() - now;
1996 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001997
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001998 // |mStateLock| not needed as we are on the main thread
1999 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002000 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2001 logFrameStats();
2002 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002003}
2004
Mathias Agopian87baae12012-07-31 12:38:26 -07002005void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006{
Mathias Agopian841cde52012-03-01 15:44:37 -08002007 ATRACE_CALL();
2008
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002009 // here we keep a copy of the drawing state (that is the state that's
2010 // going to be overwritten by handleTransactionLocked()) outside of
2011 // mStateLock so that the side-effects of the State assignment
2012 // don't happen with mStateLock held (which can cause deadlocks).
2013 State drawingState(mDrawingState);
2014
Mathias Agopianca4d3602011-05-19 15:38:14 -07002015 Mutex::Autolock _l(mStateLock);
2016 const nsecs_t now = systemTime();
2017 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018
Mathias Agopianca4d3602011-05-19 15:38:14 -07002019 // Here we're guaranteed that some transaction flags are set
2020 // so we can call handleTransactionLocked() unconditionally.
2021 // We call getTransactionFlags(), which will also clear the flags,
2022 // with mStateLock held to guarantee that mCurrentState won't change
2023 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002024
Mathias Agopiane57f2922012-08-09 16:29:12 -07002025 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002026 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002027
Mathias Agopianca4d3602011-05-19 15:38:14 -07002028 mLastTransactionTime = systemTime() - now;
2029 mDebugInTransaction = 0;
2030 invalidateHwcGeometry();
2031 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002032}
2033
Mathias Agopian87baae12012-07-31 12:38:26 -07002034void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002035{
Dan Stoza7dde5992015-05-22 09:51:44 -07002036 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002037 mCurrentState.traverseInZOrder([](Layer* layer) {
2038 layer->notifyAvailableFrames();
2039 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002040
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002041 /*
2042 * Traversal of the children
2043 * (perform the transaction for each of them if needed)
2044 */
2045
Mathias Agopian3559b072012-08-15 13:46:03 -07002046 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002047 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002048 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002049 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002050
2051 const uint32_t flags = layer->doTransaction(0);
2052 if (flags & Layer::eVisibleRegion)
2053 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002054 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055 }
2056
2057 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002058 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002059 */
2060
Mathias Agopiane57f2922012-08-09 16:29:12 -07002061 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002062 // here we take advantage of Vector's copy-on-write semantics to
2063 // improve performance by skipping the transaction entirely when
2064 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002065 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2066 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002067 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002068 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002069 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002070 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002071
2072 // find the displays that were removed
2073 // (ie: in drawing state but not in current state)
2074 // also handle displays that changed
2075 // (ie: displays that are in both lists)
2076 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002077 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2078 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002079 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002080 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002081 // Call makeCurrent() on the primary display so we can
2082 // be sure that nothing associated with this display
2083 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002084 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002085 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002086 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002087 if (hw != NULL)
2088 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002089 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002090 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002091 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002092 } else {
2093 ALOGW("trying to remove the main display");
2094 }
2095 } else {
2096 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002097 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002098 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002099 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2100 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002101 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002102 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002103 // recreating the DisplayDevice, so we just remove it
2104 // from the drawing state, so that it get re-added
2105 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002106 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002107 if (hw != NULL)
2108 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002109 mDisplays.removeItem(display);
2110 mDrawingState.displays.removeItemsAt(i);
2111 dc--; i--;
2112 // at this point we must loop to the next item
2113 continue;
2114 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002115
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002116 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002117 if (disp != NULL) {
2118 if (state.layerStack != draw[i].layerStack) {
2119 disp->setLayerStack(state.layerStack);
2120 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002121 if ((state.orientation != draw[i].orientation)
2122 || (state.viewport != draw[i].viewport)
2123 || (state.frame != draw[i].frame))
2124 {
2125 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002126 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002127 }
Michael Lentine47e45402014-07-18 15:34:25 -07002128 if (state.width != draw[i].width || state.height != draw[i].height) {
2129 disp->setDisplaySize(state.width, state.height);
2130 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002131 }
2132 }
2133 }
2134
2135 // find displays that were added
2136 // (ie: in current state but not in drawing state)
2137 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002138 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002139 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002140
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002141 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002142 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002143 sp<IGraphicBufferProducer> bqProducer;
2144 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002145 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002146
Dan Stoza9e56aa02015-11-02 13:00:03 -08002147 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002148 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002149 // Virtual displays without a surface are dormant:
2150 // they have external state (layer stack, projection,
2151 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002152 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002153
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002154 // Allow VR composer to use virtual displays.
Steven Thomasd7f49c52017-07-26 18:48:28 -07002155 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002156 int width = 0;
2157 int status = state.surface->query(
2158 NATIVE_WINDOW_WIDTH, &width);
2159 ALOGE_IF(status != NO_ERROR,
2160 "Unable to query width (%d)", status);
2161 int height = 0;
2162 status = state.surface->query(
2163 NATIVE_WINDOW_HEIGHT, &height);
2164 ALOGE_IF(status != NO_ERROR,
2165 "Unable to query height (%d)", status);
2166 int intFormat = 0;
2167 status = state.surface->query(
2168 NATIVE_WINDOW_FORMAT, &intFormat);
2169 ALOGE_IF(status != NO_ERROR,
2170 "Unable to query format (%d)", status);
2171 auto format = static_cast<android_pixel_format_t>(
2172 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002173
Dan Stoza8cf150a2016-08-02 10:27:31 -07002174 mHwc->allocateVirtualDisplay(width, height, &format,
2175 &hwcId);
2176 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002177
Dan Stoza5cf424b2016-05-20 14:02:39 -07002178 // TODO: Plumb requested format back up to consumer
2179
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 sp<VirtualDisplaySurface> vds =
2181 new VirtualDisplaySurface(*mHwc,
2182 hwcId, state.surface, bqProducer,
2183 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002184
2185 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002186 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002187 }
2188 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002189 ALOGE_IF(state.surface!=NULL,
2190 "adding a supported display, but rendering "
2191 "surface is provided (%p), ignoring it",
2192 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002193
2194 hwcId = state.type;
2195 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2196 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002197 }
2198
2199 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002200 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002201 sp<DisplayDevice> hw =
2202 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2203 dispSurface, producer,
2204 mRenderEngine->getEGLConfig(),
2205 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002206 hw->setLayerStack(state.layerStack);
2207 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002208 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002209 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002210 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002212 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002213 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002214 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002215 }
2216 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002217 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002219
Mathias Agopian84300952012-11-21 16:02:13 -08002220 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2221 // The transform hint might have changed for some layers
2222 // (either because a display has changed, or because a layer
2223 // as changed).
2224 //
2225 // Walk through all the layers in currentLayers,
2226 // and update their transform hint.
2227 //
2228 // If a layer is visible only on a single display, then that
2229 // display is used to calculate the hint, otherwise we use the
2230 // default display.
2231 //
2232 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2233 // the hint is set before we acquire a buffer from the surface texture.
2234 //
2235 // NOTE: layer transactions have taken place already, so we use their
2236 // drawing state. However, SurfaceFlinger's own transaction has not
2237 // happened yet, so we must use the current state layer list
2238 // (soon to become the drawing state list).
2239 //
2240 sp<const DisplayDevice> disp;
2241 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002242 bool first = true;
2243 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002244 // NOTE: we rely on the fact that layers are sorted by
2245 // layerStack first (so we don't have to traverse the list
2246 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002247 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002248 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002249 currentlayerStack = layerStack;
2250 // figure out if this layerstack is mirrored
2251 // (more than one display) if so, pick the default display,
2252 // if not, pick the only display it's on.
2253 disp.clear();
2254 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2255 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002256 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002257 if (disp == NULL) {
2258 disp = hw;
2259 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002260 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002261 break;
2262 }
2263 }
2264 }
2265 }
Chet Haase91d25932013-04-11 15:24:55 -07002266 if (disp == NULL) {
2267 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2268 // redraw after transform hint changes. See bug 8508397.
2269
2270 // could be null when this layer is using a layerStack
2271 // that is not visible on any display. Also can occur at
2272 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002273 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002274 }
Chet Haase91d25932013-04-11 15:24:55 -07002275 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002276
2277 first = false;
2278 });
Mathias Agopian84300952012-11-21 16:02:13 -08002279 }
2280
2281
Mathias Agopian3559b072012-08-15 13:46:03 -07002282 /*
2283 * Perform our own transaction if needed
2284 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002285
2286 if (mLayersAdded) {
2287 mLayersAdded = false;
2288 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002289 mVisibleRegionsDirty = true;
2290 }
2291
2292 // some layers might have been removed, so
2293 // we need to update the regions they're exposing.
2294 if (mLayersRemoved) {
2295 mLayersRemoved = false;
2296 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002297 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002298 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002299 // this layer is not visible anymore
2300 // TODO: we could traverse the tree from front to back and
2301 // compute the actual visible region
2302 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002303 Region visibleReg;
2304 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002305 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002306 }
Robert Carr2047fae2016-11-28 14:09:09 -08002307 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308 }
2309
2310 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002311
2312 updateCursorAsync();
2313}
2314
2315void SurfaceFlinger::updateCursorAsync()
2316{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002317 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2318 auto& displayDevice = mDisplays[displayId];
2319 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002320 continue;
2321 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002322
2323 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2324 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002325 }
2326 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002327}
2328
2329void SurfaceFlinger::commitTransaction()
2330{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002331 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002332 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002333 for (const auto& l : mLayersPendingRemoval) {
2334 recordBufferingStats(l->getName().string(),
2335 l->getOccupancyHistory(true));
2336 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002337 }
2338 mLayersPendingRemoval.clear();
2339 }
2340
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002341 // If this transaction is part of a window animation then the next frame
2342 // we composite should be considered an animation as well.
2343 mAnimCompositionPending = mAnimTransactionPending;
2344
Mathias Agopian4fec8732012-06-29 14:12:52 -07002345 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002346 mDrawingState.traverseInZOrder([](Layer* layer) {
2347 layer->commitChildList();
2348 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002349 mTransactionPending = false;
2350 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002351 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002352}
2353
Chia-I Wuab0c3192017-08-01 11:29:00 -07002354void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002355 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356{
Mathias Agopian841cde52012-03-01 15:44:37 -08002357 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002358 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002359
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 Region aboveOpaqueLayers;
2361 Region aboveCoveredLayers;
2362 Region dirty;
2363
Mathias Agopian87baae12012-07-31 12:38:26 -07002364 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365
Robert Carr2047fae2016-11-28 14:09:09 -08002366 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002368 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Jesse Hall01e29052013-02-19 16:13:35 -08002370 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002371 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002372 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002373
Mathias Agopianab028732010-03-16 16:41:46 -07002374 /*
2375 * opaqueRegion: area of a surface that is fully opaque.
2376 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002377 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002378
2379 /*
2380 * visibleRegion: area of a surface that is visible on screen
2381 * and not fully transparent. This is essentially the layer's
2382 * footprint minus the opaque regions above it.
2383 * Areas covered by a translucent surface are considered visible.
2384 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002385 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002386
2387 /*
2388 * coveredRegion: area of a surface that is covered by all
2389 * visible regions above it (which includes the translucent areas).
2390 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002392
Jesse Halla8026d22012-09-25 13:25:04 -07002393 /*
2394 * transparentRegion: area of a surface that is hinted to be completely
2395 * transparent. This is only used to tell when the layer has no visible
2396 * non-transparent regions and can be removed from the layer list. It
2397 * does not affect the visibleRegion of this layer or any layers
2398 * beneath it. The hint may not be correct if apps don't respect the
2399 * SurfaceView restrictions (which, sadly, some don't).
2400 */
2401 Region transparentRegion;
2402
Mathias Agopianab028732010-03-16 16:41:46 -07002403
2404 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002405 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002406 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002407 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002408 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002409 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002410 if (!visibleRegion.isEmpty()) {
2411 // Remove the transparent area from the visible region
2412 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002413 if (tr.preserveRects()) {
2414 // transform the transparent region
2415 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002416 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002417 // transformation too complex, can't do the
2418 // transparent region optimization.
2419 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002420 }
Mathias Agopianab028732010-03-16 16:41:46 -07002421 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422
Mathias Agopianab028732010-03-16 16:41:46 -07002423 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002424 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002425 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002426 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2427 // the opaque region is the layer's footprint
2428 opaqueRegion = visibleRegion;
2429 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002430 }
2431 }
2432
Mathias Agopianab028732010-03-16 16:41:46 -07002433 // Clip the covered region to the visible region
2434 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2435
2436 // Update aboveCoveredLayers for next (lower) layer
2437 aboveCoveredLayers.orSelf(visibleRegion);
2438
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002439 // subtract the opaque region covered by the layers above us
2440 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002441
2442 // compute this layer's dirty region
2443 if (layer->contentDirty) {
2444 // we need to invalidate the whole region
2445 dirty = visibleRegion;
2446 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002447 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 layer->contentDirty = false;
2449 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002450 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002451 * the exposed region consists of two components:
2452 * 1) what's VISIBLE now and was COVERED before
2453 * 2) what's EXPOSED now less what was EXPOSED before
2454 *
2455 * note that (1) is conservative, we start with the whole
2456 * visible region but only keep what used to be covered by
2457 * something -- which mean it may have been exposed.
2458 *
2459 * (2) handles areas that were not covered by anything but got
2460 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002461 */
Mathias Agopianab028732010-03-16 16:41:46 -07002462 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002463 const Region oldVisibleRegion = layer->visibleRegion;
2464 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002465 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2466 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002467 }
2468 dirty.subtractSelf(aboveOpaqueLayers);
2469
2470 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002471 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002472
Mathias Agopianab028732010-03-16 16:41:46 -07002473 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002474 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002475
Jesse Halla8026d22012-09-25 13:25:04 -07002476 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477 layer->setVisibleRegion(visibleRegion);
2478 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002479 layer->setVisibleNonTransparentRegion(
2480 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002481 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482
Mathias Agopian87baae12012-07-31 12:38:26 -07002483 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002484}
2485
Chia-I Wuab0c3192017-08-01 11:29:00 -07002486void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002487 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002488 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002489 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002490 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002491 }
2492 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002493}
2494
Dan Stoza6b9454d2014-11-07 16:00:59 -08002495bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002497 ALOGV("handlePageFlip");
2498
Brian Andersond6927fb2016-07-23 23:37:30 -07002499 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500
Mathias Agopian4fec8732012-06-29 14:12:52 -07002501 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002502 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002503 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002504
2505 // Store the set of layers that need updates. This set must not change as
2506 // buffers are being latched, as this could result in a deadlock.
2507 // Example: Two producers share the same command stream and:
2508 // 1.) Layer 0 is latched
2509 // 2.) Layer 0 gets a new frame
2510 // 2.) Layer 1 gets a new frame
2511 // 3.) Layer 1 is latched.
2512 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2513 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002514 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002515 if (layer->hasQueuedFrame()) {
2516 frameQueued = true;
2517 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002518 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002519 } else {
2520 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002521 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002522 } else {
2523 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002524 }
Robert Carr2047fae2016-11-28 14:09:09 -08002525 });
2526
Dan Stoza9e56aa02015-11-02 13:00:03 -08002527 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002528 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002529 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002530 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002531 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002532 newDataLatched = true;
2533 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002534 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002535
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002536 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002537
2538 // If we will need to wake up at some time in the future to deal with a
2539 // queued frame that shouldn't be displayed during this vsync period, wake
2540 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002541 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002542 signalLayerUpdate();
2543 }
2544
2545 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002546 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002547}
2548
Mathias Agopianad456f92011-01-13 17:53:01 -08002549void SurfaceFlinger::invalidateHwcGeometry()
2550{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002551 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002552}
2553
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002554
Fabien Sanglard830b8472016-11-30 16:35:58 -08002555void SurfaceFlinger::doDisplayComposition(
2556 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002557 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558{
Dan Stoza71433162014-02-04 16:22:36 -08002559 // We only need to actually compose the display if:
2560 // 1) It is being handled by hardware composer, which may need this to
2561 // keep its virtual display state machine in sync, or
2562 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002563 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002564 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002565 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002566 return;
2567 }
2568
Dan Stoza9e56aa02015-11-02 13:00:03 -08002569 ALOGV("doDisplayComposition");
2570
Mathias Agopian87baae12012-07-31 12:38:26 -07002571 Region dirtyRegion(inDirtyRegion);
2572
Mathias Agopianb8a55602009-06-26 19:06:36 -07002573 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002574 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575
Fabien Sanglard830b8472016-11-30 16:35:58 -08002576 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002577 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002578 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2579 // takes a rectangle, we must make sure to update that whole
2580 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002581 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002582 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002583 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002584 // We need to redraw the rectangle that will be updated
2585 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002586 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002587 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002588 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002589 } else {
2590 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002591 dirtyRegion.set(displayDevice->bounds());
2592 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593 }
2594 }
2595
Fabien Sanglard830b8472016-11-30 16:35:58 -08002596 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002597
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002598 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002599 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002600
2601 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002602 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603}
2604
Dan Stoza9e56aa02015-11-02 13:00:03 -08002605bool SurfaceFlinger::doComposeSurfaces(
2606 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002607{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002608 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002609
Dan Stoza9e56aa02015-11-02 13:00:03 -08002610 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002611
2612 mat4 oldColorMatrix;
2613 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2614 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2615 if (applyColorMatrix) {
2616 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2617 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2618 }
2619
Dan Stoza9e56aa02015-11-02 13:00:03 -08002620 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2621 if (hasClientComposition) {
2622 ALOGV("hasClientComposition");
2623
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002624#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002625 mRenderEngine->setWideColor(
2626 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2627 mRenderEngine->setColorMode(mForceNativeColorMode ?
2628 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002629#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002630 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002631 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002633 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002634
2635 // |mStateLock| not needed as we are on the main thread
2636 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002637 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2638 }
2639 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002640 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002641
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002642 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2644 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002645 // when using overlays, we assume a fully transparent framebuffer
2646 // NOTE: we could reduce how much we need to clear, for instance
2647 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002648 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002649 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002650 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002651 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002652 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002653 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002654
2655 // we remove the scissor part
2656 // we're left with the letterbox region
2657 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002658 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002659
2660 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002662
2663 // but limit it to the dirty region
2664 region.andSelf(dirty);
2665
Mathias Agopianb9494d52012-04-18 02:28:45 -07002666 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002667 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002668 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002669 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002670 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002671 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002672
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002674 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002675 // scissor on the main display. It should never be needed
2676 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002677 const Rect& bounds(displayDevice->getBounds());
2678 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002679 if (scissor != bounds) {
2680 // scissor doesn't match the screen's dimensions, so we
2681 // need to clear everything outside of it and enable
2682 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002683
Mathias Agopianf45c5102012-10-24 16:29:17 -07002684 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002685 const uint32_t height = displayDevice->getHeight();
2686 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002687 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002688 }
2689 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002690 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002691
Mathias Agopian85d751c2012-08-29 16:59:24 -07002692 /*
2693 * and then, render the layers targeted at the framebuffer
2694 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002695
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 ALOGV("Rendering client layers");
2697 const Transform& displayTransform = displayDevice->getTransform();
2698 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002699 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002700 bool firstLayer = true;
2701 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2702 const Region clip(dirty.intersect(
2703 displayTransform.transform(layer->visibleRegion)));
2704 ALOGV("Layer: %s", layer->getName().string());
2705 ALOGV(" Composition type: %s",
2706 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002707 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 switch (layer->getCompositionType(hwcId)) {
2709 case HWC2::Composition::Cursor:
2710 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002711 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002713 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002714 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2715 layer->isOpaque(state) && (state.alpha == 1.0f)
2716 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002717 // never clear the very first layer since we're
2718 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002719 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002720 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002721 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002722 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002723 case HWC2::Composition::Client: {
2724 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002725 break;
2726 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002727 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002728 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002729 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 } else {
2731 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002732 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002733 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002734 }
2735 } else {
2736 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002737 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002738 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002740 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002742 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002743 }
2744 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002745
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002746 if (applyColorMatrix) {
2747 getRenderEngine().setupColorTransform(oldColorMatrix);
2748 }
2749
Mathias Agopianf45c5102012-10-24 16:29:17 -07002750 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002751 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002752 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753}
2754
Fabien Sanglard830b8472016-11-30 16:35:58 -08002755void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2756 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002757 RenderEngine& engine(getRenderEngine());
2758 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759}
2760
Dan Stoza7d89d062015-04-30 13:29:25 -07002761status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002762 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002763 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 const sp<Layer>& lbc,
2765 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002766{
Dan Stoza7d89d062015-04-30 13:29:25 -07002767 // add this layer to the current state list
2768 {
2769 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002771 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2772 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002773 return NO_MEMORY;
2774 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 if (parent == nullptr) {
2776 mCurrentState.layersSortedByZ.add(lbc);
2777 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002778 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2779 ALOGE("addClientLayer called with a removed parent");
2780 return NAME_NOT_FOUND;
2781 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002782 parent->addChild(lbc);
2783 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002784
Dan Stoza7d89d062015-04-30 13:29:25 -07002785 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 mLayersAdded = true;
2787 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002788 }
2789
Mathias Agopian96f08192010-06-02 23:28:45 -07002790 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002791 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002792
Dan Stoza7d89d062015-04-30 13:29:25 -07002793 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002794}
2795
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002796status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002797 Mutex::Autolock _l(mStateLock);
2798
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002800 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002801 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002802 if (topLevelOnly) {
2803 return NO_ERROR;
2804 }
2805
Chia-I Wu98f1c102017-05-30 14:54:08 -07002806 sp<Layer> ancestor = p;
2807 while (ancestor->getParent() != nullptr) {
2808 ancestor = ancestor->getParent();
2809 }
2810 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2811 ALOGE("removeLayer called with a layer whose parent has been removed");
2812 return NAME_NOT_FOUND;
2813 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002814
2815 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002816 } else {
2817 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002818 }
2819
Robert Carr136e2f62017-02-08 17:54:29 -08002820 // As a matter of normal operation, the LayerCleaner will produce a second
2821 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2822 // so we will succeed in promoting it, but it's already been removed
2823 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2824 // otherwise something has gone wrong and we are leaking the layer.
2825 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002826 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2827 layer->getName().string(),
2828 (p != nullptr) ? p->getName().string() : "no-parent");
2829 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002830 } else if (index < 0) {
2831 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002832 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833
Chia-I Wuc6657022017-08-15 11:18:17 -07002834 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 mLayersPendingRemoval.add(layer);
2836 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002837 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002838 setTransactionFlags(eTransactionNeeded);
2839 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840}
2841
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002842uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002843 return android_atomic_release_load(&mTransactionFlags);
2844}
2845
Mathias Agopian3f844832013-08-07 21:24:32 -07002846uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2848}
2849
Mathias Agopian3f844832013-08-07 21:24:32 -07002850uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2852 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002853 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854 }
2855 return old;
2856}
2857
Mathias Agopian8b33f032012-07-24 20:43:54 -07002858void SurfaceFlinger::setTransactionState(
2859 const Vector<ComposerState>& state,
2860 const Vector<DisplayState>& displays,
2861 uint32_t flags)
2862{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002863 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002864 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002865 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002866
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002867 if (flags & eAnimation) {
2868 // For window updates that are part of an animation we must wait for
2869 // previous animation "frames" to be handled.
2870 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002871 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002872 if (CC_UNLIKELY(err != NO_ERROR)) {
2873 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002874 // caller after a few seconds.
2875 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2876 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002877 mAnimTransactionPending = false;
2878 break;
2879 }
2880 }
2881 }
2882
Mathias Agopiane57f2922012-08-09 16:29:12 -07002883 size_t count = displays.size();
2884 for (size_t i=0 ; i<count ; i++) {
2885 const DisplayState& s(displays[i]);
2886 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002887 }
2888
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002890 for (size_t i=0 ; i<count ; i++) {
2891 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002892 // Here we need to check that the interface we're given is indeed
2893 // one of our own. A malicious client could give us a NULL
2894 // IInterface, or one of its own or even one of our own but a
2895 // different type. All these situations would cause us to crash.
2896 //
2897 // NOTE: it would be better to use RTTI as we could directly check
2898 // that we have a Client*. however, RTTI is disabled in Android.
2899 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002900 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002901 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002902 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002903 sp<Client> client( static_cast<Client *>(s.client.get()) );
2904 transactionFlags |= setClientStateLocked(client, s.state);
2905 }
2906 }
2907 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002908 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002909
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002910 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2911 // anyway. This can be used as a flush mechanism for previous async transactions.
2912 // Empty animation transaction can be used to simulate back-pressure, so also force a
2913 // transaction for empty animation transactions.
2914 if (transactionFlags == 0 &&
2915 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002916 transactionFlags = eTransactionNeeded;
2917 }
2918
Mathias Agopian386aa982011-11-07 21:58:03 -08002919 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002920 if (mInterceptor.isEnabled()) {
2921 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2922 }
Irvel468051e2016-06-13 16:44:44 -07002923
Mathias Agopian386aa982011-11-07 21:58:03 -08002924 // this triggers the transaction
2925 setTransactionFlags(transactionFlags);
2926
2927 // if this is a synchronous transaction, wait for it to take effect
2928 // before returning.
2929 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002930 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002931 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002932 if (flags & eAnimation) {
2933 mAnimTransactionPending = true;
2934 }
2935 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002936 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2937 if (CC_UNLIKELY(err != NO_ERROR)) {
2938 // just in case something goes wrong in SF, return to the
2939 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002940 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2941 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002942 break;
2943 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002944 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 }
2946}
2947
Mathias Agopiane57f2922012-08-09 16:29:12 -07002948uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2949{
Jesse Hall9a143922012-10-04 16:29:19 -07002950 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2951 if (dpyIdx < 0)
2952 return 0;
2953
Mathias Agopiane57f2922012-08-09 16:29:12 -07002954 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002955 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002956 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002957 const uint32_t what = s.what;
2958 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002959 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002960 disp.surface = s.surface;
2961 flags |= eDisplayTransactionNeeded;
2962 }
2963 }
2964 if (what & DisplayState::eLayerStackChanged) {
2965 if (disp.layerStack != s.layerStack) {
2966 disp.layerStack = s.layerStack;
2967 flags |= eDisplayTransactionNeeded;
2968 }
2969 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002970 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002971 if (disp.orientation != s.orientation) {
2972 disp.orientation = s.orientation;
2973 flags |= eDisplayTransactionNeeded;
2974 }
2975 if (disp.frame != s.frame) {
2976 disp.frame = s.frame;
2977 flags |= eDisplayTransactionNeeded;
2978 }
2979 if (disp.viewport != s.viewport) {
2980 disp.viewport = s.viewport;
2981 flags |= eDisplayTransactionNeeded;
2982 }
2983 }
Michael Lentine47e45402014-07-18 15:34:25 -07002984 if (what & DisplayState::eDisplaySizeChanged) {
2985 if (disp.width != s.width) {
2986 disp.width = s.width;
2987 flags |= eDisplayTransactionNeeded;
2988 }
2989 if (disp.height != s.height) {
2990 disp.height = s.height;
2991 flags |= eDisplayTransactionNeeded;
2992 }
2993 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002994 }
2995 return flags;
2996}
2997
2998uint32_t SurfaceFlinger::setClientStateLocked(
2999 const sp<Client>& client,
3000 const layer_state_t& s)
3001{
3002 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08003003 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07003004 if (layer != 0) {
3005 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07003006 bool geometryAppliesWithResize =
3007 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003009 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003010 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07003011 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003012 }
3013 if (what & layer_state_t::eLayerChanged) {
3014 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07003015 const auto& p = layer->getParent();
3016 if (p == nullptr) {
3017 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3018 if (layer->setLayer(s.z) && idx >= 0) {
3019 mCurrentState.layersSortedByZ.removeAt(idx);
3020 mCurrentState.layersSortedByZ.add(layer);
3021 // we need traversal (state changed)
3022 // AND transaction (list changed)
3023 flags |= eTransactionNeeded|eTraversalNeeded;
3024 }
3025 } else {
3026 if (p->setChildLayer(layer, s.z)) {
3027 flags |= eTransactionNeeded|eTraversalNeeded;
3028 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003029 }
3030 }
Robert Carrdb66e622017-04-10 16:55:57 -07003031 if (what & layer_state_t::eRelativeLayerChanged) {
3032 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
3033 flags |= eTransactionNeeded|eTraversalNeeded;
3034 }
3035 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003036 if (what & layer_state_t::eSizeChanged) {
3037 if (layer->setSize(s.w, s.h)) {
3038 flags |= eTraversalNeeded;
3039 }
3040 }
3041 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003042 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003043 flags |= eTraversalNeeded;
3044 }
3045 if (what & layer_state_t::eMatrixChanged) {
3046 if (layer->setMatrix(s.matrix))
3047 flags |= eTraversalNeeded;
3048 }
3049 if (what & layer_state_t::eTransparentRegionChanged) {
3050 if (layer->setTransparentRegionHint(s.transparentRegion))
3051 flags |= eTraversalNeeded;
3052 }
Dan Stoza23116082015-06-18 14:58:39 -07003053 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003054 if (layer->setFlags(s.flags, s.mask))
3055 flags |= eTraversalNeeded;
3056 }
3057 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003058 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003059 flags |= eTraversalNeeded;
3060 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003061 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003062 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003063 flags |= eTraversalNeeded;
3064 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003065 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 // We only allow setting layer stacks for top level layers,
3068 // everything else inherits layer stack from its parent.
3069 if (layer->hasParent()) {
3070 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3071 layer->getName().string());
3072 } else if (idx < 0) {
3073 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3074 "that also does not appear in the top level layer list. Something"
3075 " has gone wrong.", layer->getName().string());
3076 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003077 mCurrentState.layersSortedByZ.removeAt(idx);
3078 mCurrentState.layersSortedByZ.add(layer);
3079 // we need traversal (state changed)
3080 // AND transaction (list changed)
3081 flags |= eTransactionNeeded|eTraversalNeeded;
3082 }
3083 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003084 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003085 if (s.barrierHandle != nullptr) {
3086 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3087 } else if (s.barrierGbp != nullptr) {
3088 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3089 if (authenticateSurfaceTextureLocked(gbp)) {
3090 const auto& otherLayer =
3091 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3092 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3093 } else {
3094 ALOGE("Attempt to defer transaction to to an"
3095 " unrecognized GraphicBufferProducer");
3096 }
3097 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003098 // We don't trigger a traversal here because if no other state is
3099 // changed, we don't want this to cause any more work
3100 }
Robert Carr1db73f62016-12-21 12:58:51 -08003101 if (what & layer_state_t::eReparentChildren) {
3102 if (layer->reparentChildren(s.reparentHandle)) {
3103 flags |= eTransactionNeeded|eTraversalNeeded;
3104 }
3105 }
Robert Carr9524cb32017-02-13 11:32:32 -08003106 if (what & layer_state_t::eDetachChildren) {
3107 layer->detachChildren();
3108 }
Robert Carrc3574f72016-03-24 12:19:32 -07003109 if (what & layer_state_t::eOverrideScalingModeChanged) {
3110 layer->setOverrideScalingMode(s.overrideScalingMode);
3111 // We don't trigger a traversal here because if no other state is
3112 // changed, we don't want this to cause any more work
3113 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003114 }
3115 return flags;
3116}
3117
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003118status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003119 const String8& name,
3120 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003121 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003122 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3123 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003125 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003126 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003127 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003128 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003129 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003130
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003131 status_t result = NO_ERROR;
3132
3133 sp<Layer> layer;
3134
Cody Northropbc755282017-03-31 12:00:08 -06003135 String8 uniqueName = getUniqueLayerName(name);
3136
Mathias Agopian3165cc22012-08-08 19:42:09 -07003137 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3138 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003139 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003140 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003141 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003142 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003143 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003144 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003145 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003146 handle, gbp, &layer);
3147 break;
3148 default:
3149 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150 break;
3151 }
3152
Dan Stoza7d89d062015-04-30 13:29:25 -07003153 if (result != NO_ERROR) {
3154 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003156
Chia-I Wuab0c3192017-08-01 11:29:00 -07003157 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3158 // TODO b/64227542
3159 if (windowType == 441731) {
3160 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3161 layer->setPrimaryDisplayOnly();
3162 }
3163
Albert Chaulk479c60c2017-01-27 14:21:34 -05003164 layer->setInfo(windowType, ownerUid);
3165
Robert Carr1f0a16a2016-10-24 16:27:39 -07003166 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003167 if (result != NO_ERROR) {
3168 return result;
3169 }
Irvelffc9efc2016-07-27 15:16:37 -07003170 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003171
3172 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003173 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003174}
3175
Cody Northropbc755282017-03-31 12:00:08 -06003176String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3177{
3178 bool matchFound = true;
3179 uint32_t dupeCounter = 0;
3180
3181 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3182 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3183
3184 // Loop over layers until we're sure there is no matching name
3185 while (matchFound) {
3186 matchFound = false;
3187 mDrawingState.traverseInZOrder([&](Layer* layer) {
3188 if (layer->getName() == uniqueName) {
3189 matchFound = true;
3190 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3191 }
3192 });
3193 }
3194
3195 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3196
3197 return uniqueName;
3198}
3199
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003200status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3201 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3202 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203{
3204 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003205 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 case PIXEL_FORMAT_TRANSPARENT:
3207 case PIXEL_FORMAT_TRANSLUCENT:
3208 format = PIXEL_FORMAT_RGBA_8888;
3209 break;
3210 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003211 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 break;
3213 }
3214
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003215 *outLayer = new Layer(this, client, name, w, h, flags);
3216 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3217 if (err == NO_ERROR) {
3218 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003219 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003221
3222 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3223 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224}
3225
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003226status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3227 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3228 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003230 *outLayer = new LayerDim(this, client, name, w, h, flags);
3231 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003232 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003233 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003234}
3235
Mathias Agopianac9fa422013-02-11 16:40:36 -08003236status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237{
Robert Carr9524cb32017-02-13 11:32:32 -08003238 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003239 status_t err = NO_ERROR;
3240 sp<Layer> l(client->getLayerUser(handle));
3241 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003242 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003243 err = removeLayer(l);
3244 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3245 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003246 }
3247 return err;
3248}
3249
Mathias Agopian13127d82013-03-05 17:47:11 -08003250status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003251{
Mathias Agopian67106042013-03-14 19:18:13 -07003252 // called by ~LayerCleaner() when all references to the IBinder (handle)
3253 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003254 sp<Layer> l = layer.promote();
3255 if (l == nullptr) {
3256 // The layer has already been removed, carry on
3257 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003258 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003259 // If we have a parent, then we can continue to live as long as it does.
3260 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003261}
3262
Mathias Agopianb60314a2012-04-10 22:09:54 -07003263// ---------------------------------------------------------------------------
3264
Andy McFadden13a082e2012-08-24 10:16:42 -07003265void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003266 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003267 Vector<ComposerState> state;
3268 Vector<DisplayState> displays;
3269 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003270 d.what = DisplayState::eDisplayProjectionChanged |
3271 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003272 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003273 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003274 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003275 d.frame.makeInvalid();
3276 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003277 d.width = 0;
3278 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003279 displays.add(d);
3280 setTransactionState(state, displays, 0);
Steven Thomasd7f49c52017-07-26 18:48:28 -07003281 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3282 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003283
Dan Stoza9e56aa02015-11-02 13:00:03 -08003284 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3285 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003286 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003287
Brian Andersond0010582017-03-07 13:20:31 -08003288 // Use phase of 0 since phase is not known.
3289 // Use latency of 0, which will snap to the ideal latency.
3290 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003291}
3292
3293void SurfaceFlinger::initializeDisplays() {
3294 class MessageScreenInitialized : public MessageBase {
3295 SurfaceFlinger* flinger;
3296 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003297 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003298 virtual bool handler() {
3299 flinger->onInitializeDisplays();
3300 return true;
3301 }
3302 };
3303 sp<MessageBase> msg = new MessageScreenInitialized(this);
3304 postMessageAsync(msg); // we may be called from main thread, use async message
3305}
3306
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003307void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasd7f49c52017-07-26 18:48:28 -07003308 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003309 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3310 this);
3311 int32_t type = hw->getDisplayType();
3312 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003313
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003314 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003315 return;
3316 }
3317
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003318 hw->setPowerMode(mode);
3319 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3320 ALOGW("Trying to set power mode for virtual display");
3321 return;
3322 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003323
Irvelffc9efc2016-07-27 15:16:37 -07003324 if (mInterceptor.isEnabled()) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003325 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003326 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3327 if (idx < 0) {
3328 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3329 return;
3330 }
3331 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3332 }
3333
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003334 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003335 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003336 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003337 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3338 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003339 // FIXME: eventthread only knows about the main display right now
3340 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003341 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003342 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003343
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003344 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003345 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003346 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003347
3348 struct sched_param param = {0};
3349 param.sched_priority = 1;
3350 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3351 ALOGW("Couldn't set SCHED_FIFO on display on");
3352 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003354 // Turn off the display
3355 struct sched_param param = {0};
3356 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3357 ALOGW("Couldn't set SCHED_OTHER on display off");
3358 }
3359
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003360 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003361 disableHardwareVsync(true); // also cancels any in-progress resync
3362
Mathias Agopiancde87a32012-09-13 14:09:01 -07003363 // FIXME: eventthread only knows about the main display right now
3364 mEventThread->onScreenReleased();
3365 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003366
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003367 getHwComposer().setPowerMode(type, mode);
3368 mVisibleRegionsDirty = true;
3369 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003370 } else if (mode == HWC_POWER_MODE_DOZE ||
3371 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003372 // Update display while dozing
3373 getHwComposer().setPowerMode(type, mode);
3374 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3375 // FIXME: eventthread only knows about the main display right now
3376 mEventThread->onScreenAcquired();
3377 resyncToHardwareVsync(true);
3378 }
3379 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3380 // Leave display going to doze
3381 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3382 disableHardwareVsync(true); // also cancels any in-progress resync
3383 // FIXME: eventthread only knows about the main display right now
3384 mEventThread->onScreenReleased();
3385 }
3386 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003387 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003388 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003389 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003390 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003391}
3392
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003393void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3394 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003395 SurfaceFlinger& mFlinger;
3396 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003397 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003398 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003399 MessageSetPowerMode(SurfaceFlinger& flinger,
3400 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3401 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003402 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003403 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003404 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003405 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003406 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003407 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003408 ALOGW("Attempt to set power mode = %d for virtual display",
3409 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003410 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003411 mFlinger.setPowerModeInternal(
3412 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003413 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003414 return true;
3415 }
3416 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003417 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003418 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003419}
3420
3421// ---------------------------------------------------------------------------
3422
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003423status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3424{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003425 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003426
Mathias Agopianbd115332013-04-18 16:41:04 -07003427 IPCThreadState* ipc = IPCThreadState::self();
3428 const int pid = ipc->getCallingPid();
3429 const int uid = ipc->getCallingUid();
3430 if ((uid != AID_SHELL) &&
3431 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003433 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003434 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003435 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003436 // (this would indicate SF is stuck, but we want to be able to
3437 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003438 status_t err = mStateLock.timedLock(s2ns(1));
3439 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003440 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003441 result.appendFormat(
3442 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3443 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003444 }
3445
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003446 bool dumpAll = true;
3447 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003448 size_t numArgs = args.size();
3449 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003450 if ((index < numArgs) &&
3451 (args[index] == String16("--list"))) {
3452 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003453 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003454 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003455 }
3456
3457 if ((index < numArgs) &&
3458 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003459 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003460 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003461 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003462 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003463
3464 if ((index < numArgs) &&
3465 (args[index] == String16("--latency-clear"))) {
3466 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003467 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003468 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003469 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003470
3471 if ((index < numArgs) &&
3472 (args[index] == String16("--dispsync"))) {
3473 index++;
3474 mPrimaryDispSync.dump(result);
3475 dumpAll = false;
3476 }
Dan Stozab90cf072015-03-05 11:05:59 -08003477
3478 if ((index < numArgs) &&
3479 (args[index] == String16("--static-screen"))) {
3480 index++;
3481 dumpStaticScreenStats(result);
3482 dumpAll = false;
3483 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003484
3485 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003486 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003487 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003488 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003489 dumpAll = false;
3490 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003491
3492 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3493 index++;
3494 dumpWideColorInfo(result);
3495 dumpAll = false;
3496 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003498
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003499 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003500 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003501 }
3502
Mathias Agopian9795c422009-08-26 16:36:26 -07003503 if (locked) {
3504 mStateLock.unlock();
3505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 }
3507 write(fd, result.string(), result.size());
3508 return NO_ERROR;
3509}
3510
Dan Stozac7014012014-02-14 15:03:43 -08003511void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3512 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003513{
Robert Carr2047fae2016-11-28 14:09:09 -08003514 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003515 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003516 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003517}
3518
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003519void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003520 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003521{
3522 String8 name;
3523 if (index < args.size()) {
3524 name = String8(args[index]);
3525 index++;
3526 }
3527
Dan Stoza9e56aa02015-11-02 13:00:03 -08003528 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3529 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003530 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003531
3532 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003533 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003534 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003535 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003536 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003537 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003538 }
Robert Carr2047fae2016-11-28 14:09:09 -08003539 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003540 }
3541}
3542
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003543void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003544 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003545{
3546 String8 name;
3547 if (index < args.size()) {
3548 name = String8(args[index]);
3549 index++;
3550 }
3551
Robert Carr2047fae2016-11-28 14:09:09 -08003552 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003553 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003554 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003555 }
Robert Carr2047fae2016-11-28 14:09:09 -08003556 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003557
Svetoslavd85084b2014-03-20 10:28:31 -07003558 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003559}
3560
Jamie Gennis6547ff42013-07-16 20:12:42 -07003561// This should only be called from the main thread. Otherwise it would need
3562// the lock and should use mCurrentState rather than mDrawingState.
3563void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003564 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003565 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003566 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003567
3568 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3569}
3570
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003571void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003572{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003573 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003574 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3575
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003576 if (isLayerTripleBufferingDisabled())
3577 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003578
3579 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003580 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003581 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003582 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003583 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3584 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003585 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003586}
3587
Dan Stozab90cf072015-03-05 11:05:59 -08003588void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3589{
3590 result.appendFormat("Static screen stats:\n");
3591 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3592 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3593 float percent = 100.0f *
3594 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3595 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3596 b + 1, bucketTimeSec, percent);
3597 }
3598 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3599 float percent = 100.0f *
3600 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3601 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3602 NUM_BUCKETS - 1, bucketTimeSec, percent);
3603}
3604
Dan Stozae77c7662016-05-13 11:37:28 -07003605void SurfaceFlinger::recordBufferingStats(const char* layerName,
3606 std::vector<OccupancyTracker::Segment>&& history) {
3607 Mutex::Autolock lock(mBufferingStatsMutex);
3608 auto& stats = mBufferingStats[layerName];
3609 for (const auto& segment : history) {
3610 if (!segment.usedThirdBuffer) {
3611 stats.twoBufferTime += segment.totalTime;
3612 }
3613 if (segment.occupancyAverage < 1.0f) {
3614 stats.doubleBufferedTime += segment.totalTime;
3615 } else if (segment.occupancyAverage < 2.0f) {
3616 stats.tripleBufferedTime += segment.totalTime;
3617 }
3618 ++stats.numSegments;
3619 stats.totalTime += segment.totalTime;
3620 }
3621}
3622
Brian Andersond6927fb2016-07-23 23:37:30 -07003623void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3624 result.appendFormat("Layer frame timestamps:\n");
3625
3626 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3627 const size_t count = currentLayers.size();
3628 for (size_t i=0 ; i<count ; i++) {
3629 currentLayers[i]->dumpFrameEvents(result);
3630 }
3631}
3632
Dan Stozae77c7662016-05-13 11:37:28 -07003633void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3634 result.append("Buffering stats:\n");
3635 result.append(" [Layer name] <Active time> <Two buffer> "
3636 "<Double buffered> <Triple buffered>\n");
3637 Mutex::Autolock lock(mBufferingStatsMutex);
3638 typedef std::tuple<std::string, float, float, float> BufferTuple;
3639 std::map<float, BufferTuple, std::greater<float>> sorted;
3640 for (const auto& statsPair : mBufferingStats) {
3641 const char* name = statsPair.first.c_str();
3642 const BufferingStats& stats = statsPair.second;
3643 if (stats.numSegments == 0) {
3644 continue;
3645 }
3646 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3647 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3648 stats.totalTime;
3649 float doubleBufferRatio = static_cast<float>(
3650 stats.doubleBufferedTime) / stats.totalTime;
3651 float tripleBufferRatio = static_cast<float>(
3652 stats.tripleBufferedTime) / stats.totalTime;
3653 sorted.insert({activeTime, {name, twoBufferRatio,
3654 doubleBufferRatio, tripleBufferRatio}});
3655 }
3656 for (const auto& sortedPair : sorted) {
3657 float activeTime = sortedPair.first;
3658 const BufferTuple& values = sortedPair.second;
3659 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3660 std::get<0>(values).c_str(), activeTime,
3661 std::get<1>(values), std::get<2>(values),
3662 std::get<3>(values));
3663 }
3664 result.append("\n");
3665}
3666
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003667void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3668 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003669 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003670
3671 // TODO: print out if wide-color mode is active or not
3672
3673 for (size_t d = 0; d < mDisplays.size(); d++) {
3674 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3675 int32_t hwcId = displayDevice->getHwcDisplayId();
3676 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3677 continue;
3678 }
3679
3680 result.appendFormat("Display %d color modes:\n", hwcId);
3681 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3682 for (auto&& mode : modes) {
3683 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3684 }
3685
3686 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3687 result.appendFormat(" Current color mode: %s (%d)\n",
3688 decodeColorMode(currentMode).c_str(), currentMode);
3689 }
3690 result.append("\n");
3691}
3692
Mathias Agopian74d211a2013-04-22 16:55:35 +02003693void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3694 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003695{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003696 bool colorize = false;
3697 if (index < args.size()
3698 && (args[index] == String16("--color"))) {
3699 colorize = true;
3700 index++;
3701 }
3702
3703 Colorizer colorizer(colorize);
3704
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003705 // figure out if we're stuck somewhere
3706 const nsecs_t now = systemTime();
3707 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3708 const nsecs_t inTransaction(mDebugInTransaction);
3709 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3710 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3711
3712 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003713 * Dump library configuration.
3714 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003715
3716 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003717 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003718 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003719 appendSfConfigString(result);
3720 appendUiConfigString(result);
3721 appendGuiConfigString(result);
3722 result.append("\n");
3723
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003724 result.append("\nWide-Color information:\n");
3725 dumpWideColorInfo(result);
3726
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003727 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003728 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003729 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003730 result.append(SyncFeatures::getInstance().toString());
3731 result.append("\n");
3732
Dan Stoza9e56aa02015-11-02 13:00:03 -08003733 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3734
Andy McFadden41d67d72014-04-25 16:58:34 -07003735 colorizer.bold(result);
3736 result.append("DispSync configuration: ");
3737 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003738 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003739 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003740 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003741 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003742 result.append("\n");
3743
Dan Stozab90cf072015-03-05 11:05:59 -08003744 // Dump static screen stats
3745 result.append("\n");
3746 dumpStaticScreenStats(result);
3747 result.append("\n");
3748
Dan Stozae77c7662016-05-13 11:37:28 -07003749 dumpBufferingStats(result);
3750
Andy McFadden4803b742012-09-24 19:07:20 -07003751 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003752 * Dump the visible layer list
3753 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003754 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003755 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003756 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003757 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003758 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003759 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003760
3761 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003762 * Dump Display state
3763 */
3764
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003765 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003766 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003767 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003768 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3769 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003770 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003771 }
3772
3773 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003774 * Dump SurfaceFlinger global state
3775 */
3776
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003777 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003778 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003779 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003780
Mathias Agopian888c8222012-08-04 21:10:38 -07003781 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003782 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003783
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003784 colorizer.bold(result);
3785 result.appendFormat("EGL implementation : %s\n",
3786 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3787 colorizer.reset(result);
3788 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003789 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003790
Mathias Agopian875d8e12013-06-07 15:35:48 -07003791 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003792
Mathias Agopian42977342012-08-05 00:40:46 -07003793 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003794 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3795 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003796 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003797 " last eglSwapBuffers() time: %f us\n"
3798 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003799 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003800 " refresh-rate : %f fps\n"
3801 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003802 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003803 " gpu_to_cpu_unsupported : %d\n"
3804 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003805 mLastSwapBufferTime/1000.0,
3806 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003807 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003808 1e9 / activeConfig->getVsyncPeriod(),
3809 activeConfig->getDpiX(),
3810 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003811 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003812
Mathias Agopian74d211a2013-04-22 16:55:35 +02003813 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003814 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003815
Mathias Agopian74d211a2013-04-22 16:55:35 +02003816 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003817 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818
3819 /*
3820 * VSYNC state
3821 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003822 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003823 result.append("\n");
3824
3825 /*
3826 * HWC layer minidump
3827 */
3828 for (size_t d = 0; d < mDisplays.size(); d++) {
3829 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3830 int32_t hwcId = displayDevice->getHwcDisplayId();
3831 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3832 continue;
3833 }
3834
3835 result.appendFormat("Display %d HWC layers:\n", hwcId);
3836 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003837 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003838 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003839 });
Dan Stozae22aec72016-08-01 13:20:59 -07003840 result.append("\n");
3841 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003842
3843 /*
3844 * Dump HWComposer state
3845 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003846 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003847 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003848 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003849 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003850 result.appendFormat(" h/w composer %s\n",
3851 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003852 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003853
3854 /*
3855 * Dump gralloc state
3856 */
3857 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3858 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003859
3860 /*
3861 * Dump VrFlinger state if in use.
3862 */
3863 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3864 result.append("VrFlinger state:\n");
3865 result.append(mVrFlinger->Dump().c_str());
3866 result.append("\n");
3867 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003868}
3869
Mathias Agopian13127d82013-03-05 17:47:11 -08003870const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003871SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003872 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003873 wp<IBinder> dpy;
3874 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3875 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3876 dpy = mDisplays.keyAt(i);
3877 break;
3878 }
3879 }
3880 if (dpy == NULL) {
3881 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3882 // Just use the primary display so we have something to return
3883 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3884 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003885 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003886}
3887
Keun young Park63f165f2012-08-31 10:53:36 -07003888bool SurfaceFlinger::startDdmConnection()
3889{
3890 void* libddmconnection_dso =
3891 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3892 if (!libddmconnection_dso) {
3893 return false;
3894 }
3895 void (*DdmConnection_start)(const char* name);
3896 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003897 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003898 if (!DdmConnection_start) {
3899 dlclose(libddmconnection_dso);
3900 return false;
3901 }
3902 (*DdmConnection_start)(getServiceName());
3903 return true;
3904}
3905
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003906status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003907 switch (code) {
3908 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003909 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003911 case CLEAR_ANIMATION_FRAME_STATS:
3912 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003913 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003914 case GET_HDR_CAPABILITIES:
Chia-I Wu6200eac2017-10-05 14:24:41 -07003915 case ENABLE_VSYNC_INJECTIONS:
3916 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003917 {
3918 // codes that require permission check
3919 IPCThreadState* ipc = IPCThreadState::self();
3920 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003921 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003922 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003923 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003924 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003925 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003927 break;
3928 }
Robert Carr1db73f62016-12-21 12:58:51 -08003929 /*
3930 * Calling setTransactionState is safe, because you need to have been
3931 * granted a reference to Client* and Handle* to do anything with it.
3932 *
3933 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3934 */
3935 case SET_TRANSACTION_STATE:
3936 case CREATE_SCOPED_CONNECTION:
3937 {
3938 return OK;
3939 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003940 case CAPTURE_SCREEN:
3941 {
3942 // codes that require permission check
3943 IPCThreadState* ipc = IPCThreadState::self();
3944 const int pid = ipc->getCallingPid();
3945 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003946 if ((uid != AID_GRAPHICS) &&
3947 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003948 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003949 return PERMISSION_DENIED;
3950 }
3951 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952 }
3953 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003954 return OK;
3955}
3956
3957status_t SurfaceFlinger::onTransact(
3958 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3959{
3960 status_t credentialCheck = CheckTransactCodeCredentials(code);
3961 if (credentialCheck != OK) {
3962 return credentialCheck;
3963 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003964
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3966 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003967 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003968 IPCThreadState* ipc = IPCThreadState::self();
3969 const int uid = ipc->getCallingUid();
3970 if (CC_UNLIKELY(uid != AID_SYSTEM
3971 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003972 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003973 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003974 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003975 return PERMISSION_DENIED;
3976 }
3977 int n;
3978 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003979 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003980 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 return NO_ERROR;
3982 case 1002: // SHOW_UPDATES
3983 n = data.readInt32();
3984 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003985 invalidateHwcGeometry();
3986 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003987 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003989 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003990 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003991 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003992 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07003993 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003994 setTransactionFlags(
3995 eTransactionNeeded|
3996 eDisplayTransactionNeeded|
3997 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003998 return NO_ERROR;
3999 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004000 case 1006:{ // send empty update
4001 signalRefresh();
4002 return NO_ERROR;
4003 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004004 case 1008: // toggle use of hw composer
4005 n = data.readInt32();
4006 mDebugDisableHWC = n ? 1 : 0;
4007 invalidateHwcGeometry();
4008 repaintEverything();
4009 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004010 case 1009: // toggle use of transform hint
4011 n = data.readInt32();
4012 mDebugDisableTransformHint = n ? 1 : 0;
4013 invalidateHwcGeometry();
4014 repaintEverything();
4015 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004016 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004017 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 reply->writeInt32(0);
4019 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004020 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004021 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004022 return NO_ERROR;
4023 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004024 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004025 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004026 return NO_ERROR;
4027 }
4028 case 1014: {
4029 // daltonize
4030 n = data.readInt32();
4031 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004032 case 1:
4033 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4034 break;
4035 case 2:
4036 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4037 break;
4038 case 3:
4039 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4040 break;
4041 default:
4042 mDaltonizer.setType(ColorBlindnessType::None);
4043 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004044 }
4045 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004046 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004047 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004048 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004049 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004050 invalidateHwcGeometry();
4051 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004052 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004054 case 1015: {
4055 // apply a color matrix
4056 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004057 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004058 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004059 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004060 for (size_t j = 0; j < 4; j++) {
4061 mColorMatrix[i][j] = data.readFloat();
4062 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004063 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004064 } else {
4065 mColorMatrix = mat4();
4066 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004067
4068 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4069 // the division by w in the fragment shader
4070 float4 lastRow(transpose(mColorMatrix)[3]);
4071 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4072 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4073 }
4074
Alan Viverette9c5a3332013-09-12 20:04:35 -07004075 invalidateHwcGeometry();
4076 repaintEverything();
4077 return NO_ERROR;
4078 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004079 // This is an experimental interface
4080 // Needs to be shifted to proper binder interface when we productize
4081 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004082 n = data.readInt32();
4083 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004084 return NO_ERROR;
4085 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004086 case 1017: {
4087 n = data.readInt32();
4088 mForceFullDamage = static_cast<bool>(n);
4089 return NO_ERROR;
4090 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004091 case 1018: { // Modify Choreographer's phase offset
4092 n = data.readInt32();
4093 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4094 return NO_ERROR;
4095 }
4096 case 1019: { // Modify SurfaceFlinger's phase offset
4097 n = data.readInt32();
4098 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4099 return NO_ERROR;
4100 }
Irvel468051e2016-06-13 16:44:44 -07004101 case 1020: { // Layer updates interceptor
4102 n = data.readInt32();
4103 if (n) {
4104 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004105 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004106 }
4107 else{
4108 ALOGV("Interceptor disabled");
4109 mInterceptor.disable();
4110 }
4111 return NO_ERROR;
4112 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004113 case 1021: { // Disable HWC virtual displays
4114 n = data.readInt32();
4115 mUseHwcVirtualDisplays = !n;
4116 return NO_ERROR;
4117 }
Romain Guy0147a172017-06-01 13:53:56 -07004118 case 1022: { // Set saturation boost
4119 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4120
4121 invalidateHwcGeometry();
4122 repaintEverything();
4123 return NO_ERROR;
4124 }
Romain Guy54f154a2017-10-24 21:40:32 +01004125 case 1023: { // Set native mode
4126 mForceNativeColorMode = data.readInt32() == 1;
4127
4128 invalidateHwcGeometry();
4129 repaintEverything();
4130 return NO_ERROR;
4131 }
4132 case 1024: { // Is wide color gamut rendering/color management supported?
4133 reply->writeBool(hasWideColorDisplay);
4134 return NO_ERROR;
4135 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004136 }
4137 }
4138 return err;
4139}
4140
Steven Thomas6d8110b2017-08-31 18:24:21 -07004141void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004142 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004143 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004144}
4145
Steven Thomas6d8110b2017-08-31 18:24:21 -07004146void SurfaceFlinger::repaintEverything() {
4147 ConditionalLock _l(mStateLock,
4148 std::this_thread::get_id() != mMainThreadId);
4149 repaintEverythingLocked();
4150}
4151
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004152// Checks that the requested width and height are valid and updates them to the display dimensions
4153// if they are set to 0
4154static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4155 Transform::orientation_flags rotation,
4156 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4157 // get screen geometry
4158 uint32_t displayWidth = displayDevice->getWidth();
4159 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004160
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004161 if (rotation & Transform::ROT_90) {
4162 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004163 }
4164
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004165 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4166 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4167 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4168 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004169 }
4170
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004171 if (*requestedWidth == 0) {
4172 *requestedWidth = displayWidth;
4173 }
4174 if (*requestedHeight == 0) {
4175 *requestedHeight = displayHeight;
4176 }
4177
4178 return NO_ERROR;
4179}
4180
4181// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4182class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004183public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004184 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4185 ~WindowDisconnector() {
4186 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004187 }
4188
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004189private:
4190 ANativeWindow* mWindow;
4191 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004192};
4193
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004194static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4195 uint32_t requestedHeight, bool hasWideColorDisplay,
4196 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4197 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4198 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4199
4200 int err = 0;
4201 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4202 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4203 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4204 err |= native_window_set_usage(window, usage);
4205
4206 if (hasWideColorDisplay) {
4207 err |= native_window_set_buffers_data_space(window,
4208 renderEngineUsesWideColor
4209 ? HAL_DATASPACE_DISPLAY_P3
4210 : HAL_DATASPACE_V0_SRGB);
4211 }
4212
4213 if (err != NO_ERROR) {
4214 return BAD_VALUE;
4215 }
4216
4217 /* TODO: Once we have the sync framework everywhere this can use
4218 * server-side waits on the fence that dequeueBuffer returns.
4219 */
4220 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4221 if (err != NO_ERROR) {
4222 return err;
4223 }
4224
4225 return NO_ERROR;
4226}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004227
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004228status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4229 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004230 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004231 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004232 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004233 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004234
4235 if (CC_UNLIKELY(display == 0))
4236 return BAD_VALUE;
4237
4238 if (CC_UNLIKELY(producer == 0))
4239 return BAD_VALUE;
4240
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004241 // if we have secure windows on this display, never allow the screen capture
4242 // unless the producer interface is local (i.e.: we can take a screenshot for
4243 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004244 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004245
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004246 // Convert to surfaceflinger's internal rotation type.
4247 Transform::orientation_flags rotationFlags;
4248 switch (rotation) {
4249 case ISurfaceComposer::eRotateNone:
4250 rotationFlags = Transform::ROT_0;
4251 break;
4252 case ISurfaceComposer::eRotate90:
4253 rotationFlags = Transform::ROT_90;
4254 break;
4255 case ISurfaceComposer::eRotate180:
4256 rotationFlags = Transform::ROT_180;
4257 break;
4258 case ISurfaceComposer::eRotate270:
4259 rotationFlags = Transform::ROT_270;
4260 break;
4261 default:
4262 rotationFlags = Transform::ROT_0;
4263 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4264 break;
4265 }
4266
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004267 { // Autolock scope
4268 Mutex::Autolock lock(mStateLock);
4269 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4270 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004271 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004272
4273 // create a surface (because we're a producer, and we need to
4274 // dequeue/queue a buffer)
4275 sp<Surface> surface = new Surface(producer, false);
4276
4277 // Put the screenshot Surface into async mode so that
4278 // Layer::headFenceHasSignaled will always return true and we'll latch the
4279 // first buffer regardless of whether or not its acquire fence has
4280 // signaled. This is needed to avoid a race condition in the rotation
4281 // animation. See b/30209608
4282 surface->setAsyncMode(true);
4283
4284 ANativeWindow* window = surface.get();
4285
4286 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4287 if (result != NO_ERROR) {
4288 return result;
4289 }
4290 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4291
4292 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004293 result = getWindowBuffer(window, reqWidth, reqHeight,
4294 hasWideColorDisplay && !mForceNativeColorMode,
4295 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004296 if (result != NO_ERROR) {
4297 return result;
4298 }
4299
4300 // This mutex protects syncFd and captureResult for communication of the return values from the
4301 // main thread back to this Binder thread
4302 std::mutex captureMutex;
4303 std::condition_variable captureCondition;
4304 std::unique_lock<std::mutex> captureLock(captureMutex);
4305 int syncFd = -1;
4306 std::optional<status_t> captureResult;
4307
4308 sp<LambdaMessage> message = new LambdaMessage([&]() {
4309 // If there is a refresh pending, bug out early and tell the binder thread to try again
4310 // after the refresh.
4311 if (mRefreshPending) {
4312 ATRACE_NAME("Skipping screenshot for now");
4313 std::unique_lock<std::mutex> captureLock(captureMutex);
4314 captureResult = std::make_optional<status_t>(EAGAIN);
4315 captureCondition.notify_one();
4316 return;
4317 }
4318
4319 status_t result = NO_ERROR;
4320 int fd = -1;
4321 {
4322 Mutex::Autolock _l(mStateLock);
4323 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4324 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4325 minLayerZ, maxLayerZ, useIdentityTransform,
4326 rotationFlags, isLocalScreenshot, &fd);
4327 }
4328
4329 {
4330 std::unique_lock<std::mutex> captureLock(captureMutex);
4331 syncFd = fd;
4332 captureResult = std::make_optional<status_t>(result);
4333 captureCondition.notify_one();
4334 }
4335 });
4336
4337 result = postMessageAsync(message);
4338 if (result == NO_ERROR) {
4339 captureCondition.wait(captureLock, [&]() { return captureResult; });
4340 while (*captureResult == EAGAIN) {
4341 captureResult.reset();
4342 result = postMessageAsync(message);
4343 if (result != NO_ERROR) {
4344 return result;
4345 }
4346 captureCondition.wait(captureLock, [&]() { return captureResult; });
4347 }
4348 result = *captureResult;
4349 }
4350
4351 if (result == NO_ERROR) {
4352 // queueBuffer takes ownership of syncFd
4353 result = window->queueBuffer(window, buffer, syncFd);
4354 }
4355
4356 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004357}
4358
Mathias Agopian180f10d2013-04-10 22:55:41 -07004359
4360void SurfaceFlinger::renderScreenImplLocked(
4361 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004362 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004363 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004364 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004365{
4366 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004367 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004368
4369 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004370 const int32_t hw_w = hw->getWidth();
4371 const int32_t hw_h = hw->getHeight();
4372 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004373 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004374
Dan Stozac1879002014-05-22 15:59:05 -07004375 // if a default or invalid sourceCrop is passed in, set reasonable values
4376 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4377 !sourceCrop.isValid()) {
4378 sourceCrop.setLeftTop(Point(0, 0));
4379 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4380 }
4381
4382 // ensure that sourceCrop is inside screen
4383 if (sourceCrop.left < 0) {
4384 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4385 }
Dan Stozabe31f442014-06-11 11:20:54 -07004386 if (sourceCrop.right > hw_w) {
4387 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004388 }
4389 if (sourceCrop.top < 0) {
4390 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4391 }
Dan Stozabe31f442014-06-11 11:20:54 -07004392 if (sourceCrop.bottom > hw_h) {
4393 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004394 }
4395
Romain Guy88d37dd2017-05-26 17:57:05 -07004396#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004397 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4398 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004399#endif
4400
Mathias Agopian180f10d2013-04-10 22:55:41 -07004401 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004402 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004403
4404 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004405 engine.setViewportAndProjection(
4406 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004407 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004408
4409 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004410 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004411
Robert Carr1f0a16a2016-10-24 16:27:39 -07004412 // We loop through the first level of layers without traversing,
4413 // as we need to interpret min/max layer Z in the top level Z space.
4414 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004415 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004416 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004417 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004418 const Layer::State& state(layer->getDrawingState());
4419 if (state.z < minLayerZ || state.z > maxLayerZ) {
4420 continue;
4421 }
Dan Stoza412903f2017-04-27 13:42:17 -07004422 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004423 if (!layer->isVisible()) {
4424 return;
4425 }
4426 if (filtering) layer->setFiltering(true);
4427 layer->draw(hw, useIdentityTransform);
4428 if (filtering) layer->setFiltering(false);
4429 });
4430 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004431
Mathias Agopian931bda12013-08-28 18:11:46 -07004432 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004433}
4434
Dan Stozaabcda352017-06-01 14:37:39 -07004435// A simple RAII class that holds an EGLImage and destroys it either:
4436// a) When the destroy() method is called
4437// b) When the object goes out of scope
4438class ImageHolder {
4439public:
4440 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4441 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004442
Dan Stozaabcda352017-06-01 14:37:39 -07004443 void destroy() {
4444 if (mImage != EGL_NO_IMAGE_KHR) {
4445 eglDestroyImageKHR(mDisplay, mImage);
4446 mImage = EGL_NO_IMAGE_KHR;
4447 }
4448 }
4449
4450private:
4451 const EGLDisplay mDisplay;
4452 EGLImageKHR mImage;
4453};
4454
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004455status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4456 ANativeWindowBuffer* buffer, Rect sourceCrop,
4457 uint32_t reqWidth, uint32_t reqHeight,
4458 int32_t minLayerZ, int32_t maxLayerZ,
4459 bool useIdentityTransform,
4460 Transform::orientation_flags rotation,
4461 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004462 ATRACE_CALL();
4463
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004464 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004465 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004466 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004467 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004468 (state.z < minLayerZ || state.z > maxLayerZ)) {
4469 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004470 }
Dan Stoza412903f2017-04-27 13:42:17 -07004471 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004472 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4473 layer->isSecure());
4474 });
4475 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004476
4477 if (!isLocalScreenshot && secureLayerIsVisible) {
4478 ALOGW("FB is protected: PERMISSION_DENIED");
4479 return PERMISSION_DENIED;
4480 }
4481
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004482 int syncFd = -1;
4483 // create an EGLImage from the buffer so we can later
4484 // turn it into a texture
4485 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4486 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4487 if (image == EGL_NO_IMAGE_KHR) {
4488 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004489 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004490
Dan Stozaabcda352017-06-01 14:37:39 -07004491 // This will automatically destroy the image if we return before calling its destroy method
4492 ImageHolder imageHolder(mEGLDisplay, image);
4493
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004494 // this binds the given EGLImage as a framebuffer for the
4495 // duration of this scope.
4496 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004497 if (imageBond.getStatus() != NO_ERROR) {
4498 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004499 return INVALID_OPERATION;
4500 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004501
Dan Stozaabcda352017-06-01 14:37:39 -07004502 // this will in fact render into our dequeued buffer
4503 // via an FBO, which means we didn't have to create
4504 // an EGLSurface and therefore we're not
4505 // dependent on the context's EGLConfig.
4506 renderScreenImplLocked(
4507 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4508 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004509
Dan Stozaabcda352017-06-01 14:37:39 -07004510 // Attempt to create a sync khr object that can produce a sync point. If that
4511 // isn't available, create a non-dupable sync object in the fallback path and
4512 // wait on it directly.
4513 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4514 if (!DEBUG_SCREENSHOTS) {
4515 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4516 // native fence fd will not be populated until flush() is done.
4517 getRenderEngine().flush();
4518 }
4519
4520 if (sync != EGL_NO_SYNC_KHR) {
4521 // get the sync fd
4522 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4523 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4524 ALOGW("captureScreen: failed to dup sync khr object");
4525 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004526 }
Dan Stozaabcda352017-06-01 14:37:39 -07004527 eglDestroySyncKHR(mEGLDisplay, sync);
4528 } else {
4529 // fallback path
4530 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004531 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004532 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4533 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4534 EGLint eglErr = eglGetError();
4535 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4536 ALOGW("captureScreen: fence wait timed out");
4537 } else {
4538 ALOGW_IF(eglErr != EGL_SUCCESS,
4539 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004540 }
4541 eglDestroySyncKHR(mEGLDisplay, sync);
4542 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004543 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004544 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004545 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004546 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004547
4548 if (DEBUG_SCREENSHOTS) {
4549 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4550 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4551 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4552 hw, minLayerZ, maxLayerZ);
4553 delete [] pixels;
4554 }
4555
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004556 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004557 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004558
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004559 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004560}
4561
Mathias Agopiand5556842013-09-19 17:08:37 -07004562void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004563 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004564 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004565 for (size_t y=0 ; y<h ; y++) {
4566 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4567 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004568 if (p[x] != 0xFF000000) return;
4569 }
4570 }
4571 ALOGE("*** we just took a black screenshot ***\n"
4572 "requested minz=%d, maxz=%d, layerStack=%d",
4573 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004574
Robert Carr2047fae2016-11-28 14:09:09 -08004575 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004576 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004577 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004578 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004579 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004580 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004581 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4582 layer->isVisible() ? '+' : '-',
4583 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004584 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004585 i++;
4586 });
4587 }
4588 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004589 }
4590}
4591
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004592// ---------------------------------------------------------------------------
4593
Dan Stoza412903f2017-04-27 13:42:17 -07004594void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4595 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004596}
4597
Dan Stoza412903f2017-04-27 13:42:17 -07004598void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4599 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004600}
4601
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004602}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004603
4604
4605#if defined(__gl_h_)
4606#error "don't include gl/gl.h in this file"
4607#endif
4608
4609#if defined(__gl2_h_)
4610#error "don't include gl2/gl2.h in this file"
4611#endif