blob: bb0e33cb45bac5c446d5fb97e41f2d0012aa4a05 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
31#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080040#include <dvr/vr_flinger.h>
41
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060042#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070043#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070044#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070045
Jamie Gennis1a4d8832012-08-02 20:11:05 -070046#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070047#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020067#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080068#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070069#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070071#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080072#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070074#include "LayerVector.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Steven Thomasd7f49c52017-07-26 18:48:28 -070079#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070080#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070081#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070082#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Mathias Agopianff2ed702013-09-01 21:36:12 -070084#include "Effects/Daltonizer.h"
85
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070088
Jiyong Park4b20c2e2017-01-14 19:45:11 +090089#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090090#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090091
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#define DISPLAY_COUNT 1
93
Mathias Agopianfee2b462013-07-03 12:34:01 -070094/*
95 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
96 * black pixels.
97 */
98#define DEBUG_SCREENSHOTS false
99
Jiyong Park00b15b82017-08-10 20:30:56 +0900100extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
Mathias Agopianca088332013-03-28 17:44:13 -0700101
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800102namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700103
Jaesoo Lee43518572017-01-23 19:03:16 +0900104using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900105using namespace android::hardware::configstore::V1_0;
106
Steven Thomasd7f49c52017-07-26 18:48:28 -0700107namespace {
108class ConditionalLock {
109public:
110 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
111 if (lock) {
112 mMutex.lock();
113 }
114 }
115 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
116private:
117 Mutex& mMutex;
118 bool mLocked;
119};
120} // namespace anonymous
121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122// ---------------------------------------------------------------------------
123
Mathias Agopian99b49842011-06-27 16:05:52 -0700124const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127const String16 sDump("android.permission.DUMP");
128
129// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800130int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
131int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700132bool SurfaceFlinger::useContextPriority;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700133int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700134bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800135uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800136bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800137bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800138int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600139bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800141SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700142 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700144 mTransactionPending(false),
145 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700146 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700147 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700148 mRepaintEverything(0),
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -0800149 mRenderEngine(nullptr),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800151 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800154 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700156 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700157 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700158 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700159 mDebugInSwapBuffers(0),
160 mLastSwapBufferTime(0),
161 mDebugInTransaction(0),
162 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700163 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700164 mForceFullDamage(false),
Robert Carr0d480722017-01-10 16:42:54 -0800165 mInterceptor(this),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000166 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700167 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700168 mHWVsyncAvailable(false),
Romain Guya9638732017-06-01 12:05:21 -0700169 mHasColorMatrix(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800170 mHasPoweredOff(false),
171 mFrameBuckets(),
172 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700173 mLastSwapTime(0),
Steven Thomas050b2c82017-03-06 11:45:16 -0800174 mNumLayers(0),
Steven Thomasd7f49c52017-07-26 18:48:28 -0700175 mVrFlingerRequestsDisplay(false),
176 mMainThreadId(std::this_thread::get_id()),
177 mComposerSequenceId(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800178{
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800179 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800180
181 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
182 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
183
184 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
185 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
186
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800187 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
188 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800189
Fabien Sanglardc93afd52017-03-13 13:02:42 -0700190 useContextPriority = getBool< ISurfaceFlingerConfigs,
191 &ISurfaceFlingerConfigs::useContextPriority>(false);
192
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700193 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
194 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
195
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700196 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
197 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
198
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800199 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
200 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
201
Steven Thomas050b2c82017-03-06 11:45:16 -0800202 // Vr flinger is only enabled on Daydream ready devices.
203 useVrFlinger = getBool< ISurfaceFlingerConfigs,
204 &ISurfaceFlingerConfigs::useVrFlinger>(false);
205
Fabien Sanglard1971b632017-03-10 14:50:03 -0800206 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
207 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
208
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600209 hasWideColorDisplay =
210 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
211
Saurabh Shahf4174532017-07-13 10:45:07 -0700212 mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 // debugging stuff...
215 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700216
Mathias Agopianb4b17302013-03-20 18:36:41 -0700217 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700218 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700219
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 property_get("debug.sf.showupdates", value, "0");
221 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700222
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700223 property_get("debug.sf.ddms", value, "0");
224 mDebugDDMS = atoi(value);
225 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700226 if (!startDdmConnection()) {
227 // start failed, and DDMS debugging not enabled
228 mDebugDDMS = 0;
229 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700230 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700231 ALOGI_IF(mDebugRegion, "showupdates enabled");
232 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700233
234 property_get("debug.sf.disable_backpressure", value, "0");
235 mPropagateBackpressure = !atoi(value);
236 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700237
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800238 property_get("debug.sf.enable_hwc_vds", value, "0");
239 mUseHwcVirtualDisplays = atoi(value);
240 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800241
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800242 property_get("ro.sf.disable_triple_buffer", value, "1");
243 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800244 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700245
Romain Guy11d63f42017-07-20 12:47:14 -0700246 // We should be reading 'persist.sys.sf.color_saturation' here
247 // but since /data may be encrypted, we need to wait until after vold
248 // comes online to attempt to read the property. The property is
249 // instead read after the boot animation
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800250}
251
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800252void SurfaceFlinger::onFirstRef()
253{
254 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800255}
256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257SurfaceFlinger::~SurfaceFlinger()
258{
Mathias Agopiana4912602012-07-12 14:25:33 -0700259 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
260 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
261 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800262}
263
Dan Stozac7014012014-02-14 15:03:43 -0800264void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800265{
266 // the window manager died on us. prepare its eulogy.
267
Andy McFadden13a082e2012-08-24 10:16:42 -0700268 // restore initial conditions (default device unblank, etc)
269 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800270
271 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700272 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800273}
274
Robert Carr1db73f62016-12-21 12:58:51 -0800275static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700276 status_t err = client->initCheck();
277 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800278 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800279 }
Robert Carr1db73f62016-12-21 12:58:51 -0800280 return nullptr;
281}
282
283sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
284 return initClient(new Client(this));
285}
286
287sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
288 const sp<IGraphicBufferProducer>& gbp) {
289 if (authenticateSurfaceTexture(gbp) == false) {
290 return nullptr;
291 }
292 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
293 if (layer == nullptr) {
294 return nullptr;
295 }
296
297 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800298}
299
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700300sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
301 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700302{
303 class DisplayToken : public BBinder {
304 sp<SurfaceFlinger> flinger;
305 virtual ~DisplayToken() {
306 // no more references, this display must be terminated
307 Mutex::Autolock _l(flinger->mStateLock);
308 flinger->mCurrentState.displays.removeItem(this);
309 flinger->setTransactionFlags(eDisplayTransactionNeeded);
310 }
311 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700312 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700313 : flinger(flinger) {
314 }
315 };
316
317 sp<BBinder> token = new DisplayToken(this);
318
319 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700320 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700321 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700322 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700323 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700324 return token;
325}
326
Jesse Hall6c913be2013-08-08 12:15:49 -0700327void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
328 Mutex::Autolock _l(mStateLock);
329
330 ssize_t idx = mCurrentState.displays.indexOfKey(display);
331 if (idx < 0) {
332 ALOGW("destroyDisplay: invalid display token");
333 return;
334 }
335
336 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
337 if (!info.isVirtualDisplay()) {
338 ALOGE("destroyDisplay called for non-virtual display");
339 return;
340 }
Irvelffc9efc2016-07-27 15:16:37 -0700341 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700342 mCurrentState.displays.removeItemsAt(idx);
343 setTransactionFlags(eDisplayTransactionNeeded);
344}
345
Jesse Hall692c7232012-11-08 15:41:56 -0800346void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800347 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800348 ALOGW_IF(mBuiltinDisplays[type],
349 "Overwriting display token for display type %d", type);
350 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800351 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700352 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800353 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700354 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800355}
356
Mathias Agopiane57f2922012-08-09 16:29:12 -0700357sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700358 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700359 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
360 return NULL;
361 }
Jesse Hall692c7232012-11-08 15:41:56 -0800362 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700363}
364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365void SurfaceFlinger::bootFinished()
366{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700367 if (mStartPropertySetThread->join() != NO_ERROR) {
368 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 const nsecs_t now = systemTime();
371 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000372 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700373
374 // wait patiently for the window manager death
375 const String16 name("window");
376 sp<IBinder> window(defaultServiceManager()->getService(name));
377 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700378 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700379 }
380
Steven Thomas050b2c82017-03-06 11:45:16 -0800381 if (mVrFlinger) {
382 mVrFlinger->OnBootFinished();
383 }
384
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700385 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700386 // formerly we would just kill the process, but we now ask it to exit so it
387 // can choose where to stop the animation.
388 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700389
390 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
391 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
392 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700393
Thierry Strudel2924d012017-08-14 15:19:37 -0700394 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700395 readPersistentProperties();
396 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700397 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398}
399
Mathias Agopian3f844832013-08-07 21:24:32 -0700400void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700401 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700402 RenderEngine& engine;
403 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700404 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700405 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
406 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700407 }
408 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700409 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700410 return true;
411 }
412 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700413 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700414}
415
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700416class DispSyncSource : public VSyncSource, private DispSync::Callback {
417public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700418 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000419 const char* name) :
420 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700421 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700422 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000423 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
424 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700425 mDispSync(dispSync),
426 mCallbackMutex(),
427 mCallback(),
428 mVsyncMutex(),
429 mPhaseOffset(phaseOffset),
430 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700431
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 virtual ~DispSyncSource() {}
433
434 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700435 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700436 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000437 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 static_cast<DispSync::Callback*>(this));
439 if (err != NO_ERROR) {
440 ALOGE("error registering vsync callback: %s (%d)",
441 strerror(-err), err);
442 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700443 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700444 } else {
445 status_t err = mDispSync->removeEventListener(
446 static_cast<DispSync::Callback*>(this));
447 if (err != NO_ERROR) {
448 ALOGE("error unregistering vsync callback: %s (%d)",
449 strerror(-err), err);
450 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700451 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700453 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700454 }
455
456 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 mCallback = callback;
459 }
460
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700461 virtual void setPhaseOffset(nsecs_t phaseOffset) {
462 Mutex::Autolock lock(mVsyncMutex);
463
464 // Normalize phaseOffset to [0, period)
465 auto period = mDispSync->getPeriod();
466 phaseOffset %= period;
467 if (phaseOffset < 0) {
468 // If we're here, then phaseOffset is in (-period, 0). After this
469 // operation, it will be in (0, period)
470 phaseOffset += period;
471 }
472 mPhaseOffset = phaseOffset;
473
474 // If we're not enabled, we don't need to mess with the listeners
475 if (!mEnabled) {
476 return;
477 }
478
479 // Remove the listener with the old offset
480 status_t err = mDispSync->removeEventListener(
481 static_cast<DispSync::Callback*>(this));
482 if (err != NO_ERROR) {
483 ALOGE("error unregistering vsync callback: %s (%d)",
484 strerror(-err), err);
485 }
486
487 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000488 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700489 static_cast<DispSync::Callback*>(this));
490 if (err != NO_ERROR) {
491 ALOGE("error registering vsync callback: %s (%d)",
492 strerror(-err), err);
493 }
494 }
495
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700496private:
497 virtual void onDispSyncEvent(nsecs_t when) {
498 sp<VSyncSource::Callback> callback;
499 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700500 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700501 callback = mCallback;
502
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700503 if (mTraceVsync) {
504 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700505 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700506 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700507 }
508
509 if (callback != NULL) {
510 callback->onVSyncEvent(when);
511 }
512 }
513
Tim Murray4a4e4a22016-04-19 16:29:23 +0000514 const char* const mName;
515
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700516 int mValue;
517
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700518 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700519 const String8 mVsyncOnLabel;
520 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700521
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700522 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700523
524 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700525 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700526
527 Mutex mVsyncMutex; // Protects the following
528 nsecs_t mPhaseOffset;
529 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700530};
531
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700532class InjectVSyncSource : public VSyncSource {
533public:
534 InjectVSyncSource() {}
535
536 virtual ~InjectVSyncSource() {}
537
538 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
539 std::lock_guard<std::mutex> lock(mCallbackMutex);
540 mCallback = callback;
541 }
542
543 virtual void onInjectSyncEvent(nsecs_t when) {
544 std::lock_guard<std::mutex> lock(mCallbackMutex);
545 mCallback->onVSyncEvent(when);
546 }
547
548 virtual void setVSyncEnabled(bool) {}
549 virtual void setPhaseOffset(nsecs_t) {}
550
551private:
552 std::mutex mCallbackMutex; // Protects the following
553 sp<VSyncSource::Callback> mCallback;
554};
555
Wei Wangf9b05ee2017-07-19 20:59:39 -0700556// Do not call property_set on main thread which will be blocked by init
557// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700558void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700559 ALOGI( "SurfaceFlinger's main thread ready to run. "
560 "Initializing graphics H/W...");
561
Thierry Strudel2924d012017-08-14 15:19:37 -0700562 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900563
Steven Thomasd7f49c52017-07-26 18:48:28 -0700564 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800565
Steven Thomasd7f49c52017-07-26 18:48:28 -0700566 // initialize EGL for the default display
567 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
568 eglInitialize(mEGLDisplay, NULL, NULL);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800569
Steven Thomasd7f49c52017-07-26 18:48:28 -0700570 // start the EventThread
571 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
572 vsyncPhaseOffsetNs, true, "app");
573 mEventThread = new EventThread(vsyncSrc, *this, false);
574 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
575 sfVsyncPhaseOffsetNs, true, "sf");
576 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
577 mEventQueue.setEventThread(mSFEventThread);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800578
Steven Thomasd7f49c52017-07-26 18:48:28 -0700579 // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
580 struct sched_param param = {0};
581 param.sched_priority = 2;
582 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
583 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
584 }
585 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
586 ALOGE("Couldn't set SCHED_FIFO for EventThread");
Dan Stoza9e56aa02015-11-02 13:00:03 -0800587 }
588
Steven Thomasd7f49c52017-07-26 18:48:28 -0700589 // Get a RenderEngine for the given display / config (can't fail)
590 mRenderEngine = RenderEngine::create(mEGLDisplay,
591 HAL_PIXEL_FORMAT_RGBA_8888,
592 hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
Steven Thomasd7f49c52017-07-26 18:48:28 -0700594 // retrieve the EGL context that was selected/created
595 mEGLContext = mRenderEngine->getEGLContext();
596
597 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
598 "couldn't create EGLContext");
599
600 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
601 "Starting with vr flinger active is not currently supported.");
602 mHwc.reset(new HWComposer(false));
603 mHwc->registerCallback(this, mComposerSequenceId);
Jesse Hall692c7232012-11-08 15:41:56 -0800604
Steven Thomas050b2c82017-03-06 11:45:16 -0800605 if (useVrFlinger) {
606 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700607 // This callback is called from the vr flinger dispatch thread. We
608 // need to call signalTransaction(), which requires holding
609 // mStateLock when we're not on the main thread. Acquiring
610 // mStateLock from the vr flinger dispatch thread might trigger a
611 // deadlock in surface flinger (see b/66916578), so post a message
612 // to be handled on the main thread instead.
613 sp<LambdaMessage> message = new LambdaMessage([=]() {
614 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
615 mVrFlingerRequestsDisplay = requestDisplay;
616 signalTransaction();
617 });
618 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800619 };
620 mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
621 vrFlingerRequestDisplayCallback);
622 if (!mVrFlinger) {
623 ALOGE("Failed to start vrflinger");
624 }
625 }
626
Jamie Gennisd1700752013-10-14 12:22:52 -0700627 mEventControlThread = new EventControlThread(this);
628 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
629
Mathias Agopian92a979a2012-08-02 18:32:23 -0700630 // initialize our drawing state
631 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700632
Andy McFadden13a082e2012-08-24 10:16:42 -0700633 // set initial conditions (e.g. unblank default device)
634 initializeDisplays();
635
Dan Stoza4e637772016-07-28 13:31:51 -0700636 mRenderEngine->primeCache();
637
Wei Wangf9b05ee2017-07-19 20:59:39 -0700638 // Inform native graphics APIs whether the present timestamp is supported:
639 if (getHwComposer().hasCapability(
640 HWC2::Capability::PresentFenceIsNotReliable)) {
641 mStartPropertySetThread = new StartPropertySetThread(false);
642 } else {
643 mStartPropertySetThread = new StartPropertySetThread(true);
644 }
645
646 if (mStartPropertySetThread->Start() != NO_ERROR) {
647 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800649
Dan Stoza9e56aa02015-11-02 13:00:03 -0800650 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700651}
652
Romain Guy11d63f42017-07-20 12:47:14 -0700653void SurfaceFlinger::readPersistentProperties() {
654 char value[PROPERTY_VALUE_MAX];
655
656 property_get("persist.sys.sf.color_saturation", value, "1.0");
657 mSaturation = atof(value);
658 ALOGV("Saturation is set to %.2f", mSaturation);
Romain Guy54f154a2017-10-24 21:40:32 +0100659
660 property_get("persist.sys.sf.native_mode", value, "0");
661 mForceNativeColorMode = atoi(value) == 1;
662 if (mForceNativeColorMode) {
663 ALOGV("Forcing native color mode");
664 }
Romain Guy11d63f42017-07-20 12:47:14 -0700665}
666
Mathias Agopiana67e4182012-06-19 17:26:12 -0700667void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800668 // Start boot animation service by setting a property mailbox
669 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700670 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800671 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700672 if (mStartPropertySetThread->join() != NO_ERROR) {
673 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700675}
676
Mathias Agopian875d8e12013-06-07 15:35:48 -0700677size_t SurfaceFlinger::getMaxTextureSize() const {
678 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700679}
680
Mathias Agopian875d8e12013-06-07 15:35:48 -0700681size_t SurfaceFlinger::getMaxViewportDims() const {
682 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700683}
684
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800686
Jamie Gennis582270d2011-08-17 18:19:00 -0700687bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800688 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800689 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800690 return authenticateSurfaceTextureLocked(bufferProducer);
691}
692
693bool SurfaceFlinger::authenticateSurfaceTextureLocked(
694 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800695 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700696 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800697}
698
Brian Anderson6b376712017-04-04 10:51:39 -0700699status_t SurfaceFlinger::getSupportedFrameTimestamps(
700 std::vector<FrameEvent>* outSupported) const {
701 *outSupported = {
702 FrameEvent::REQUESTED_PRESENT,
703 FrameEvent::ACQUIRE,
704 FrameEvent::LATCH,
705 FrameEvent::FIRST_REFRESH_START,
706 FrameEvent::LAST_REFRESH_START,
707 FrameEvent::GPU_COMPOSITION_DONE,
708 FrameEvent::DEQUEUE_READY,
709 FrameEvent::RELEASE,
710 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700711 ConditionalLock _l(mStateLock,
712 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700713 if (!getHwComposer().hasCapability(
714 HWC2::Capability::PresentFenceIsNotReliable)) {
715 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
716 }
717 return NO_ERROR;
718}
719
Dan Stoza7f7da322014-05-02 15:26:25 -0700720status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
721 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700722 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700723 return BAD_VALUE;
724 }
725
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500726 if (!display.get())
727 return NAME_NOT_FOUND;
728
Jesse Hall692c7232012-11-08 15:41:56 -0800729 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700730 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800731 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700732 type = i;
733 break;
734 }
735 }
736
737 if (type < 0) {
738 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700739 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700740
Mathias Agopian8b736f12012-08-13 17:54:26 -0700741 // TODO: Not sure if display density should handled by SF any longer
742 class Density {
743 static int getDensityFromProperty(char const* propName) {
744 char property[PROPERTY_VALUE_MAX];
745 int density = 0;
746 if (property_get(propName, property, NULL) > 0) {
747 density = atoi(property);
748 }
749 return density;
750 }
751 public:
752 static int getEmuDensity() {
753 return getDensityFromProperty("qemu.sf.lcd_density"); }
754 static int getBuildDensity() {
755 return getDensityFromProperty("ro.sf.lcd_density"); }
756 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700757
Dan Stoza7f7da322014-05-02 15:26:25 -0700758 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700759
Steven Thomas6d8110b2017-08-31 18:24:21 -0700760 ConditionalLock _l(mStateLock,
761 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800762 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700763 DisplayInfo info = DisplayInfo();
764
Dan Stoza9e56aa02015-11-02 13:00:03 -0800765 float xdpi = hwConfig->getDpiX();
766 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700767
768 if (type == DisplayDevice::DISPLAY_PRIMARY) {
769 // The density of the device is provided by a build property
770 float density = Density::getBuildDensity() / 160.0f;
771 if (density == 0) {
772 // the build doesn't provide a density -- this is wrong!
773 // use xdpi instead
774 ALOGE("ro.sf.lcd_density must be defined as a build property");
775 density = xdpi / 160.0f;
776 }
777 if (Density::getEmuDensity()) {
778 // if "qemu.sf.lcd_density" is specified, it overrides everything
779 xdpi = ydpi = density = Density::getEmuDensity();
780 density /= 160.0f;
781 }
782 info.density = density;
783
784 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000786 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700787 } else {
788 // TODO: where should this value come from?
789 static const int TV_DENSITY = 213;
790 info.density = TV_DENSITY / 160.0f;
791 info.orientation = 0;
792 }
793
Dan Stoza9e56aa02015-11-02 13:00:03 -0800794 info.w = hwConfig->getWidth();
795 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 info.xdpi = xdpi;
797 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800798 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900799 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800
Andy McFadden91b2ca82014-06-13 14:04:23 -0700801 // This is how far in advance a buffer must be queued for
802 // presentation at a given time. If you want a buffer to appear
803 // on the screen at time N, you must submit the buffer before
804 // (N - presentationDeadline).
805 //
806 // Normally it's one full refresh period (to give SF a chance to
807 // latch the buffer), but this can be reduced by configuring a
808 // DispSync offset. Any additional delays introduced by the hardware
809 // composer or panel must be accounted for here.
810 //
811 // We add an additional 1ms to allow for processing time and
812 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800814 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700815
816 // All non-virtual displays are currently considered secure.
817 info.secure = true;
818
Michael Wright28f24d02016-07-12 13:30:53 -0700819 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 }
821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 return NO_ERROR;
823}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700824
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800825status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700826 DisplayStatInfo* stats) {
827 if (stats == NULL) {
828 return BAD_VALUE;
829 }
830
831 // FIXME for now we always return stats for the primary display
832 memset(stats, 0, sizeof(*stats));
833 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
834 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
835 return NO_ERROR;
836}
837
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700838int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800839 if (display == NULL) {
840 ALOGE("%s : display is NULL", __func__);
841 return BAD_VALUE;
842 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700843
844 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700845 if (device != NULL) {
846 return device->getActiveConfig();
847 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700848
Dan Stoza24a42e92015-03-09 10:04:11 -0700849 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700850}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700851
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700852void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
853 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
854 this);
855 int32_t type = hw->getDisplayType();
856 int currentMode = hw->getActiveConfig();
857
858 if (mode == currentMode) {
859 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
860 return;
861 }
862
863 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
864 ALOGW("Trying to set config for virtual display");
865 return;
866 }
867
868 hw->setActiveConfig(mode);
869 getHwComposer().setActiveConfig(type, mode);
870}
871
872status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
873 class MessageSetActiveConfig: public MessageBase {
874 SurfaceFlinger& mFlinger;
875 sp<IBinder> mDisplay;
876 int mMode;
877 public:
878 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
879 int mode) :
880 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
881 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700882 Vector<DisplayInfo> configs;
883 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700884 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700885 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700886 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700887 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700888 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700889 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
890 if (hw == NULL) {
891 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700892 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700893 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
894 ALOGW("Attempt to set active config = %d for virtual display",
895 mMode);
896 } else {
897 mFlinger.setActiveConfigInternal(hw, mMode);
898 }
899 return true;
900 }
901 };
902 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
903 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700904 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700905}
Michael Wright28f24d02016-07-12 13:30:53 -0700906status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
907 Vector<android_color_mode_t>* outColorModes) {
908 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
909 return BAD_VALUE;
910 }
911
912 if (!display.get()) {
913 return NAME_NOT_FOUND;
914 }
915
916 int32_t type = NAME_NOT_FOUND;
917 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
918 if (display == mBuiltinDisplays[i]) {
919 type = i;
920 break;
921 }
922 }
923
924 if (type < 0) {
925 return type;
926 }
927
Steven Thomas6d8110b2017-08-31 18:24:21 -0700928 std::vector<android_color_mode_t> modes;
929 {
930 ConditionalLock _l(mStateLock,
931 std::this_thread::get_id() != mMainThreadId);
932 modes = getHwComposer().getColorModes(type);
933 }
Michael Wright28f24d02016-07-12 13:30:53 -0700934 outColorModes->clear();
935 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
936
937 return NO_ERROR;
938}
939
940android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700941 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700942 if (device != nullptr) {
943 return device->getActiveColorMode();
944 }
945 return static_cast<android_color_mode_t>(BAD_VALUE);
946}
947
948void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
949 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700950 int32_t type = hw->getDisplayType();
951 android_color_mode_t currentMode = hw->getActiveColorMode();
952
953 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700954 return;
955 }
956
957 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
958 ALOGW("Trying to set config for virtual display");
959 return;
960 }
961
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600962 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
963 hw->getDisplayType());
964
Michael Wright28f24d02016-07-12 13:30:53 -0700965 hw->setActiveColorMode(mode);
966 getHwComposer().setActiveColorMode(type, mode);
967}
968
969
970status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
971 android_color_mode_t colorMode) {
972 class MessageSetActiveColorMode: public MessageBase {
973 SurfaceFlinger& mFlinger;
974 sp<IBinder> mDisplay;
975 android_color_mode_t mMode;
976 public:
977 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
978 android_color_mode_t mode) :
979 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
980 virtual bool handler() {
981 Vector<android_color_mode_t> modes;
982 mFlinger.getDisplayColorModes(mDisplay, &modes);
983 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
984 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600985 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
986 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700987 return true;
988 }
989 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
990 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600991 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
992 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700993 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600994 ALOGW("Attempt to set active color mode %s %d for virtual display",
995 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700996 } else {
997 mFlinger.setActiveColorModeInternal(hw, mMode);
998 }
999 return true;
1000 }
1001 };
1002 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1003 postMessageSync(msg);
1004 return NO_ERROR;
1005}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001006
Svetoslavd85084b2014-03-20 10:28:31 -07001007status_t SurfaceFlinger::clearAnimationFrameStats() {
1008 Mutex::Autolock _l(mStateLock);
1009 mAnimFrameTracker.clearStats();
1010 return NO_ERROR;
1011}
1012
1013status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1014 Mutex::Autolock _l(mStateLock);
1015 mAnimFrameTracker.getStats(outStats);
1016 return NO_ERROR;
1017}
1018
Dan Stozac4f471e2016-03-24 09:31:08 -07001019status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1020 HdrCapabilities* outCapabilities) const {
1021 Mutex::Autolock _l(mStateLock);
1022
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001023 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001024 if (displayDevice == nullptr) {
1025 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1026 return BAD_VALUE;
1027 }
1028
1029 std::unique_ptr<HdrCapabilities> capabilities =
1030 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1031 if (capabilities) {
1032 std::swap(*outCapabilities, *capabilities);
1033 } else {
1034 return BAD_VALUE;
1035 }
1036
1037 return NO_ERROR;
1038}
1039
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001040status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1041 if (enable == mInjectVSyncs) {
1042 return NO_ERROR;
1043 }
1044
1045 if (enable) {
1046 mInjectVSyncs = enable;
1047 ALOGV("VSync Injections enabled");
1048 if (mVSyncInjector.get() == nullptr) {
1049 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001050 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001051 }
1052 mEventQueue.setEventThread(mInjectorEventThread);
1053 } else {
1054 mInjectVSyncs = enable;
1055 ALOGV("VSync Injections disabled");
1056 mEventQueue.setEventThread(mSFEventThread);
1057 mVSyncInjector.clear();
1058 }
1059 return NO_ERROR;
1060}
1061
1062status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1063 if (!mInjectVSyncs) {
1064 ALOGE("VSync Injections not enabled");
1065 return BAD_VALUE;
1066 }
1067 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1068 ALOGV("Injecting VSync inside SurfaceFlinger");
1069 mVSyncInjector->onInjectSyncEvent(when);
1070 }
1071 return NO_ERROR;
1072}
1073
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001074// ----------------------------------------------------------------------------
1075
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001076sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1077 ISurfaceComposer::VsyncSource vsyncSource) {
1078 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1079 return mSFEventThread->createEventConnection();
1080 } else {
1081 return mEventThread->createEventConnection();
1082 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001083}
1084
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001085// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001086
1087void SurfaceFlinger::waitForEvent() {
1088 mEventQueue.waitMessage();
1089}
1090
1091void SurfaceFlinger::signalTransaction() {
1092 mEventQueue.invalidate();
1093}
1094
1095void SurfaceFlinger::signalLayerUpdate() {
1096 mEventQueue.invalidate();
1097}
1098
1099void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001100 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001101 mEventQueue.refresh();
1102}
1103
1104status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001105 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001106 return mEventQueue.postMessage(msg, reltime);
1107}
1108
1109status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001110 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001111 status_t res = mEventQueue.postMessage(msg, reltime);
1112 if (res == NO_ERROR) {
1113 msg->wait();
1114 }
1115 return res;
1116}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001117
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001118void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001119 do {
1120 waitForEvent();
1121 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001122}
1123
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001124void SurfaceFlinger::enableHardwareVsync() {
1125 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001126 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001127 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001128 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1129 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001130 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001131 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001132}
1133
Jesse Hall948fe0c2013-10-14 12:56:09 -07001134void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001135 Mutex::Autolock _l(mHWVsyncLock);
1136
Jesse Hall948fe0c2013-10-14 12:56:09 -07001137 if (makeAvailable) {
1138 mHWVsyncAvailable = true;
1139 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001140 // Hardware vsync is not currently available, so abort the resync
1141 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001142 return;
1143 }
1144
Dan Stoza9e56aa02015-11-02 13:00:03 -08001145 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1146 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001147
1148 mPrimaryDispSync.reset();
1149 mPrimaryDispSync.setPeriod(period);
1150
1151 if (!mPrimaryHWVsyncEnabled) {
1152 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001153 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1154 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001155 mPrimaryHWVsyncEnabled = true;
1156 }
1157}
1158
Jesse Hall948fe0c2013-10-14 12:56:09 -07001159void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001160 Mutex::Autolock _l(mHWVsyncLock);
1161 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001162 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1163 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164 mPrimaryDispSync.endResync();
1165 mPrimaryHWVsyncEnabled = false;
1166 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001167 if (makeUnavailable) {
1168 mHWVsyncAvailable = false;
1169 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001170}
1171
Tim Murray4a4e4a22016-04-19 16:29:23 +00001172void SurfaceFlinger::resyncWithRateLimit() {
1173 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001174
1175 // No explicit locking is needed here since EventThread holds a lock while calling this method
1176 static nsecs_t sLastResyncAttempted = 0;
1177 const nsecs_t now = systemTime();
1178 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001179 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001180 }
Dan Stoza57164302017-05-08 14:03:54 -07001181 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001182}
1183
Steven Thomasd7f49c52017-07-26 18:48:28 -07001184void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1185 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001186 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001187 // Ignore any vsyncs from a previous hardware composer.
1188 if (sequenceId != mComposerSequenceId) {
1189 return;
1190 }
1191
1192 int32_t type;
1193 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001194 return;
1195 }
1196
Jamie Gennisd1700752013-10-14 12:22:52 -07001197 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001198
Jamie Gennisd1700752013-10-14 12:22:52 -07001199 { // Scope for the lock
1200 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001201 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001202 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001203 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001204 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001205
1206 if (needsHwVsync) {
1207 enableHardwareVsync();
1208 } else {
1209 disableHardwareVsync(false);
1210 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001211}
1212
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001213void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001214 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001215 *compositorTiming = mCompositorTiming;
1216}
1217
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001218void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001219 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001220 wp<IBinder> token = mBuiltinDisplays[type];
1221
1222 // All non-virtual displays are currently considered secure.
1223 const bool isSecure = true;
1224
1225 sp<IGraphicBufferProducer> producer;
1226 sp<IGraphicBufferConsumer> consumer;
1227 BufferQueue::createBufferQueue(&producer, &consumer);
1228
1229 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1230
1231 bool hasWideColorModes = false;
1232 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1233 for (android_color_mode_t colorMode : modes) {
1234 switch (colorMode) {
1235 case HAL_COLOR_MODE_DISPLAY_P3:
1236 case HAL_COLOR_MODE_ADOBE_RGB:
1237 case HAL_COLOR_MODE_DCI_P3:
1238 hasWideColorModes = true;
1239 break;
1240 default:
1241 break;
1242 }
1243 }
Romain Guy54f154a2017-10-24 21:40:32 +01001244 bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001245 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1246 token, fbs, producer, mRenderEngine->getEGLConfig(),
Romain Guy54f154a2017-10-24 21:40:32 +01001247 useWideColorMode);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001248 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001249 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
Romain Guy54f154a2017-10-24 21:40:32 +01001250 if (useWideColorMode) {
Thierry Strudel2924d012017-08-14 15:19:37 -07001251 defaultColorMode = HAL_COLOR_MODE_SRGB;
1252 }
1253 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001254 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001255
1256 // Add the primary display token to mDrawingState so we don't try to
1257 // recreate the DisplayDevice for the primary display.
1258 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1259
1260 // make the GLContext current so that we can create textures when creating
1261 // Layers (which may happens before we render something)
1262 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001263}
1264
Steven Thomasd7f49c52017-07-26 18:48:28 -07001265void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1266 hwc2_display_t display, HWC2::Connection connection,
1267 bool primaryDisplay) {
1268 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1269 sequenceId, display,
1270 connection == HWC2::Connection::Connected ?
1271 "connected" : "disconnected",
1272 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001273
Steven Thomasd7f49c52017-07-26 18:48:28 -07001274 // Only lock if we're not on the main thread. This function is normally
1275 // called on a hwbinder thread, but for the primary display it's called on
1276 // the main thread with the state lock already held, so don't attempt to
1277 // acquire it here.
1278 ConditionalLock lock(mStateLock,
1279 std::this_thread::get_id() != mMainThreadId);
1280
1281 if (primaryDisplay) {
1282 mHwc->onHotplug(display, connection);
1283 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1284 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001285 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001286 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001287 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001288 if (sequenceId != mComposerSequenceId) {
1289 return;
1290 }
1291 if (mHwc->isUsingVrComposer()) {
1292 ALOGE("External displays are not supported by the vr hardware composer.");
1293 return;
1294 }
1295 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001296 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasd7f49c52017-07-26 18:48:28 -07001297 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001298 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001299 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001300 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1301 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001302 }
1303 setTransactionFlags(eDisplayTransactionNeeded);
1304
Andy McFadden9e9689c2012-10-10 18:17:51 -07001305 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001306 }
Mathias Agopian86303202012-07-24 22:46:10 -07001307}
1308
Steven Thomasd7f49c52017-07-26 18:48:28 -07001309void SurfaceFlinger::onRefreshReceived(int sequenceId,
1310 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001311 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001312 if (sequenceId != mComposerSequenceId) {
1313 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001314 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001315 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001316}
1317
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319 ATRACE_CALL();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001320 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 getHwComposer().setVsyncEnabled(disp,
1322 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001323}
1324
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001325// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasd7f49c52017-07-26 18:48:28 -07001326void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001328 // Clear the drawing state so that the logic inside of
1329 // handleTransactionLocked will fire. It will determine the delta between
1330 // mCurrentState and mDrawingState and re-apply all changes when we make the
1331 // transition.
1332 mDrawingState.displays.clear();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001333 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001334 mDisplays.clear();
1335}
1336
Steven Thomas050b2c82017-03-06 11:45:16 -08001337void SurfaceFlinger::updateVrFlinger() {
1338 if (!mVrFlinger)
1339 return;
1340 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1341 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001342 return;
1343 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001344
Steven Thomasd7f49c52017-07-26 18:48:28 -07001345 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1346 ALOGE("Vr flinger is only supported for remote hardware composer"
1347 " service connections. Ignoring request to transition to vr"
1348 " flinger.");
1349 mVrFlingerRequestsDisplay = false;
1350 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001351 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001352
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354
Steven Thomasd7f49c52017-07-26 18:48:28 -07001355 int currentDisplayPowerMode = getDisplayDeviceLocked(
1356 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001357
Steven Thomasd7f49c52017-07-26 18:48:28 -07001358 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001360 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001361
Steven Thomasd7f49c52017-07-26 18:48:28 -07001362 resetDisplayState();
1363 mHwc.reset(); // Delete the current instance before creating the new one
1364 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1365 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366
Steven Thomasd7f49c52017-07-26 18:48:28 -07001367 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1368 "Switched to non-remote hardware composer");
1369
1370 if (vrFlingerRequestsDisplay) {
1371 mVrFlinger->GrantDisplayOwnership();
1372 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001373 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001374 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375
1376 mVisibleRegionsDirty = true;
1377 invalidateHwcGeometry();
1378
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001379 // Re-enable default display.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001380 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1381 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1382 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001383
Steven Thomasd7f49c52017-07-26 18:48:28 -07001384 // Reset the timing values to account for the period of the swapped in HWC
1385 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1386 const nsecs_t period = activeConfig->getVsyncPeriod();
1387 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001388
Steven Thomasd7f49c52017-07-26 18:48:28 -07001389 // Use phase of 0 since phase is not known.
1390 // Use latency of 0, which will snap to the ideal latency.
1391 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001392
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001393 android_atomic_or(1, &mRepaintEverything);
1394 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001395}
1396
Mathias Agopian4fec8732012-06-29 14:12:52 -07001397void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001398 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001399 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001400 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001401 bool frameMissed = !mHadClientComposition &&
1402 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001403 (mPreviousPresentFence->getSignalTime() ==
1404 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001405 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001406 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001407 signalLayerUpdate();
1408 break;
1409 }
1410
Steven Thomas050b2c82017-03-06 11:45:16 -08001411 // Now that we're going to make it to the handleMessageTransaction()
1412 // call below it's safe to call updateVrFlinger(), which will
1413 // potentially trigger a display handoff.
1414 updateVrFlinger();
1415
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 bool refreshNeeded = handleMessageTransaction();
1417 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001418 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001419 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001420 // Signal a refresh if a transaction modified the window state,
1421 // a new buffer was latched, or if HWC has requested a full
1422 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001423 signalRefresh();
1424 }
1425 break;
1426 }
1427 case MessageQueue::REFRESH: {
1428 handleMessageRefresh();
1429 break;
1430 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431 }
1432}
1433
Dan Stoza6b9454d2014-11-07 16:00:59 -08001434bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001435 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001436 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001437 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001439 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001440 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001441}
1442
Dan Stoza6b9454d2014-11-07 16:00:59 -08001443bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001444 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001445 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001446}
1447
1448void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001449 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001450
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001451 mRefreshPending = false;
1452
Pablo Ceballos40845df2016-01-25 17:41:15 -08001453 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001454
Brian Andersond6927fb2016-07-23 23:37:30 -07001455 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001456 rebuildLayerStacks();
1457 setUpHWComposer();
1458 doDebugFlashRegions();
1459 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001460 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001461
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001462 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001463
1464 mHadClientComposition = false;
1465 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1466 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1467 mHadClientComposition = mHadClientComposition ||
1468 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1469 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001470
Dan Stoza9e56aa02015-11-02 13:00:03 -08001471 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001472}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473
Mathias Agopiancd60f992012-08-16 16:28:27 -07001474void SurfaceFlinger::doDebugFlashRegions()
1475{
1476 // is debugging enabled
1477 if (CC_LIKELY(!mDebugRegion))
1478 return;
1479
1480 const bool repaintEverything = mRepaintEverything;
1481 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1482 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001483 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 // transform the dirty region into this screen's coordinate space
1485 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1486 if (!dirtyRegion.isEmpty()) {
1487 // redraw the whole screen
1488 doComposeSurfaces(hw, Region(hw->bounds()));
1489
1490 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001491 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001492 RenderEngine& engine(getRenderEngine());
1493 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1494
Mathias Agopianda27af92012-09-13 18:17:13 -07001495 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001496 }
1497 }
1498 }
1499
1500 postFramebuffer();
1501
1502 if (mDebugRegion > 1) {
1503 usleep(mDebugRegion * 1000);
1504 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001505
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001507 auto& displayDevice = mDisplays[displayId];
1508 if (!displayDevice->isDisplayOn()) {
1509 continue;
1510 }
1511
1512 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001513 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1514 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001515 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516}
1517
Brian Andersond6927fb2016-07-23 23:37:30 -07001518void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001520 ATRACE_CALL();
1521 ALOGV("preComposition");
1522
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001524 mDrawingState.traverseInZOrder([&](Layer* layer) {
1525 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001526 needExtraInvalidate = true;
1527 }
Robert Carr2047fae2016-11-28 14:09:09 -08001528 });
1529
Mathias Agopiancd60f992012-08-16 16:28:27 -07001530 if (needExtraInvalidate) {
1531 signalLayerUpdate();
1532 }
1533}
1534
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001535void SurfaceFlinger::updateCompositorTiming(
1536 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1537 std::shared_ptr<FenceTime>& presentFenceTime) {
1538 // Update queue of past composite+present times and determine the
1539 // most recently known composite to present latency.
1540 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1541 nsecs_t compositeToPresentLatency = -1;
1542 while (!mCompositePresentTimes.empty()) {
1543 CompositePresentTime& cpt = mCompositePresentTimes.front();
1544 // Cached values should have been updated before calling this method,
1545 // which helps avoid duplicate syscalls.
1546 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1547 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1548 break;
1549 }
1550 compositeToPresentLatency = displayTime - cpt.composite;
1551 mCompositePresentTimes.pop();
1552 }
1553
1554 // Don't let mCompositePresentTimes grow unbounded, just in case.
1555 while (mCompositePresentTimes.size() > 16) {
1556 mCompositePresentTimes.pop();
1557 }
1558
Brian Andersond0010582017-03-07 13:20:31 -08001559 setCompositorTimingSnapped(
1560 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1561}
1562
1563void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1564 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001565 // Integer division and modulo round toward 0 not -inf, so we need to
1566 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001567 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001568 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1569 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1570
Brian Andersond0010582017-03-07 13:20:31 -08001571 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1572 if (idealLatency <= 0) {
1573 idealLatency = vsyncInterval;
1574 }
1575
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001576 // Snap the latency to a value that removes scheduling jitter from the
1577 // composition and present times, which often have >1ms of jitter.
1578 // Reducing jitter is important if an app attempts to extrapolate
1579 // something (such as user input) to an accurate diasplay time.
1580 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1581 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001582 nsecs_t bias = vsyncInterval / 2;
1583 int64_t extraVsyncs =
1584 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1585 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1586 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587
Brian Andersond0010582017-03-07 13:20:31 -08001588 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001589 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1590 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001591 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001592}
1593
1594void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001595{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001596 ATRACE_CALL();
1597 ALOGV("postComposition");
1598
Brian Anderson3546a3f2016-07-14 11:51:14 -07001599 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001600 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001601 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001602 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001603 }
1604
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001605 // |mStateLock| not needed as we are on the main thread
1606 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001607
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001608 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001609 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1610 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1611 glCompositionDoneFenceTime =
1612 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1613 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1614 } else {
1615 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1616 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001617
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001618 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001619 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1620 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1621 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001622
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001623 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1624 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1625
1626 // We use the refreshStartTime which might be sampled a little later than
1627 // when we started doing work for this frame, but that should be okay
1628 // since updateCompositorTiming has snapping logic.
1629 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001630 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001631 CompositorTiming compositorTiming;
1632 {
1633 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1634 compositorTiming = mCompositorTiming;
1635 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001636
Robert Carr2047fae2016-11-28 14:09:09 -08001637 mDrawingState.traverseInZOrder([&](Layer* layer) {
1638 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001639 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001640 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001641 recordBufferingStats(layer->getName().string(),
1642 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001643 }
Robert Carr2047fae2016-11-28 14:09:09 -08001644 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001645
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001646 if (presentFenceTime->isValid()) {
1647 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001648 enableHardwareVsync();
1649 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001650 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001651 }
1652 }
1653
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001654 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001655 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001656 enableHardwareVsync();
1657 }
1658 }
1659
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001660 if (mAnimCompositionPending) {
1661 mAnimCompositionPending = false;
1662
Brian Anderson4e606e32017-03-16 15:34:57 -07001663 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001664 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001665 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001666 } else {
1667 // The HWC doesn't support present fences, so use the refresh
1668 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001669 nsecs_t presentTime =
1670 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001671 mAnimFrameTracker.setActualPresentTime(presentTime);
1672 }
1673 mAnimFrameTracker.advanceFrame();
1674 }
Dan Stozab90cf072015-03-05 11:05:59 -08001675
1676 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1677 return;
1678 }
1679
1680 nsecs_t currentTime = systemTime();
1681 if (mHasPoweredOff) {
1682 mHasPoweredOff = false;
1683 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001684 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001685 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001686 if (numPeriods < NUM_BUCKETS - 1) {
1687 mFrameBuckets[numPeriods] += elapsedTime;
1688 } else {
1689 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1690 }
1691 mTotalTime += elapsedTime;
1692 }
1693 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001694}
1695
1696void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001697 ATRACE_CALL();
1698 ALOGV("rebuildLayerStacks");
1699
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001701 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1702 ATRACE_CALL();
1703 mVisibleRegionsDirty = false;
1704 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001705
Jeff Sharkey76488112017-02-27 14:15:18 -07001706 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1707 Region opaqueRegion;
1708 Region dirtyRegion;
1709 Vector<sp<Layer>> layersSortedByZ;
1710 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1711 const Transform& tr(displayDevice->getTransform());
1712 const Rect bounds(displayDevice->getBounds());
1713 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001714 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001715
Jeff Sharkey76488112017-02-27 14:15:18 -07001716 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001717 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1718 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001719 Region drawRegion(tr.transform(
1720 layer->visibleNonTransparentRegion));
1721 drawRegion.andSelf(bounds);
1722 if (!drawRegion.isEmpty()) {
1723 layersSortedByZ.add(layer);
1724 } else {
1725 // Clear out the HWC layer if this layer was
1726 // previously visible, but no longer is
Steven Thomasd7f49c52017-07-26 18:48:28 -07001727 layer->destroyHwcLayer(
1728 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001729 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001730 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001731 // WM changes displayDevice->layerStack upon sleep/awake.
1732 // Here we make sure we delete the HWC layers even if
1733 // WM changed their layer stack.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001734 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001735 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001736 });
1737 }
1738 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1739 displayDevice->undefinedRegion.set(bounds);
1740 displayDevice->undefinedRegion.subtractSelf(
1741 tr.transform(opaqueRegion));
1742 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001743 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001744 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001745}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001746
Romain Guy0147a172017-06-01 13:53:56 -07001747mat4 SurfaceFlinger::computeSaturationMatrix() const {
1748 if (mSaturation == 1.0f) {
1749 return mat4();
1750 }
1751
1752 // Rec.709 luma coefficients
1753 float3 luminance{0.213f, 0.715f, 0.072f};
1754 luminance *= 1.0f - mSaturation;
1755 return mat4(
1756 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1757 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1758 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1759 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1760 );
1761}
1762
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001763// pickColorMode translates a given dataspace into the best available color mode.
1764// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001765android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Romain Guy54f154a2017-10-24 21:40:32 +01001766 if (mForceNativeColorMode) {
1767 return HAL_COLOR_MODE_NATIVE;
1768 }
1769
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001770 switch (dataSpace) {
1771 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1772 // system expects.
1773 case HAL_DATASPACE_UNKNOWN:
1774 case HAL_DATASPACE_SRGB:
1775 case HAL_DATASPACE_V0_SRGB:
1776 return HAL_COLOR_MODE_SRGB;
1777 break;
1778
1779 case HAL_DATASPACE_DISPLAY_P3:
1780 return HAL_COLOR_MODE_DISPLAY_P3;
1781 break;
1782
1783 default:
1784 // TODO (courtneygo): Do we want to assert an error here?
1785 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1786 dataSpace);
1787 return HAL_COLOR_MODE_SRGB;
1788 break;
1789 }
1790}
1791
Romain Guy0147a172017-06-01 13:53:56 -07001792android_dataspace SurfaceFlinger::bestTargetDataSpace(
1793 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001794 // Only support sRGB and Display-P3 right now.
1795 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1796 return HAL_DATASPACE_DISPLAY_P3;
1797 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001798 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1799 return HAL_DATASPACE_DISPLAY_P3;
1800 }
1801 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1802 return HAL_DATASPACE_DISPLAY_P3;
1803 }
1804
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001805 return HAL_DATASPACE_V0_SRGB;
1806}
1807
Mathias Agopiancd60f992012-08-16 16:28:27 -07001808void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 ATRACE_CALL();
1810 ALOGV("setUpHWComposer");
1811
Jesse Hall028dc8f2013-08-20 16:35:32 -07001812 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001813 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1814 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1815 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1816
1817 // If nothing has changed (!dirty), don't recompose.
1818 // If something changed, but we don't currently have any visible layers,
1819 // and didn't when we last did a composition, then skip it this time.
1820 // The second rule does two things:
1821 // - When all layers are removed from a display, we'll emit one black
1822 // frame, then nothing more until we get new layers.
1823 // - When a display is created with a private layer stack, we won't
1824 // emit any black frames until a layer is added to the layer stack.
1825 bool mustRecompose = dirty && !(empty && wasEmpty);
1826
1827 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1828 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1829 mustRecompose ? "doing" : "skipping",
1830 dirty ? "+" : "-",
1831 empty ? "+" : "-",
1832 wasEmpty ? "+" : "-");
1833
Dan Stoza71433162014-02-04 16:22:36 -08001834 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001835
1836 if (mustRecompose) {
1837 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1838 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001839 }
1840
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 // build the h/w work list
1842 if (CC_UNLIKELY(mGeometryInvalid)) {
1843 mGeometryInvalid = false;
1844 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1845 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1846 const auto hwcId = displayDevice->getHwcDisplayId();
1847 if (hwcId >= 0) {
1848 const Vector<sp<Layer>>& currentLayers(
1849 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001850 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001851 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001852 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001853 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001856 }
1857 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001858
Robert Carrae060832016-11-28 10:51:00 -08001859 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001860 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001861 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001862 }
1863 }
1864 }
1865 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001866 }
Riley Andrews03414a12014-07-01 14:22:59 -07001867
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001868
Romain Guy0147a172017-06-01 13:53:56 -07001869 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001870
Dan Stoza9e56aa02015-11-02 13:00:03 -08001871 // Set the per-frame data
1872 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1873 auto& displayDevice = mDisplays[displayId];
1874 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001875
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 if (hwcId < 0) {
1877 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001878 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001879 if (colorMatrix != mPreviousColorMatrix) {
1880 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1881 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1882 "display %zd: %d", displayId, result);
1883 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1885 layer->setPerFrameData(displayDevice);
1886 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001887
1888 if (hasWideColorDisplay) {
1889 android_color_mode newColorMode;
1890 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1891
1892 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1893 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1894 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1895 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1896 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1897 }
1898 newColorMode = pickColorMode(newDataSpace);
1899
Thierry Strudel2924d012017-08-14 15:19:37 -07001900 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001901 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 }
1903
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001904 mPreviousColorMatrix = colorMatrix;
1905
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001907 auto& displayDevice = mDisplays[displayId];
1908 if (!displayDevice->isDisplayOn()) {
1909 continue;
1910 }
1911
1912 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001913 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1914 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001915 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001916}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001917
Mathias Agopiancd60f992012-08-16 16:28:27 -07001918void SurfaceFlinger::doComposition() {
1919 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001920 ALOGV("doComposition");
1921
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001922 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001923 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001924 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001925 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001926 // transform the dirty region into this screen's coordinate space
1927 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001928
1929 // repaint the framebuffer (if needed)
1930 doDisplayComposition(hw, dirtyRegion);
1931
Mathias Agopiancd60f992012-08-16 16:28:27 -07001932 hw->dirtyRegion.clear();
1933 hw->flip(hw->swapRegion);
1934 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001935 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001936 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001937 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001938}
1939
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001940void SurfaceFlinger::postFramebuffer()
1941{
Mathias Agopian841cde52012-03-01 15:44:37 -08001942 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001943 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001944
Mathias Agopiana44b0412011-10-16 18:46:35 -07001945 const nsecs_t now = systemTime();
1946 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001947
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1949 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001950 if (!displayDevice->isDisplayOn()) {
1951 continue;
1952 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001953 const auto hwcId = displayDevice->getHwcDisplayId();
1954 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001955 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001956 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001957 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001958 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1960 sp<Fence> releaseFence = Fence::NO_FENCE;
1961 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1962 releaseFence = displayDevice->getClientTargetAcquireFence();
1963 } else {
1964 auto hwcLayer = layer->getHwcLayer(hwcId);
1965 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001966 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001967 layer->onLayerDisplayed(releaseFence);
1968 }
1969 if (hwcId >= 0) {
1970 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001971 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001972 }
1973
Mathias Agopiana44b0412011-10-16 18:46:35 -07001974 mLastSwapBufferTime = systemTime() - now;
1975 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001976
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001977 // |mStateLock| not needed as we are on the main thread
1978 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001979 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1980 logFrameStats();
1981 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001982}
1983
Mathias Agopian87baae12012-07-31 12:38:26 -07001984void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985{
Mathias Agopian841cde52012-03-01 15:44:37 -08001986 ATRACE_CALL();
1987
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001988 // here we keep a copy of the drawing state (that is the state that's
1989 // going to be overwritten by handleTransactionLocked()) outside of
1990 // mStateLock so that the side-effects of the State assignment
1991 // don't happen with mStateLock held (which can cause deadlocks).
1992 State drawingState(mDrawingState);
1993
Mathias Agopianca4d3602011-05-19 15:38:14 -07001994 Mutex::Autolock _l(mStateLock);
1995 const nsecs_t now = systemTime();
1996 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001997
Mathias Agopianca4d3602011-05-19 15:38:14 -07001998 // Here we're guaranteed that some transaction flags are set
1999 // so we can call handleTransactionLocked() unconditionally.
2000 // We call getTransactionFlags(), which will also clear the flags,
2001 // with mStateLock held to guarantee that mCurrentState won't change
2002 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002003
Mathias Agopiane57f2922012-08-09 16:29:12 -07002004 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002005 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002006
Mathias Agopianca4d3602011-05-19 15:38:14 -07002007 mLastTransactionTime = systemTime() - now;
2008 mDebugInTransaction = 0;
2009 invalidateHwcGeometry();
2010 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002011}
2012
Mathias Agopian87baae12012-07-31 12:38:26 -07002013void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002014{
Dan Stoza7dde5992015-05-22 09:51:44 -07002015 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002016 mCurrentState.traverseInZOrder([](Layer* layer) {
2017 layer->notifyAvailableFrames();
2018 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002019
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002020 /*
2021 * Traversal of the children
2022 * (perform the transaction for each of them if needed)
2023 */
2024
Mathias Agopian3559b072012-08-15 13:46:03 -07002025 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002026 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002027 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002028 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002029
2030 const uint32_t flags = layer->doTransaction(0);
2031 if (flags & Layer::eVisibleRegion)
2032 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002033 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002034 }
2035
2036 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002037 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002038 */
2039
Mathias Agopiane57f2922012-08-09 16:29:12 -07002040 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002041 // here we take advantage of Vector's copy-on-write semantics to
2042 // improve performance by skipping the transaction entirely when
2043 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002044 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2045 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002046 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002048 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002049 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002050
2051 // find the displays that were removed
2052 // (ie: in drawing state but not in current state)
2053 // also handle displays that changed
2054 // (ie: displays that are in both lists)
2055 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002056 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2057 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002058 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002059 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002060 // Call makeCurrent() on the primary display so we can
2061 // be sure that nothing associated with this display
2062 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002063 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002064 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002065 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002066 if (hw != NULL)
2067 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002068 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002069 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002070 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002071 } else {
2072 ALOGW("trying to remove the main display");
2073 }
2074 } else {
2075 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002076 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002077 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002078 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2079 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002080 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002081 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002082 // recreating the DisplayDevice, so we just remove it
2083 // from the drawing state, so that it get re-added
2084 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002085 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002086 if (hw != NULL)
2087 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002088 mDisplays.removeItem(display);
2089 mDrawingState.displays.removeItemsAt(i);
2090 dc--; i--;
2091 // at this point we must loop to the next item
2092 continue;
2093 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002094
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002095 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002096 if (disp != NULL) {
2097 if (state.layerStack != draw[i].layerStack) {
2098 disp->setLayerStack(state.layerStack);
2099 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002100 if ((state.orientation != draw[i].orientation)
2101 || (state.viewport != draw[i].viewport)
2102 || (state.frame != draw[i].frame))
2103 {
2104 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002105 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002106 }
Michael Lentine47e45402014-07-18 15:34:25 -07002107 if (state.width != draw[i].width || state.height != draw[i].height) {
2108 disp->setDisplaySize(state.width, state.height);
2109 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002110 }
2111 }
2112 }
2113
2114 // find displays that were added
2115 // (ie: in current state but not in drawing state)
2116 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002117 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002118 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002119
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002120 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002121 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002122 sp<IGraphicBufferProducer> bqProducer;
2123 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002124 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002125
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002127 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002128 // Virtual displays without a surface are dormant:
2129 // they have external state (layer stack, projection,
2130 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002131 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002132
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002133 // Allow VR composer to use virtual displays.
Steven Thomasd7f49c52017-07-26 18:48:28 -07002134 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002135 int width = 0;
2136 int status = state.surface->query(
2137 NATIVE_WINDOW_WIDTH, &width);
2138 ALOGE_IF(status != NO_ERROR,
2139 "Unable to query width (%d)", status);
2140 int height = 0;
2141 status = state.surface->query(
2142 NATIVE_WINDOW_HEIGHT, &height);
2143 ALOGE_IF(status != NO_ERROR,
2144 "Unable to query height (%d)", status);
2145 int intFormat = 0;
2146 status = state.surface->query(
2147 NATIVE_WINDOW_FORMAT, &intFormat);
2148 ALOGE_IF(status != NO_ERROR,
2149 "Unable to query format (%d)", status);
2150 auto format = static_cast<android_pixel_format_t>(
2151 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002152
Dan Stoza8cf150a2016-08-02 10:27:31 -07002153 mHwc->allocateVirtualDisplay(width, height, &format,
2154 &hwcId);
2155 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156
Dan Stoza5cf424b2016-05-20 14:02:39 -07002157 // TODO: Plumb requested format back up to consumer
2158
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 sp<VirtualDisplaySurface> vds =
2160 new VirtualDisplaySurface(*mHwc,
2161 hwcId, state.surface, bqProducer,
2162 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002163
2164 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002165 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002166 }
2167 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002168 ALOGE_IF(state.surface!=NULL,
2169 "adding a supported display, but rendering "
2170 "surface is provided (%p), ignoring it",
2171 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002172
2173 hwcId = state.type;
2174 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2175 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002176 }
2177
2178 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002179 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002180 sp<DisplayDevice> hw =
2181 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2182 dispSurface, producer,
2183 mRenderEngine->getEGLConfig(),
2184 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002185 hw->setLayerStack(state.layerStack);
2186 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002187 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002188 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002189 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002190 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002191 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002192 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002193 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002194 }
2195 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002196 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002197 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002198
Mathias Agopian84300952012-11-21 16:02:13 -08002199 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2200 // The transform hint might have changed for some layers
2201 // (either because a display has changed, or because a layer
2202 // as changed).
2203 //
2204 // Walk through all the layers in currentLayers,
2205 // and update their transform hint.
2206 //
2207 // If a layer is visible only on a single display, then that
2208 // display is used to calculate the hint, otherwise we use the
2209 // default display.
2210 //
2211 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2212 // the hint is set before we acquire a buffer from the surface texture.
2213 //
2214 // NOTE: layer transactions have taken place already, so we use their
2215 // drawing state. However, SurfaceFlinger's own transaction has not
2216 // happened yet, so we must use the current state layer list
2217 // (soon to become the drawing state list).
2218 //
2219 sp<const DisplayDevice> disp;
2220 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002221 bool first = true;
2222 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002223 // NOTE: we rely on the fact that layers are sorted by
2224 // layerStack first (so we don't have to traverse the list
2225 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002226 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002227 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002228 currentlayerStack = layerStack;
2229 // figure out if this layerstack is mirrored
2230 // (more than one display) if so, pick the default display,
2231 // if not, pick the only display it's on.
2232 disp.clear();
2233 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2234 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002235 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002236 if (disp == NULL) {
2237 disp = hw;
2238 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002239 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002240 break;
2241 }
2242 }
2243 }
2244 }
Chet Haase91d25932013-04-11 15:24:55 -07002245 if (disp == NULL) {
2246 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2247 // redraw after transform hint changes. See bug 8508397.
2248
2249 // could be null when this layer is using a layerStack
2250 // that is not visible on any display. Also can occur at
2251 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002252 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002253 }
Chet Haase91d25932013-04-11 15:24:55 -07002254 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002255
2256 first = false;
2257 });
Mathias Agopian84300952012-11-21 16:02:13 -08002258 }
2259
2260
Mathias Agopian3559b072012-08-15 13:46:03 -07002261 /*
2262 * Perform our own transaction if needed
2263 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002264
2265 if (mLayersAdded) {
2266 mLayersAdded = false;
2267 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002268 mVisibleRegionsDirty = true;
2269 }
2270
2271 // some layers might have been removed, so
2272 // we need to update the regions they're exposing.
2273 if (mLayersRemoved) {
2274 mLayersRemoved = false;
2275 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002276 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002277 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002278 // this layer is not visible anymore
2279 // TODO: we could traverse the tree from front to back and
2280 // compute the actual visible region
2281 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002282 Region visibleReg;
2283 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002284 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002285 }
Robert Carr2047fae2016-11-28 14:09:09 -08002286 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002287 }
2288
2289 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002290
2291 updateCursorAsync();
2292}
2293
2294void SurfaceFlinger::updateCursorAsync()
2295{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002296 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2297 auto& displayDevice = mDisplays[displayId];
2298 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002299 continue;
2300 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002301
2302 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2303 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002304 }
2305 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002306}
2307
2308void SurfaceFlinger::commitTransaction()
2309{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002310 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002311 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002312 for (const auto& l : mLayersPendingRemoval) {
2313 recordBufferingStats(l->getName().string(),
2314 l->getOccupancyHistory(true));
2315 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002316 }
2317 mLayersPendingRemoval.clear();
2318 }
2319
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002320 // If this transaction is part of a window animation then the next frame
2321 // we composite should be considered an animation as well.
2322 mAnimCompositionPending = mAnimTransactionPending;
2323
Mathias Agopian4fec8732012-06-29 14:12:52 -07002324 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002325 mDrawingState.traverseInZOrder([](Layer* layer) {
2326 layer->commitChildList();
2327 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002328 mTransactionPending = false;
2329 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002330 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002331}
2332
Chia-I Wuab0c3192017-08-01 11:29:00 -07002333void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002334 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335{
Mathias Agopian841cde52012-03-01 15:44:37 -08002336 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339 Region aboveOpaqueLayers;
2340 Region aboveCoveredLayers;
2341 Region dirty;
2342
Mathias Agopian87baae12012-07-31 12:38:26 -07002343 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344
Robert Carr2047fae2016-11-28 14:09:09 -08002345 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002347 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348
Jesse Hall01e29052013-02-19 16:13:35 -08002349 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002350 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002351 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002352
Mathias Agopianab028732010-03-16 16:41:46 -07002353 /*
2354 * opaqueRegion: area of a surface that is fully opaque.
2355 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002357
2358 /*
2359 * visibleRegion: area of a surface that is visible on screen
2360 * and not fully transparent. This is essentially the layer's
2361 * footprint minus the opaque regions above it.
2362 * Areas covered by a translucent surface are considered visible.
2363 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002365
2366 /*
2367 * coveredRegion: area of a surface that is covered by all
2368 * visible regions above it (which includes the translucent areas).
2369 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002371
Jesse Halla8026d22012-09-25 13:25:04 -07002372 /*
2373 * transparentRegion: area of a surface that is hinted to be completely
2374 * transparent. This is only used to tell when the layer has no visible
2375 * non-transparent regions and can be removed from the layer list. It
2376 * does not affect the visibleRegion of this layer or any layers
2377 * beneath it. The hint may not be correct if apps don't respect the
2378 * SurfaceView restrictions (which, sadly, some don't).
2379 */
2380 Region transparentRegion;
2381
Mathias Agopianab028732010-03-16 16:41:46 -07002382
2383 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002384 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002385 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002386 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002387 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002388 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002389 if (!visibleRegion.isEmpty()) {
2390 // Remove the transparent area from the visible region
2391 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002392 if (tr.preserveRects()) {
2393 // transform the transparent region
2394 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002395 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002396 // transformation too complex, can't do the
2397 // transparent region optimization.
2398 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002399 }
Mathias Agopianab028732010-03-16 16:41:46 -07002400 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002401
Mathias Agopianab028732010-03-16 16:41:46 -07002402 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002403 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002404 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002405 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2406 // the opaque region is the layer's footprint
2407 opaqueRegion = visibleRegion;
2408 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409 }
2410 }
2411
Mathias Agopianab028732010-03-16 16:41:46 -07002412 // Clip the covered region to the visible region
2413 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2414
2415 // Update aboveCoveredLayers for next (lower) layer
2416 aboveCoveredLayers.orSelf(visibleRegion);
2417
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002418 // subtract the opaque region covered by the layers above us
2419 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002420
2421 // compute this layer's dirty region
2422 if (layer->contentDirty) {
2423 // we need to invalidate the whole region
2424 dirty = visibleRegion;
2425 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002427 layer->contentDirty = false;
2428 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002429 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002430 * the exposed region consists of two components:
2431 * 1) what's VISIBLE now and was COVERED before
2432 * 2) what's EXPOSED now less what was EXPOSED before
2433 *
2434 * note that (1) is conservative, we start with the whole
2435 * visible region but only keep what used to be covered by
2436 * something -- which mean it may have been exposed.
2437 *
2438 * (2) handles areas that were not covered by anything but got
2439 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002440 */
Mathias Agopianab028732010-03-16 16:41:46 -07002441 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002442 const Region oldVisibleRegion = layer->visibleRegion;
2443 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002444 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2445 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002446 }
2447 dirty.subtractSelf(aboveOpaqueLayers);
2448
2449 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002450 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451
Mathias Agopianab028732010-03-16 16:41:46 -07002452 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002454
Jesse Halla8026d22012-09-25 13:25:04 -07002455 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 layer->setVisibleRegion(visibleRegion);
2457 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002458 layer->setVisibleNonTransparentRegion(
2459 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002460 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461
Mathias Agopian87baae12012-07-31 12:38:26 -07002462 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463}
2464
Chia-I Wuab0c3192017-08-01 11:29:00 -07002465void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002466 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002467 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002468 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002469 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002470 }
2471 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002472}
2473
Dan Stoza6b9454d2014-11-07 16:00:59 -08002474bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 ALOGV("handlePageFlip");
2477
Brian Andersond6927fb2016-07-23 23:37:30 -07002478 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479
Mathias Agopian4fec8732012-06-29 14:12:52 -07002480 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002481 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002482 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002483
2484 // Store the set of layers that need updates. This set must not change as
2485 // buffers are being latched, as this could result in a deadlock.
2486 // Example: Two producers share the same command stream and:
2487 // 1.) Layer 0 is latched
2488 // 2.) Layer 0 gets a new frame
2489 // 2.) Layer 1 gets a new frame
2490 // 3.) Layer 1 is latched.
2491 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2492 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002493 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002494 if (layer->hasQueuedFrame()) {
2495 frameQueued = true;
2496 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002497 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002498 } else {
2499 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002500 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002501 } else {
2502 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002503 }
Robert Carr2047fae2016-11-28 14:09:09 -08002504 });
2505
Dan Stoza9e56aa02015-11-02 13:00:03 -08002506 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002507 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002508 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002509 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002510 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002511 newDataLatched = true;
2512 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002513 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002514
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002515 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002516
2517 // If we will need to wake up at some time in the future to deal with a
2518 // queued frame that shouldn't be displayed during this vsync period, wake
2519 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002520 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002521 signalLayerUpdate();
2522 }
2523
2524 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002525 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526}
2527
Mathias Agopianad456f92011-01-13 17:53:01 -08002528void SurfaceFlinger::invalidateHwcGeometry()
2529{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002530 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002531}
2532
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002533
Fabien Sanglard830b8472016-11-30 16:35:58 -08002534void SurfaceFlinger::doDisplayComposition(
2535 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002536 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537{
Dan Stoza71433162014-02-04 16:22:36 -08002538 // We only need to actually compose the display if:
2539 // 1) It is being handled by hardware composer, which may need this to
2540 // keep its virtual display state machine in sync, or
2541 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002542 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002543 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002544 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002545 return;
2546 }
2547
Dan Stoza9e56aa02015-11-02 13:00:03 -08002548 ALOGV("doDisplayComposition");
2549
Mathias Agopian87baae12012-07-31 12:38:26 -07002550 Region dirtyRegion(inDirtyRegion);
2551
Mathias Agopianb8a55602009-06-26 19:06:36 -07002552 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002553 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554
Fabien Sanglard830b8472016-11-30 16:35:58 -08002555 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002556 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002557 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2558 // takes a rectangle, we must make sure to update that whole
2559 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002560 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002561 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002562 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002563 // We need to redraw the rectangle that will be updated
2564 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002565 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002566 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002567 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002568 } else {
2569 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002570 dirtyRegion.set(displayDevice->bounds());
2571 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572 }
2573 }
2574
Fabien Sanglard830b8472016-11-30 16:35:58 -08002575 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002577 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002578 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002579
2580 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002581 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582}
2583
Dan Stoza9e56aa02015-11-02 13:00:03 -08002584bool SurfaceFlinger::doComposeSurfaces(
2585 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002586{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002587 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002588
Dan Stoza9e56aa02015-11-02 13:00:03 -08002589 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002590
2591 mat4 oldColorMatrix;
2592 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2593 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2594 if (applyColorMatrix) {
2595 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2596 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2597 }
2598
Dan Stoza9e56aa02015-11-02 13:00:03 -08002599 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2600 if (hasClientComposition) {
2601 ALOGV("hasClientComposition");
2602
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002603#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01002604 mRenderEngine->setWideColor(
2605 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
2606 mRenderEngine->setColorMode(mForceNativeColorMode ?
2607 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002608#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002610 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002611 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002612 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002613
2614 // |mStateLock| not needed as we are on the main thread
2615 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002616 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2617 }
2618 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002619 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002620
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002621 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002622 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2623 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002624 // when using overlays, we assume a fully transparent framebuffer
2625 // NOTE: we could reduce how much we need to clear, for instance
2626 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002627 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002628 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002629 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002630 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002631 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002632 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002633
2634 // we remove the scissor part
2635 // we're left with the letterbox region
2636 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002637 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002638
2639 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002640 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002641
2642 // but limit it to the dirty region
2643 region.andSelf(dirty);
2644
Mathias Agopianb9494d52012-04-18 02:28:45 -07002645 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002646 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002647 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002648 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002649 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002650 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002651
Dan Stoza9e56aa02015-11-02 13:00:03 -08002652 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002653 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002654 // scissor on the main display. It should never be needed
2655 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 const Rect& bounds(displayDevice->getBounds());
2657 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002658 if (scissor != bounds) {
2659 // scissor doesn't match the screen's dimensions, so we
2660 // need to clear everything outside of it and enable
2661 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002662
Mathias Agopianf45c5102012-10-24 16:29:17 -07002663 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 const uint32_t height = displayDevice->getHeight();
2665 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002666 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002667 }
2668 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002669 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002670
Mathias Agopian85d751c2012-08-29 16:59:24 -07002671 /*
2672 * and then, render the layers targeted at the framebuffer
2673 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002674
Dan Stoza9e56aa02015-11-02 13:00:03 -08002675 ALOGV("Rendering client layers");
2676 const Transform& displayTransform = displayDevice->getTransform();
2677 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002678 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002679 bool firstLayer = true;
2680 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2681 const Region clip(dirty.intersect(
2682 displayTransform.transform(layer->visibleRegion)));
2683 ALOGV("Layer: %s", layer->getName().string());
2684 ALOGV(" Composition type: %s",
2685 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002686 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002687 switch (layer->getCompositionType(hwcId)) {
2688 case HWC2::Composition::Cursor:
2689 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002690 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002691 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002692 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2694 layer->isOpaque(state) && (state.alpha == 1.0f)
2695 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002696 // never clear the very first layer since we're
2697 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002698 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002699 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002700 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002701 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702 case HWC2::Composition::Client: {
2703 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002704 break;
2705 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002706 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002707 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002708 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002709 } else {
2710 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002711 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002712 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002713 }
2714 } else {
2715 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002716 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002717 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002719 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002720 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002721 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002722 }
2723 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002724
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002725 if (applyColorMatrix) {
2726 getRenderEngine().setupColorTransform(oldColorMatrix);
2727 }
2728
Mathias Agopianf45c5102012-10-24 16:29:17 -07002729 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002731 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002732}
2733
Fabien Sanglard830b8472016-11-30 16:35:58 -08002734void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2735 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002736 RenderEngine& engine(getRenderEngine());
2737 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738}
2739
Dan Stoza7d89d062015-04-30 13:29:25 -07002740status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002741 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002742 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002743 const sp<Layer>& lbc,
2744 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002745{
Dan Stoza7d89d062015-04-30 13:29:25 -07002746 // add this layer to the current state list
2747 {
2748 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002749 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002750 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2751 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002752 return NO_MEMORY;
2753 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002754 if (parent == nullptr) {
2755 mCurrentState.layersSortedByZ.add(lbc);
2756 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002757 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2758 ALOGE("addClientLayer called with a removed parent");
2759 return NAME_NOT_FOUND;
2760 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 parent->addChild(lbc);
2762 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002763
Dan Stoza7d89d062015-04-30 13:29:25 -07002764 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002765 mLayersAdded = true;
2766 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002767 }
2768
Mathias Agopian96f08192010-06-02 23:28:45 -07002769 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002770 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002771
Dan Stoza7d89d062015-04-30 13:29:25 -07002772 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002773}
2774
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002775status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002776 Mutex::Autolock _l(mStateLock);
2777
Robert Carr1f0a16a2016-10-24 16:27:39 -07002778 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002779 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002780 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002781 if (topLevelOnly) {
2782 return NO_ERROR;
2783 }
2784
Chia-I Wu98f1c102017-05-30 14:54:08 -07002785 sp<Layer> ancestor = p;
2786 while (ancestor->getParent() != nullptr) {
2787 ancestor = ancestor->getParent();
2788 }
2789 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2790 ALOGE("removeLayer called with a layer whose parent has been removed");
2791 return NAME_NOT_FOUND;
2792 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002793
2794 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002795 } else {
2796 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002797 }
2798
Robert Carr136e2f62017-02-08 17:54:29 -08002799 // As a matter of normal operation, the LayerCleaner will produce a second
2800 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2801 // so we will succeed in promoting it, but it's already been removed
2802 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2803 // otherwise something has gone wrong and we are leaking the layer.
2804 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002805 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2806 layer->getName().string(),
2807 (p != nullptr) ? p->getName().string() : "no-parent");
2808 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002809 } else if (index < 0) {
2810 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002811 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002812
Chia-I Wuc6657022017-08-15 11:18:17 -07002813 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 mLayersPendingRemoval.add(layer);
2815 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002816 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002817 setTransactionFlags(eTransactionNeeded);
2818 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819}
2820
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002821uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002822 return android_atomic_release_load(&mTransactionFlags);
2823}
2824
Mathias Agopian3f844832013-08-07 21:24:32 -07002825uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2827}
2828
Mathias Agopian3f844832013-08-07 21:24:32 -07002829uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2831 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002832 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 }
2834 return old;
2835}
2836
Mathias Agopian8b33f032012-07-24 20:43:54 -07002837void SurfaceFlinger::setTransactionState(
2838 const Vector<ComposerState>& state,
2839 const Vector<DisplayState>& displays,
2840 uint32_t flags)
2841{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002842 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002843 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002844 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002845
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002846 if (flags & eAnimation) {
2847 // For window updates that are part of an animation we must wait for
2848 // previous animation "frames" to be handled.
2849 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002850 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002851 if (CC_UNLIKELY(err != NO_ERROR)) {
2852 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002853 // caller after a few seconds.
2854 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2855 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002856 mAnimTransactionPending = false;
2857 break;
2858 }
2859 }
2860 }
2861
Mathias Agopiane57f2922012-08-09 16:29:12 -07002862 size_t count = displays.size();
2863 for (size_t i=0 ; i<count ; i++) {
2864 const DisplayState& s(displays[i]);
2865 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002866 }
2867
Mathias Agopiane57f2922012-08-09 16:29:12 -07002868 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002869 for (size_t i=0 ; i<count ; i++) {
2870 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002871 // Here we need to check that the interface we're given is indeed
2872 // one of our own. A malicious client could give us a NULL
2873 // IInterface, or one of its own or even one of our own but a
2874 // different type. All these situations would cause us to crash.
2875 //
2876 // NOTE: it would be better to use RTTI as we could directly check
2877 // that we have a Client*. however, RTTI is disabled in Android.
2878 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002879 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002880 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002881 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002882 sp<Client> client( static_cast<Client *>(s.client.get()) );
2883 transactionFlags |= setClientStateLocked(client, s.state);
2884 }
2885 }
2886 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002887 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002888
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002889 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2890 // anyway. This can be used as a flush mechanism for previous async transactions.
2891 // Empty animation transaction can be used to simulate back-pressure, so also force a
2892 // transaction for empty animation transactions.
2893 if (transactionFlags == 0 &&
2894 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002895 transactionFlags = eTransactionNeeded;
2896 }
2897
Mathias Agopian386aa982011-11-07 21:58:03 -08002898 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002899 if (mInterceptor.isEnabled()) {
2900 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2901 }
Irvel468051e2016-06-13 16:44:44 -07002902
Mathias Agopian386aa982011-11-07 21:58:03 -08002903 // this triggers the transaction
2904 setTransactionFlags(transactionFlags);
2905
2906 // if this is a synchronous transaction, wait for it to take effect
2907 // before returning.
2908 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002909 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002910 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002911 if (flags & eAnimation) {
2912 mAnimTransactionPending = true;
2913 }
2914 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002915 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2916 if (CC_UNLIKELY(err != NO_ERROR)) {
2917 // just in case something goes wrong in SF, return to the
2918 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002919 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2920 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002921 break;
2922 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002923 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924 }
2925}
2926
Mathias Agopiane57f2922012-08-09 16:29:12 -07002927uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2928{
Jesse Hall9a143922012-10-04 16:29:19 -07002929 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2930 if (dpyIdx < 0)
2931 return 0;
2932
Mathias Agopiane57f2922012-08-09 16:29:12 -07002933 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002934 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002935 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002936 const uint32_t what = s.what;
2937 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002938 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002939 disp.surface = s.surface;
2940 flags |= eDisplayTransactionNeeded;
2941 }
2942 }
2943 if (what & DisplayState::eLayerStackChanged) {
2944 if (disp.layerStack != s.layerStack) {
2945 disp.layerStack = s.layerStack;
2946 flags |= eDisplayTransactionNeeded;
2947 }
2948 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002949 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002950 if (disp.orientation != s.orientation) {
2951 disp.orientation = s.orientation;
2952 flags |= eDisplayTransactionNeeded;
2953 }
2954 if (disp.frame != s.frame) {
2955 disp.frame = s.frame;
2956 flags |= eDisplayTransactionNeeded;
2957 }
2958 if (disp.viewport != s.viewport) {
2959 disp.viewport = s.viewport;
2960 flags |= eDisplayTransactionNeeded;
2961 }
2962 }
Michael Lentine47e45402014-07-18 15:34:25 -07002963 if (what & DisplayState::eDisplaySizeChanged) {
2964 if (disp.width != s.width) {
2965 disp.width = s.width;
2966 flags |= eDisplayTransactionNeeded;
2967 }
2968 if (disp.height != s.height) {
2969 disp.height = s.height;
2970 flags |= eDisplayTransactionNeeded;
2971 }
2972 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002973 }
2974 return flags;
2975}
2976
2977uint32_t SurfaceFlinger::setClientStateLocked(
2978 const sp<Client>& client,
2979 const layer_state_t& s)
2980{
2981 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002982 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002983 if (layer != 0) {
2984 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002985 bool geometryAppliesWithResize =
2986 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002987 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002988 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002989 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002990 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002991 }
2992 if (what & layer_state_t::eLayerChanged) {
2993 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002994 const auto& p = layer->getParent();
2995 if (p == nullptr) {
2996 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2997 if (layer->setLayer(s.z) && idx >= 0) {
2998 mCurrentState.layersSortedByZ.removeAt(idx);
2999 mCurrentState.layersSortedByZ.add(layer);
3000 // we need traversal (state changed)
3001 // AND transaction (list changed)
3002 flags |= eTransactionNeeded|eTraversalNeeded;
3003 }
3004 } else {
3005 if (p->setChildLayer(layer, s.z)) {
3006 flags |= eTransactionNeeded|eTraversalNeeded;
3007 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003008 }
3009 }
Robert Carrdb66e622017-04-10 16:55:57 -07003010 if (what & layer_state_t::eRelativeLayerChanged) {
3011 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
3012 flags |= eTransactionNeeded|eTraversalNeeded;
3013 }
3014 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003015 if (what & layer_state_t::eSizeChanged) {
3016 if (layer->setSize(s.w, s.h)) {
3017 flags |= eTraversalNeeded;
3018 }
3019 }
3020 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003022 flags |= eTraversalNeeded;
3023 }
3024 if (what & layer_state_t::eMatrixChanged) {
3025 if (layer->setMatrix(s.matrix))
3026 flags |= eTraversalNeeded;
3027 }
3028 if (what & layer_state_t::eTransparentRegionChanged) {
3029 if (layer->setTransparentRegionHint(s.transparentRegion))
3030 flags |= eTraversalNeeded;
3031 }
Dan Stoza23116082015-06-18 14:58:39 -07003032 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003033 if (layer->setFlags(s.flags, s.mask))
3034 flags |= eTraversalNeeded;
3035 }
3036 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003037 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003038 flags |= eTraversalNeeded;
3039 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003040 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003041 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003042 flags |= eTraversalNeeded;
3043 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003044 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003045 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003046 // We only allow setting layer stacks for top level layers,
3047 // everything else inherits layer stack from its parent.
3048 if (layer->hasParent()) {
3049 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3050 layer->getName().string());
3051 } else if (idx < 0) {
3052 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3053 "that also does not appear in the top level layer list. Something"
3054 " has gone wrong.", layer->getName().string());
3055 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003056 mCurrentState.layersSortedByZ.removeAt(idx);
3057 mCurrentState.layersSortedByZ.add(layer);
3058 // we need traversal (state changed)
3059 // AND transaction (list changed)
3060 flags |= eTransactionNeeded|eTraversalNeeded;
3061 }
3062 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003063 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003064 if (s.barrierHandle != nullptr) {
3065 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3066 } else if (s.barrierGbp != nullptr) {
3067 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3068 if (authenticateSurfaceTextureLocked(gbp)) {
3069 const auto& otherLayer =
3070 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3071 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3072 } else {
3073 ALOGE("Attempt to defer transaction to to an"
3074 " unrecognized GraphicBufferProducer");
3075 }
3076 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003077 // We don't trigger a traversal here because if no other state is
3078 // changed, we don't want this to cause any more work
3079 }
Robert Carr1db73f62016-12-21 12:58:51 -08003080 if (what & layer_state_t::eReparentChildren) {
3081 if (layer->reparentChildren(s.reparentHandle)) {
3082 flags |= eTransactionNeeded|eTraversalNeeded;
3083 }
3084 }
Robert Carr9524cb32017-02-13 11:32:32 -08003085 if (what & layer_state_t::eDetachChildren) {
3086 layer->detachChildren();
3087 }
Robert Carrc3574f72016-03-24 12:19:32 -07003088 if (what & layer_state_t::eOverrideScalingModeChanged) {
3089 layer->setOverrideScalingMode(s.overrideScalingMode);
3090 // We don't trigger a traversal here because if no other state is
3091 // changed, we don't want this to cause any more work
3092 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003093 }
3094 return flags;
3095}
3096
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003097status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003098 const String8& name,
3099 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003100 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003101 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3102 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003104 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003105 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003106 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003107 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003108 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003109
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003110 status_t result = NO_ERROR;
3111
3112 sp<Layer> layer;
3113
Cody Northropbc755282017-03-31 12:00:08 -06003114 String8 uniqueName = getUniqueLayerName(name);
3115
Mathias Agopian3165cc22012-08-08 19:42:09 -07003116 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3117 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003118 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003119 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003120 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003122 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003123 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003124 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003125 handle, gbp, &layer);
3126 break;
3127 default:
3128 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 break;
3130 }
3131
Dan Stoza7d89d062015-04-30 13:29:25 -07003132 if (result != NO_ERROR) {
3133 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003135
Chia-I Wuab0c3192017-08-01 11:29:00 -07003136 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3137 // TODO b/64227542
3138 if (windowType == 441731) {
3139 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3140 layer->setPrimaryDisplayOnly();
3141 }
3142
Albert Chaulk479c60c2017-01-27 14:21:34 -05003143 layer->setInfo(windowType, ownerUid);
3144
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003146 if (result != NO_ERROR) {
3147 return result;
3148 }
Irvelffc9efc2016-07-27 15:16:37 -07003149 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003150
3151 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003152 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003153}
3154
Cody Northropbc755282017-03-31 12:00:08 -06003155String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3156{
3157 bool matchFound = true;
3158 uint32_t dupeCounter = 0;
3159
3160 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3161 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3162
3163 // Loop over layers until we're sure there is no matching name
3164 while (matchFound) {
3165 matchFound = false;
3166 mDrawingState.traverseInZOrder([&](Layer* layer) {
3167 if (layer->getName() == uniqueName) {
3168 matchFound = true;
3169 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3170 }
3171 });
3172 }
3173
3174 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3175
3176 return uniqueName;
3177}
3178
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003179status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3180 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3181 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003182{
3183 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003184 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 case PIXEL_FORMAT_TRANSPARENT:
3186 case PIXEL_FORMAT_TRANSLUCENT:
3187 format = PIXEL_FORMAT_RGBA_8888;
3188 break;
3189 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003190 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003191 break;
3192 }
3193
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003194 *outLayer = new Layer(this, client, name, w, h, flags);
3195 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3196 if (err == NO_ERROR) {
3197 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003198 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003199 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003200
3201 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3202 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203}
3204
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003205status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3206 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3207 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003209 *outLayer = new LayerDim(this, client, name, w, h, flags);
3210 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003211 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003212 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003213}
3214
Mathias Agopianac9fa422013-02-11 16:40:36 -08003215status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216{
Robert Carr9524cb32017-02-13 11:32:32 -08003217 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003218 status_t err = NO_ERROR;
3219 sp<Layer> l(client->getLayerUser(handle));
3220 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003221 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003222 err = removeLayer(l);
3223 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3224 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003225 }
3226 return err;
3227}
3228
Mathias Agopian13127d82013-03-05 17:47:11 -08003229status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003230{
Mathias Agopian67106042013-03-14 19:18:13 -07003231 // called by ~LayerCleaner() when all references to the IBinder (handle)
3232 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003233 sp<Layer> l = layer.promote();
3234 if (l == nullptr) {
3235 // The layer has already been removed, carry on
3236 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003237 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003238 // If we have a parent, then we can continue to live as long as it does.
3239 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Mathias Agopianb60314a2012-04-10 22:09:54 -07003242// ---------------------------------------------------------------------------
3243
Andy McFadden13a082e2012-08-24 10:16:42 -07003244void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003245 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003246 Vector<ComposerState> state;
3247 Vector<DisplayState> displays;
3248 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003249 d.what = DisplayState::eDisplayProjectionChanged |
3250 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003251 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003252 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003253 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003254 d.frame.makeInvalid();
3255 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003256 d.width = 0;
3257 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003258 displays.add(d);
3259 setTransactionState(state, displays, 0);
Steven Thomasd7f49c52017-07-26 18:48:28 -07003260 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3261 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003262
Dan Stoza9e56aa02015-11-02 13:00:03 -08003263 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3264 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003265 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003266
Brian Andersond0010582017-03-07 13:20:31 -08003267 // Use phase of 0 since phase is not known.
3268 // Use latency of 0, which will snap to the ideal latency.
3269 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003270}
3271
3272void SurfaceFlinger::initializeDisplays() {
3273 class MessageScreenInitialized : public MessageBase {
3274 SurfaceFlinger* flinger;
3275 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003276 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003277 virtual bool handler() {
3278 flinger->onInitializeDisplays();
3279 return true;
3280 }
3281 };
3282 sp<MessageBase> msg = new MessageScreenInitialized(this);
3283 postMessageAsync(msg); // we may be called from main thread, use async message
3284}
3285
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003286void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasd7f49c52017-07-26 18:48:28 -07003287 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003288 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3289 this);
3290 int32_t type = hw->getDisplayType();
3291 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003292
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003293 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003294 return;
3295 }
3296
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003297 hw->setPowerMode(mode);
3298 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3299 ALOGW("Trying to set power mode for virtual display");
3300 return;
3301 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003302
Irvelffc9efc2016-07-27 15:16:37 -07003303 if (mInterceptor.isEnabled()) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003304 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003305 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3306 if (idx < 0) {
3307 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3308 return;
3309 }
3310 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3311 }
3312
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003313 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003314 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003315 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003316 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3317 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003318 // FIXME: eventthread only knows about the main display right now
3319 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003320 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003321 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003322
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003323 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003324 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003325 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003326
3327 struct sched_param param = {0};
3328 param.sched_priority = 1;
3329 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3330 ALOGW("Couldn't set SCHED_FIFO on display on");
3331 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003332 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003333 // Turn off the display
3334 struct sched_param param = {0};
3335 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3336 ALOGW("Couldn't set SCHED_OTHER on display off");
3337 }
3338
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003339 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003340 disableHardwareVsync(true); // also cancels any in-progress resync
3341
Mathias Agopiancde87a32012-09-13 14:09:01 -07003342 // FIXME: eventthread only knows about the main display right now
3343 mEventThread->onScreenReleased();
3344 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003345
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003346 getHwComposer().setPowerMode(type, mode);
3347 mVisibleRegionsDirty = true;
3348 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003349 } else if (mode == HWC_POWER_MODE_DOZE ||
3350 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003351 // Update display while dozing
3352 getHwComposer().setPowerMode(type, mode);
3353 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3354 // FIXME: eventthread only knows about the main display right now
3355 mEventThread->onScreenAcquired();
3356 resyncToHardwareVsync(true);
3357 }
3358 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3359 // Leave display going to doze
3360 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3361 disableHardwareVsync(true); // also cancels any in-progress resync
3362 // FIXME: eventthread only knows about the main display right now
3363 mEventThread->onScreenReleased();
3364 }
3365 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003366 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003367 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003368 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003369 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003370}
3371
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003372void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3373 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003374 SurfaceFlinger& mFlinger;
3375 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003376 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003377 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003378 MessageSetPowerMode(SurfaceFlinger& flinger,
3379 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3380 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003381 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003382 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003383 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003384 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003385 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003386 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003387 ALOGW("Attempt to set power mode = %d for virtual display",
3388 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003389 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003390 mFlinger.setPowerModeInternal(
3391 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003392 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003393 return true;
3394 }
3395 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003396 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003397 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003398}
3399
3400// ---------------------------------------------------------------------------
3401
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003402status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3403{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003404 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003405
Mathias Agopianbd115332013-04-18 16:41:04 -07003406 IPCThreadState* ipc = IPCThreadState::self();
3407 const int pid = ipc->getCallingPid();
3408 const int uid = ipc->getCallingUid();
3409 if ((uid != AID_SHELL) &&
3410 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003411 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003412 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003413 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003414 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003415 // (this would indicate SF is stuck, but we want to be able to
3416 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003417 status_t err = mStateLock.timedLock(s2ns(1));
3418 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003419 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003420 result.appendFormat(
3421 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3422 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003423 }
3424
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425 bool dumpAll = true;
3426 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003427 size_t numArgs = args.size();
3428 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003429 if ((index < numArgs) &&
3430 (args[index] == String16("--list"))) {
3431 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003432 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003433 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003434 }
3435
3436 if ((index < numArgs) &&
3437 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003438 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003439 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003440 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003441 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003442
3443 if ((index < numArgs) &&
3444 (args[index] == String16("--latency-clear"))) {
3445 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003446 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003447 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003448 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003449
3450 if ((index < numArgs) &&
3451 (args[index] == String16("--dispsync"))) {
3452 index++;
3453 mPrimaryDispSync.dump(result);
3454 dumpAll = false;
3455 }
Dan Stozab90cf072015-03-05 11:05:59 -08003456
3457 if ((index < numArgs) &&
3458 (args[index] == String16("--static-screen"))) {
3459 index++;
3460 dumpStaticScreenStats(result);
3461 dumpAll = false;
3462 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003463
3464 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003465 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003466 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003467 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003468 dumpAll = false;
3469 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003470
3471 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3472 index++;
3473 dumpWideColorInfo(result);
3474 dumpAll = false;
3475 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003476 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003477
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003478 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003479 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003480 }
3481
Mathias Agopian9795c422009-08-26 16:36:26 -07003482 if (locked) {
3483 mStateLock.unlock();
3484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003485 }
3486 write(fd, result.string(), result.size());
3487 return NO_ERROR;
3488}
3489
Dan Stozac7014012014-02-14 15:03:43 -08003490void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3491 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003492{
Robert Carr2047fae2016-11-28 14:09:09 -08003493 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003494 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003495 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003496}
3497
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003498void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003499 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003500{
3501 String8 name;
3502 if (index < args.size()) {
3503 name = String8(args[index]);
3504 index++;
3505 }
3506
Dan Stoza9e56aa02015-11-02 13:00:03 -08003507 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3508 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003509 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003510
3511 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003512 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003513 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003514 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003515 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003516 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003517 }
Robert Carr2047fae2016-11-28 14:09:09 -08003518 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003519 }
3520}
3521
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003522void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003523 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003524{
3525 String8 name;
3526 if (index < args.size()) {
3527 name = String8(args[index]);
3528 index++;
3529 }
3530
Robert Carr2047fae2016-11-28 14:09:09 -08003531 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003532 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003533 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003534 }
Robert Carr2047fae2016-11-28 14:09:09 -08003535 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003536
Svetoslavd85084b2014-03-20 10:28:31 -07003537 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003538}
3539
Jamie Gennis6547ff42013-07-16 20:12:42 -07003540// This should only be called from the main thread. Otherwise it would need
3541// the lock and should use mCurrentState rather than mDrawingState.
3542void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003543 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003544 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003545 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003546
3547 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3548}
3549
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003550void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003551{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003552 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003553 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3554
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003555 if (isLayerTripleBufferingDisabled())
3556 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003557
3558 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003559 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003560 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003561 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003562 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3563 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003564 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003565}
3566
Dan Stozab90cf072015-03-05 11:05:59 -08003567void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3568{
3569 result.appendFormat("Static screen stats:\n");
3570 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3571 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3572 float percent = 100.0f *
3573 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3574 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3575 b + 1, bucketTimeSec, percent);
3576 }
3577 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3578 float percent = 100.0f *
3579 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3580 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3581 NUM_BUCKETS - 1, bucketTimeSec, percent);
3582}
3583
Dan Stozae77c7662016-05-13 11:37:28 -07003584void SurfaceFlinger::recordBufferingStats(const char* layerName,
3585 std::vector<OccupancyTracker::Segment>&& history) {
3586 Mutex::Autolock lock(mBufferingStatsMutex);
3587 auto& stats = mBufferingStats[layerName];
3588 for (const auto& segment : history) {
3589 if (!segment.usedThirdBuffer) {
3590 stats.twoBufferTime += segment.totalTime;
3591 }
3592 if (segment.occupancyAverage < 1.0f) {
3593 stats.doubleBufferedTime += segment.totalTime;
3594 } else if (segment.occupancyAverage < 2.0f) {
3595 stats.tripleBufferedTime += segment.totalTime;
3596 }
3597 ++stats.numSegments;
3598 stats.totalTime += segment.totalTime;
3599 }
3600}
3601
Brian Andersond6927fb2016-07-23 23:37:30 -07003602void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3603 result.appendFormat("Layer frame timestamps:\n");
3604
3605 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3606 const size_t count = currentLayers.size();
3607 for (size_t i=0 ; i<count ; i++) {
3608 currentLayers[i]->dumpFrameEvents(result);
3609 }
3610}
3611
Dan Stozae77c7662016-05-13 11:37:28 -07003612void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3613 result.append("Buffering stats:\n");
3614 result.append(" [Layer name] <Active time> <Two buffer> "
3615 "<Double buffered> <Triple buffered>\n");
3616 Mutex::Autolock lock(mBufferingStatsMutex);
3617 typedef std::tuple<std::string, float, float, float> BufferTuple;
3618 std::map<float, BufferTuple, std::greater<float>> sorted;
3619 for (const auto& statsPair : mBufferingStats) {
3620 const char* name = statsPair.first.c_str();
3621 const BufferingStats& stats = statsPair.second;
3622 if (stats.numSegments == 0) {
3623 continue;
3624 }
3625 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3626 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3627 stats.totalTime;
3628 float doubleBufferRatio = static_cast<float>(
3629 stats.doubleBufferedTime) / stats.totalTime;
3630 float tripleBufferRatio = static_cast<float>(
3631 stats.tripleBufferedTime) / stats.totalTime;
3632 sorted.insert({activeTime, {name, twoBufferRatio,
3633 doubleBufferRatio, tripleBufferRatio}});
3634 }
3635 for (const auto& sortedPair : sorted) {
3636 float activeTime = sortedPair.first;
3637 const BufferTuple& values = sortedPair.second;
3638 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3639 std::get<0>(values).c_str(), activeTime,
3640 std::get<1>(values), std::get<2>(values),
3641 std::get<3>(values));
3642 }
3643 result.append("\n");
3644}
3645
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003646void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3647 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Romain Guy54f154a2017-10-24 21:40:32 +01003648 result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003649
3650 // TODO: print out if wide-color mode is active or not
3651
3652 for (size_t d = 0; d < mDisplays.size(); d++) {
3653 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3654 int32_t hwcId = displayDevice->getHwcDisplayId();
3655 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3656 continue;
3657 }
3658
3659 result.appendFormat("Display %d color modes:\n", hwcId);
3660 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3661 for (auto&& mode : modes) {
3662 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3663 }
3664
3665 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3666 result.appendFormat(" Current color mode: %s (%d)\n",
3667 decodeColorMode(currentMode).c_str(), currentMode);
3668 }
3669 result.append("\n");
3670}
3671
Mathias Agopian74d211a2013-04-22 16:55:35 +02003672void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3673 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003674{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003675 bool colorize = false;
3676 if (index < args.size()
3677 && (args[index] == String16("--color"))) {
3678 colorize = true;
3679 index++;
3680 }
3681
3682 Colorizer colorizer(colorize);
3683
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003684 // figure out if we're stuck somewhere
3685 const nsecs_t now = systemTime();
3686 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3687 const nsecs_t inTransaction(mDebugInTransaction);
3688 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3689 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3690
3691 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003692 * Dump library configuration.
3693 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003694
3695 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003696 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003697 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003698 appendSfConfigString(result);
3699 appendUiConfigString(result);
3700 appendGuiConfigString(result);
3701 result.append("\n");
3702
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003703 result.append("\nWide-Color information:\n");
3704 dumpWideColorInfo(result);
3705
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003706 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003707 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003708 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003709 result.append(SyncFeatures::getInstance().toString());
3710 result.append("\n");
3711
Dan Stoza9e56aa02015-11-02 13:00:03 -08003712 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3713
Andy McFadden41d67d72014-04-25 16:58:34 -07003714 colorizer.bold(result);
3715 result.append("DispSync configuration: ");
3716 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003717 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003718 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003719 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003720 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003721 result.append("\n");
3722
Dan Stozab90cf072015-03-05 11:05:59 -08003723 // Dump static screen stats
3724 result.append("\n");
3725 dumpStaticScreenStats(result);
3726 result.append("\n");
3727
Dan Stozae77c7662016-05-13 11:37:28 -07003728 dumpBufferingStats(result);
3729
Andy McFadden4803b742012-09-24 19:07:20 -07003730 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003731 * Dump the visible layer list
3732 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003733 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003734 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003735 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003736 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003737 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003738 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739
3740 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003741 * Dump Display state
3742 */
3743
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003744 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003745 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003746 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003747 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3748 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003749 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003750 }
3751
3752 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003753 * Dump SurfaceFlinger global state
3754 */
3755
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003756 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003757 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003758 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003759
Mathias Agopian888c8222012-08-04 21:10:38 -07003760 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003761 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003762
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003763 colorizer.bold(result);
3764 result.appendFormat("EGL implementation : %s\n",
3765 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3766 colorizer.reset(result);
3767 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003768 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003769
Mathias Agopian875d8e12013-06-07 15:35:48 -07003770 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003771
Mathias Agopian42977342012-08-05 00:40:46 -07003772 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003773 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3774 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003775 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003776 " last eglSwapBuffers() time: %f us\n"
3777 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003778 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003779 " refresh-rate : %f fps\n"
3780 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003781 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003782 " gpu_to_cpu_unsupported : %d\n"
3783 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003784 mLastSwapBufferTime/1000.0,
3785 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003786 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003787 1e9 / activeConfig->getVsyncPeriod(),
3788 activeConfig->getDpiX(),
3789 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003790 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003791
Mathias Agopian74d211a2013-04-22 16:55:35 +02003792 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003793 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003794
Mathias Agopian74d211a2013-04-22 16:55:35 +02003795 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003796 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003797
3798 /*
3799 * VSYNC state
3800 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003801 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003802 result.append("\n");
3803
3804 /*
3805 * HWC layer minidump
3806 */
3807 for (size_t d = 0; d < mDisplays.size(); d++) {
3808 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3809 int32_t hwcId = displayDevice->getHwcDisplayId();
3810 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3811 continue;
3812 }
3813
3814 result.appendFormat("Display %d HWC layers:\n", hwcId);
3815 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003816 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003817 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003818 });
Dan Stozae22aec72016-08-01 13:20:59 -07003819 result.append("\n");
3820 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003821
3822 /*
3823 * Dump HWComposer state
3824 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003825 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003826 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003827 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003828 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003829 result.appendFormat(" h/w composer %s\n",
3830 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003831 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003832
3833 /*
3834 * Dump gralloc state
3835 */
3836 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3837 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003838
3839 /*
3840 * Dump VrFlinger state if in use.
3841 */
3842 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3843 result.append("VrFlinger state:\n");
3844 result.append(mVrFlinger->Dump().c_str());
3845 result.append("\n");
3846 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003847}
3848
Mathias Agopian13127d82013-03-05 17:47:11 -08003849const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003850SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003851 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003852 wp<IBinder> dpy;
3853 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3854 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3855 dpy = mDisplays.keyAt(i);
3856 break;
3857 }
3858 }
3859 if (dpy == NULL) {
3860 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3861 // Just use the primary display so we have something to return
3862 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3863 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003864 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003865}
3866
Keun young Park63f165f2012-08-31 10:53:36 -07003867bool SurfaceFlinger::startDdmConnection()
3868{
3869 void* libddmconnection_dso =
3870 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3871 if (!libddmconnection_dso) {
3872 return false;
3873 }
3874 void (*DdmConnection_start)(const char* name);
3875 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003876 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003877 if (!DdmConnection_start) {
3878 dlclose(libddmconnection_dso);
3879 return false;
3880 }
3881 (*DdmConnection_start)(getServiceName());
3882 return true;
3883}
3884
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003885status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886 switch (code) {
3887 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003888 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003890 case CLEAR_ANIMATION_FRAME_STATS:
3891 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003892 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003893 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 {
3895 // codes that require permission check
3896 IPCThreadState* ipc = IPCThreadState::self();
3897 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003898 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003899 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003900 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003901 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003902 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003904 break;
3905 }
Robert Carr1db73f62016-12-21 12:58:51 -08003906 /*
3907 * Calling setTransactionState is safe, because you need to have been
3908 * granted a reference to Client* and Handle* to do anything with it.
3909 *
3910 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3911 */
3912 case SET_TRANSACTION_STATE:
3913 case CREATE_SCOPED_CONNECTION:
3914 {
3915 return OK;
3916 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003917 case CAPTURE_SCREEN:
3918 {
3919 // codes that require permission check
3920 IPCThreadState* ipc = IPCThreadState::self();
3921 const int pid = ipc->getCallingPid();
3922 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003923 if ((uid != AID_GRAPHICS) &&
3924 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003925 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003926 return PERMISSION_DENIED;
3927 }
3928 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929 }
3930 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003931 return OK;
3932}
3933
3934status_t SurfaceFlinger::onTransact(
3935 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3936{
3937 status_t credentialCheck = CheckTransactCodeCredentials(code);
3938 if (credentialCheck != OK) {
3939 return credentialCheck;
3940 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003941
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003942 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3943 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003944 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003945 IPCThreadState* ipc = IPCThreadState::self();
3946 const int uid = ipc->getCallingUid();
3947 if (CC_UNLIKELY(uid != AID_SYSTEM
3948 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003949 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003950 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003951 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003952 return PERMISSION_DENIED;
3953 }
3954 int n;
3955 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003956 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003957 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 return NO_ERROR;
3959 case 1002: // SHOW_UPDATES
3960 n = data.readInt32();
3961 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003962 invalidateHwcGeometry();
3963 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003964 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003966 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003967 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003969 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07003970 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003971 setTransactionFlags(
3972 eTransactionNeeded|
3973 eDisplayTransactionNeeded|
3974 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003975 return NO_ERROR;
3976 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003977 case 1006:{ // send empty update
3978 signalRefresh();
3979 return NO_ERROR;
3980 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003981 case 1008: // toggle use of hw composer
3982 n = data.readInt32();
3983 mDebugDisableHWC = n ? 1 : 0;
3984 invalidateHwcGeometry();
3985 repaintEverything();
3986 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003987 case 1009: // toggle use of transform hint
3988 n = data.readInt32();
3989 mDebugDisableTransformHint = n ? 1 : 0;
3990 invalidateHwcGeometry();
3991 repaintEverything();
3992 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003994 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003995 reply->writeInt32(0);
3996 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003997 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003998 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003999 return NO_ERROR;
4000 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004001 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004002 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004003 return NO_ERROR;
4004 }
4005 case 1014: {
4006 // daltonize
4007 n = data.readInt32();
4008 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004009 case 1:
4010 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4011 break;
4012 case 2:
4013 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4014 break;
4015 case 3:
4016 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4017 break;
4018 default:
4019 mDaltonizer.setType(ColorBlindnessType::None);
4020 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004021 }
4022 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004023 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004024 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004025 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004026 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004027 invalidateHwcGeometry();
4028 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004029 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004030 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004031 case 1015: {
4032 // apply a color matrix
4033 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004034 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004035 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004036 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004037 for (size_t j = 0; j < 4; j++) {
4038 mColorMatrix[i][j] = data.readFloat();
4039 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004040 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004041 } else {
4042 mColorMatrix = mat4();
4043 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004044
4045 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4046 // the division by w in the fragment shader
4047 float4 lastRow(transpose(mColorMatrix)[3]);
4048 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4049 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4050 }
4051
Alan Viverette9c5a3332013-09-12 20:04:35 -07004052 invalidateHwcGeometry();
4053 repaintEverything();
4054 return NO_ERROR;
4055 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004056 // This is an experimental interface
4057 // Needs to be shifted to proper binder interface when we productize
4058 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004059 n = data.readInt32();
4060 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004061 return NO_ERROR;
4062 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004063 case 1017: {
4064 n = data.readInt32();
4065 mForceFullDamage = static_cast<bool>(n);
4066 return NO_ERROR;
4067 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004068 case 1018: { // Modify Choreographer's phase offset
4069 n = data.readInt32();
4070 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4071 return NO_ERROR;
4072 }
4073 case 1019: { // Modify SurfaceFlinger's phase offset
4074 n = data.readInt32();
4075 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4076 return NO_ERROR;
4077 }
Irvel468051e2016-06-13 16:44:44 -07004078 case 1020: { // Layer updates interceptor
4079 n = data.readInt32();
4080 if (n) {
4081 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004082 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004083 }
4084 else{
4085 ALOGV("Interceptor disabled");
4086 mInterceptor.disable();
4087 }
4088 return NO_ERROR;
4089 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004090 case 1021: { // Disable HWC virtual displays
4091 n = data.readInt32();
4092 mUseHwcVirtualDisplays = !n;
4093 return NO_ERROR;
4094 }
Romain Guy0147a172017-06-01 13:53:56 -07004095 case 1022: { // Set saturation boost
4096 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4097
4098 invalidateHwcGeometry();
4099 repaintEverything();
4100 return NO_ERROR;
4101 }
Romain Guy54f154a2017-10-24 21:40:32 +01004102 case 1023: { // Set native mode
4103 mForceNativeColorMode = data.readInt32() == 1;
4104
4105 invalidateHwcGeometry();
4106 repaintEverything();
4107 return NO_ERROR;
4108 }
4109 case 1024: { // Is wide color gamut rendering/color management supported?
4110 reply->writeBool(hasWideColorDisplay);
4111 return NO_ERROR;
4112 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004113 }
4114 }
4115 return err;
4116}
4117
Steven Thomas6d8110b2017-08-31 18:24:21 -07004118void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004119 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004120 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004121}
4122
Steven Thomas6d8110b2017-08-31 18:24:21 -07004123void SurfaceFlinger::repaintEverything() {
4124 ConditionalLock _l(mStateLock,
4125 std::this_thread::get_id() != mMainThreadId);
4126 repaintEverythingLocked();
4127}
4128
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004129// Checks that the requested width and height are valid and updates them to the display dimensions
4130// if they are set to 0
4131static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4132 Transform::orientation_flags rotation,
4133 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4134 // get screen geometry
4135 uint32_t displayWidth = displayDevice->getWidth();
4136 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004137
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004138 if (rotation & Transform::ROT_90) {
4139 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004140 }
4141
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004142 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4143 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4144 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4145 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004146 }
4147
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004148 if (*requestedWidth == 0) {
4149 *requestedWidth = displayWidth;
4150 }
4151 if (*requestedHeight == 0) {
4152 *requestedHeight = displayHeight;
4153 }
4154
4155 return NO_ERROR;
4156}
4157
4158// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4159class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004160public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004161 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4162 ~WindowDisconnector() {
4163 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004164 }
4165
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004166private:
4167 ANativeWindow* mWindow;
4168 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004169};
4170
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004171static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4172 uint32_t requestedHeight, bool hasWideColorDisplay,
4173 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4174 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4175 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4176
4177 int err = 0;
4178 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4179 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4180 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4181 err |= native_window_set_usage(window, usage);
4182
4183 if (hasWideColorDisplay) {
4184 err |= native_window_set_buffers_data_space(window,
4185 renderEngineUsesWideColor
4186 ? HAL_DATASPACE_DISPLAY_P3
4187 : HAL_DATASPACE_V0_SRGB);
4188 }
4189
4190 if (err != NO_ERROR) {
4191 return BAD_VALUE;
4192 }
4193
4194 /* TODO: Once we have the sync framework everywhere this can use
4195 * server-side waits on the fence that dequeueBuffer returns.
4196 */
4197 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4198 if (err != NO_ERROR) {
4199 return err;
4200 }
4201
4202 return NO_ERROR;
4203}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004204
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004205status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4206 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004207 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004208 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004209 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004210 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004211
4212 if (CC_UNLIKELY(display == 0))
4213 return BAD_VALUE;
4214
4215 if (CC_UNLIKELY(producer == 0))
4216 return BAD_VALUE;
4217
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004218 // if we have secure windows on this display, never allow the screen capture
4219 // unless the producer interface is local (i.e.: we can take a screenshot for
4220 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004221 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004222
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004223 // Convert to surfaceflinger's internal rotation type.
4224 Transform::orientation_flags rotationFlags;
4225 switch (rotation) {
4226 case ISurfaceComposer::eRotateNone:
4227 rotationFlags = Transform::ROT_0;
4228 break;
4229 case ISurfaceComposer::eRotate90:
4230 rotationFlags = Transform::ROT_90;
4231 break;
4232 case ISurfaceComposer::eRotate180:
4233 rotationFlags = Transform::ROT_180;
4234 break;
4235 case ISurfaceComposer::eRotate270:
4236 rotationFlags = Transform::ROT_270;
4237 break;
4238 default:
4239 rotationFlags = Transform::ROT_0;
4240 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4241 break;
4242 }
4243
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004244 { // Autolock scope
4245 Mutex::Autolock lock(mStateLock);
4246 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4247 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004248 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004249
4250 // create a surface (because we're a producer, and we need to
4251 // dequeue/queue a buffer)
4252 sp<Surface> surface = new Surface(producer, false);
4253
4254 // Put the screenshot Surface into async mode so that
4255 // Layer::headFenceHasSignaled will always return true and we'll latch the
4256 // first buffer regardless of whether or not its acquire fence has
4257 // signaled. This is needed to avoid a race condition in the rotation
4258 // animation. See b/30209608
4259 surface->setAsyncMode(true);
4260
4261 ANativeWindow* window = surface.get();
4262
4263 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4264 if (result != NO_ERROR) {
4265 return result;
4266 }
4267 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4268
4269 ANativeWindowBuffer* buffer = nullptr;
Romain Guy54f154a2017-10-24 21:40:32 +01004270 result = getWindowBuffer(window, reqWidth, reqHeight,
4271 hasWideColorDisplay && !mForceNativeColorMode,
4272 getRenderEngine().usesWideColor(), &buffer);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004273 if (result != NO_ERROR) {
4274 return result;
4275 }
4276
4277 // This mutex protects syncFd and captureResult for communication of the return values from the
4278 // main thread back to this Binder thread
4279 std::mutex captureMutex;
4280 std::condition_variable captureCondition;
4281 std::unique_lock<std::mutex> captureLock(captureMutex);
4282 int syncFd = -1;
4283 std::optional<status_t> captureResult;
4284
4285 sp<LambdaMessage> message = new LambdaMessage([&]() {
4286 // If there is a refresh pending, bug out early and tell the binder thread to try again
4287 // after the refresh.
4288 if (mRefreshPending) {
4289 ATRACE_NAME("Skipping screenshot for now");
4290 std::unique_lock<std::mutex> captureLock(captureMutex);
4291 captureResult = std::make_optional<status_t>(EAGAIN);
4292 captureCondition.notify_one();
4293 return;
4294 }
4295
4296 status_t result = NO_ERROR;
4297 int fd = -1;
4298 {
4299 Mutex::Autolock _l(mStateLock);
4300 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4301 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4302 minLayerZ, maxLayerZ, useIdentityTransform,
4303 rotationFlags, isLocalScreenshot, &fd);
4304 }
4305
4306 {
4307 std::unique_lock<std::mutex> captureLock(captureMutex);
4308 syncFd = fd;
4309 captureResult = std::make_optional<status_t>(result);
4310 captureCondition.notify_one();
4311 }
4312 });
4313
4314 result = postMessageAsync(message);
4315 if (result == NO_ERROR) {
4316 captureCondition.wait(captureLock, [&]() { return captureResult; });
4317 while (*captureResult == EAGAIN) {
4318 captureResult.reset();
4319 result = postMessageAsync(message);
4320 if (result != NO_ERROR) {
4321 return result;
4322 }
4323 captureCondition.wait(captureLock, [&]() { return captureResult; });
4324 }
4325 result = *captureResult;
4326 }
4327
4328 if (result == NO_ERROR) {
4329 // queueBuffer takes ownership of syncFd
4330 result = window->queueBuffer(window, buffer, syncFd);
4331 }
4332
4333 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004334}
4335
Mathias Agopian180f10d2013-04-10 22:55:41 -07004336
4337void SurfaceFlinger::renderScreenImplLocked(
4338 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004339 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004340 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004341 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004342{
4343 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004344 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004345
4346 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004347 const int32_t hw_w = hw->getWidth();
4348 const int32_t hw_h = hw->getHeight();
4349 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004350 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004351
Dan Stozac1879002014-05-22 15:59:05 -07004352 // if a default or invalid sourceCrop is passed in, set reasonable values
4353 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4354 !sourceCrop.isValid()) {
4355 sourceCrop.setLeftTop(Point(0, 0));
4356 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4357 }
4358
4359 // ensure that sourceCrop is inside screen
4360 if (sourceCrop.left < 0) {
4361 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4362 }
Dan Stozabe31f442014-06-11 11:20:54 -07004363 if (sourceCrop.right > hw_w) {
4364 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004365 }
4366 if (sourceCrop.top < 0) {
4367 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4368 }
Dan Stozabe31f442014-06-11 11:20:54 -07004369 if (sourceCrop.bottom > hw_h) {
4370 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004371 }
4372
Romain Guy88d37dd2017-05-26 17:57:05 -07004373#ifdef USE_HWC2
Romain Guy54f154a2017-10-24 21:40:32 +01004374 engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
4375 engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
Romain Guy88d37dd2017-05-26 17:57:05 -07004376#endif
4377
Mathias Agopian180f10d2013-04-10 22:55:41 -07004378 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004379 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004380
4381 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004382 engine.setViewportAndProjection(
4383 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004384 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004385
4386 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004387 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004388
Robert Carr1f0a16a2016-10-24 16:27:39 -07004389 // We loop through the first level of layers without traversing,
4390 // as we need to interpret min/max layer Z in the top level Z space.
4391 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004392 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004393 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004394 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004395 const Layer::State& state(layer->getDrawingState());
4396 if (state.z < minLayerZ || state.z > maxLayerZ) {
4397 continue;
4398 }
Dan Stoza412903f2017-04-27 13:42:17 -07004399 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004400 if (!layer->isVisible()) {
4401 return;
4402 }
4403 if (filtering) layer->setFiltering(true);
4404 layer->draw(hw, useIdentityTransform);
4405 if (filtering) layer->setFiltering(false);
4406 });
4407 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004408
Mathias Agopian931bda12013-08-28 18:11:46 -07004409 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004410}
4411
Dan Stozaabcda352017-06-01 14:37:39 -07004412// A simple RAII class that holds an EGLImage and destroys it either:
4413// a) When the destroy() method is called
4414// b) When the object goes out of scope
4415class ImageHolder {
4416public:
4417 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4418 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004419
Dan Stozaabcda352017-06-01 14:37:39 -07004420 void destroy() {
4421 if (mImage != EGL_NO_IMAGE_KHR) {
4422 eglDestroyImageKHR(mDisplay, mImage);
4423 mImage = EGL_NO_IMAGE_KHR;
4424 }
4425 }
4426
4427private:
4428 const EGLDisplay mDisplay;
4429 EGLImageKHR mImage;
4430};
4431
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004432status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4433 ANativeWindowBuffer* buffer, Rect sourceCrop,
4434 uint32_t reqWidth, uint32_t reqHeight,
4435 int32_t minLayerZ, int32_t maxLayerZ,
4436 bool useIdentityTransform,
4437 Transform::orientation_flags rotation,
4438 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004439 ATRACE_CALL();
4440
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004441 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004442 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004443 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004444 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004445 (state.z < minLayerZ || state.z > maxLayerZ)) {
4446 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004447 }
Dan Stoza412903f2017-04-27 13:42:17 -07004448 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004449 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4450 layer->isSecure());
4451 });
4452 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004453
4454 if (!isLocalScreenshot && secureLayerIsVisible) {
4455 ALOGW("FB is protected: PERMISSION_DENIED");
4456 return PERMISSION_DENIED;
4457 }
4458
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004459 int syncFd = -1;
4460 // create an EGLImage from the buffer so we can later
4461 // turn it into a texture
4462 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4463 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4464 if (image == EGL_NO_IMAGE_KHR) {
4465 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004466 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004467
Dan Stozaabcda352017-06-01 14:37:39 -07004468 // This will automatically destroy the image if we return before calling its destroy method
4469 ImageHolder imageHolder(mEGLDisplay, image);
4470
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004471 // this binds the given EGLImage as a framebuffer for the
4472 // duration of this scope.
4473 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004474 if (imageBond.getStatus() != NO_ERROR) {
4475 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004476 return INVALID_OPERATION;
4477 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004478
Dan Stozaabcda352017-06-01 14:37:39 -07004479 // this will in fact render into our dequeued buffer
4480 // via an FBO, which means we didn't have to create
4481 // an EGLSurface and therefore we're not
4482 // dependent on the context's EGLConfig.
4483 renderScreenImplLocked(
4484 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4485 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004486
Dan Stozaabcda352017-06-01 14:37:39 -07004487 // Attempt to create a sync khr object that can produce a sync point. If that
4488 // isn't available, create a non-dupable sync object in the fallback path and
4489 // wait on it directly.
4490 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4491 if (!DEBUG_SCREENSHOTS) {
4492 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4493 // native fence fd will not be populated until flush() is done.
4494 getRenderEngine().flush();
4495 }
4496
4497 if (sync != EGL_NO_SYNC_KHR) {
4498 // get the sync fd
4499 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4500 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4501 ALOGW("captureScreen: failed to dup sync khr object");
4502 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004503 }
Dan Stozaabcda352017-06-01 14:37:39 -07004504 eglDestroySyncKHR(mEGLDisplay, sync);
4505 } else {
4506 // fallback path
4507 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004508 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004509 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4510 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4511 EGLint eglErr = eglGetError();
4512 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4513 ALOGW("captureScreen: fence wait timed out");
4514 } else {
4515 ALOGW_IF(eglErr != EGL_SUCCESS,
4516 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004517 }
4518 eglDestroySyncKHR(mEGLDisplay, sync);
4519 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004520 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004521 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004522 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004523 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004524
4525 if (DEBUG_SCREENSHOTS) {
4526 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4527 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4528 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4529 hw, minLayerZ, maxLayerZ);
4530 delete [] pixels;
4531 }
4532
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004533 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004534 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004535
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004536 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004537}
4538
Mathias Agopiand5556842013-09-19 17:08:37 -07004539void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004540 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004541 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004542 for (size_t y=0 ; y<h ; y++) {
4543 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4544 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004545 if (p[x] != 0xFF000000) return;
4546 }
4547 }
4548 ALOGE("*** we just took a black screenshot ***\n"
4549 "requested minz=%d, maxz=%d, layerStack=%d",
4550 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004551
Robert Carr2047fae2016-11-28 14:09:09 -08004552 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004553 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004554 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004555 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004556 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004557 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004558 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4559 layer->isVisible() ? '+' : '-',
4560 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004561 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004562 i++;
4563 });
4564 }
4565 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004566 }
4567}
4568
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004569// ---------------------------------------------------------------------------
4570
Dan Stoza412903f2017-04-27 13:42:17 -07004571void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4572 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004573}
4574
Dan Stoza412903f2017-04-27 13:42:17 -07004575void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4576 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004577}
4578
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004580
4581
4582#if defined(__gl_h_)
4583#error "don't include gl/gl.h in this file"
4584#endif
4585
4586#if defined(__gl2_h_)
4587#error "don't include gl2/gl2.h in this file"
4588#endif