blob: c05ac8aaac87225684bedcbb9e6bfba7c5114f81 [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);
659}
660
Mathias Agopiana67e4182012-06-19 17:26:12 -0700661void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800662 // Start boot animation service by setting a property mailbox
663 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800665 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700666 if (mStartPropertySetThread->join() != NO_ERROR) {
667 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800668 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700669}
670
Mathias Agopian875d8e12013-06-07 15:35:48 -0700671size_t SurfaceFlinger::getMaxTextureSize() const {
672 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700673}
674
Mathias Agopian875d8e12013-06-07 15:35:48 -0700675size_t SurfaceFlinger::getMaxViewportDims() const {
676 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700677}
678
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800679// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800680
Jamie Gennis582270d2011-08-17 18:19:00 -0700681bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800682 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800683 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800684 return authenticateSurfaceTextureLocked(bufferProducer);
685}
686
687bool SurfaceFlinger::authenticateSurfaceTextureLocked(
688 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800689 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700690 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800691}
692
Brian Anderson6b376712017-04-04 10:51:39 -0700693status_t SurfaceFlinger::getSupportedFrameTimestamps(
694 std::vector<FrameEvent>* outSupported) const {
695 *outSupported = {
696 FrameEvent::REQUESTED_PRESENT,
697 FrameEvent::ACQUIRE,
698 FrameEvent::LATCH,
699 FrameEvent::FIRST_REFRESH_START,
700 FrameEvent::LAST_REFRESH_START,
701 FrameEvent::GPU_COMPOSITION_DONE,
702 FrameEvent::DEQUEUE_READY,
703 FrameEvent::RELEASE,
704 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700705 ConditionalLock _l(mStateLock,
706 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700707 if (!getHwComposer().hasCapability(
708 HWC2::Capability::PresentFenceIsNotReliable)) {
709 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
710 }
711 return NO_ERROR;
712}
713
Dan Stoza7f7da322014-05-02 15:26:25 -0700714status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
715 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700716 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700717 return BAD_VALUE;
718 }
719
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500720 if (!display.get())
721 return NAME_NOT_FOUND;
722
Jesse Hall692c7232012-11-08 15:41:56 -0800723 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700724 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800725 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700726 type = i;
727 break;
728 }
729 }
730
731 if (type < 0) {
732 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700733 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700734
Mathias Agopian8b736f12012-08-13 17:54:26 -0700735 // TODO: Not sure if display density should handled by SF any longer
736 class Density {
737 static int getDensityFromProperty(char const* propName) {
738 char property[PROPERTY_VALUE_MAX];
739 int density = 0;
740 if (property_get(propName, property, NULL) > 0) {
741 density = atoi(property);
742 }
743 return density;
744 }
745 public:
746 static int getEmuDensity() {
747 return getDensityFromProperty("qemu.sf.lcd_density"); }
748 static int getBuildDensity() {
749 return getDensityFromProperty("ro.sf.lcd_density"); }
750 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700751
Dan Stoza7f7da322014-05-02 15:26:25 -0700752 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700753
Steven Thomas6d8110b2017-08-31 18:24:21 -0700754 ConditionalLock _l(mStateLock,
755 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800756 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700757 DisplayInfo info = DisplayInfo();
758
Dan Stoza9e56aa02015-11-02 13:00:03 -0800759 float xdpi = hwConfig->getDpiX();
760 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700761
762 if (type == DisplayDevice::DISPLAY_PRIMARY) {
763 // The density of the device is provided by a build property
764 float density = Density::getBuildDensity() / 160.0f;
765 if (density == 0) {
766 // the build doesn't provide a density -- this is wrong!
767 // use xdpi instead
768 ALOGE("ro.sf.lcd_density must be defined as a build property");
769 density = xdpi / 160.0f;
770 }
771 if (Density::getEmuDensity()) {
772 // if "qemu.sf.lcd_density" is specified, it overrides everything
773 xdpi = ydpi = density = Density::getEmuDensity();
774 density /= 160.0f;
775 }
776 info.density = density;
777
778 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700779 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +0000780 info.orientation = hw->getOrientation();
Dan Stoza7f7da322014-05-02 15:26:25 -0700781 } else {
782 // TODO: where should this value come from?
783 static const int TV_DENSITY = 213;
784 info.density = TV_DENSITY / 160.0f;
785 info.orientation = 0;
786 }
787
Dan Stoza9e56aa02015-11-02 13:00:03 -0800788 info.w = hwConfig->getWidth();
789 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700790 info.xdpi = xdpi;
791 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800792 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900793 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800794
Andy McFadden91b2ca82014-06-13 14:04:23 -0700795 // This is how far in advance a buffer must be queued for
796 // presentation at a given time. If you want a buffer to appear
797 // on the screen at time N, you must submit the buffer before
798 // (N - presentationDeadline).
799 //
800 // Normally it's one full refresh period (to give SF a chance to
801 // latch the buffer), but this can be reduced by configuring a
802 // DispSync offset. Any additional delays introduced by the hardware
803 // composer or panel must be accounted for here.
804 //
805 // We add an additional 1ms to allow for processing time and
806 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800807 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800808 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700809
810 // All non-virtual displays are currently considered secure.
811 info.secure = true;
812
Michael Wright28f24d02016-07-12 13:30:53 -0700813 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 }
815
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 return NO_ERROR;
817}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700818
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800819status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700820 DisplayStatInfo* stats) {
821 if (stats == NULL) {
822 return BAD_VALUE;
823 }
824
825 // FIXME for now we always return stats for the primary display
826 memset(stats, 0, sizeof(*stats));
827 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
828 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
829 return NO_ERROR;
830}
831
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700832int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800833 if (display == NULL) {
834 ALOGE("%s : display is NULL", __func__);
835 return BAD_VALUE;
836 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700837
838 sp<const DisplayDevice> device(getDisplayDevice(display));
Dan Stoza24a42e92015-03-09 10:04:11 -0700839 if (device != NULL) {
840 return device->getActiveConfig();
841 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700842
Dan Stoza24a42e92015-03-09 10:04:11 -0700843 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700844}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700845
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700846void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
847 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
848 this);
849 int32_t type = hw->getDisplayType();
850 int currentMode = hw->getActiveConfig();
851
852 if (mode == currentMode) {
853 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
854 return;
855 }
856
857 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
858 ALOGW("Trying to set config for virtual display");
859 return;
860 }
861
862 hw->setActiveConfig(mode);
863 getHwComposer().setActiveConfig(type, mode);
864}
865
866status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
867 class MessageSetActiveConfig: public MessageBase {
868 SurfaceFlinger& mFlinger;
869 sp<IBinder> mDisplay;
870 int mMode;
871 public:
872 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
873 int mode) :
874 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
875 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700876 Vector<DisplayInfo> configs;
877 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700878 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700879 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700880 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700881 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700882 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700883 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
884 if (hw == NULL) {
885 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700886 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700887 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
888 ALOGW("Attempt to set active config = %d for virtual display",
889 mMode);
890 } else {
891 mFlinger.setActiveConfigInternal(hw, mMode);
892 }
893 return true;
894 }
895 };
896 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
897 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700898 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700899}
Michael Wright28f24d02016-07-12 13:30:53 -0700900status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
901 Vector<android_color_mode_t>* outColorModes) {
902 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
903 return BAD_VALUE;
904 }
905
906 if (!display.get()) {
907 return NAME_NOT_FOUND;
908 }
909
910 int32_t type = NAME_NOT_FOUND;
911 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
912 if (display == mBuiltinDisplays[i]) {
913 type = i;
914 break;
915 }
916 }
917
918 if (type < 0) {
919 return type;
920 }
921
Steven Thomas6d8110b2017-08-31 18:24:21 -0700922 std::vector<android_color_mode_t> modes;
923 {
924 ConditionalLock _l(mStateLock,
925 std::this_thread::get_id() != mMainThreadId);
926 modes = getHwComposer().getColorModes(type);
927 }
Michael Wright28f24d02016-07-12 13:30:53 -0700928 outColorModes->clear();
929 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
930
931 return NO_ERROR;
932}
933
934android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700935 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -0700936 if (device != nullptr) {
937 return device->getActiveColorMode();
938 }
939 return static_cast<android_color_mode_t>(BAD_VALUE);
940}
941
942void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
943 android_color_mode_t mode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700944 int32_t type = hw->getDisplayType();
945 android_color_mode_t currentMode = hw->getActiveColorMode();
946
947 if (mode == currentMode) {
Michael Wright28f24d02016-07-12 13:30:53 -0700948 return;
949 }
950
951 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
952 ALOGW("Trying to set config for virtual display");
953 return;
954 }
955
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600956 ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
957 hw->getDisplayType());
958
Michael Wright28f24d02016-07-12 13:30:53 -0700959 hw->setActiveColorMode(mode);
960 getHwComposer().setActiveColorMode(type, mode);
961}
962
963
964status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
965 android_color_mode_t colorMode) {
966 class MessageSetActiveColorMode: public MessageBase {
967 SurfaceFlinger& mFlinger;
968 sp<IBinder> mDisplay;
969 android_color_mode_t mMode;
970 public:
971 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
972 android_color_mode_t mode) :
973 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
974 virtual bool handler() {
975 Vector<android_color_mode_t> modes;
976 mFlinger.getDisplayColorModes(mDisplay, &modes);
977 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
978 if (mMode < 0 || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600979 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
980 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700981 return true;
982 }
983 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
984 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600985 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
986 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -0700987 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600988 ALOGW("Attempt to set active color mode %s %d for virtual display",
989 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -0700990 } else {
991 mFlinger.setActiveColorModeInternal(hw, mMode);
992 }
993 return true;
994 }
995 };
996 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
997 postMessageSync(msg);
998 return NO_ERROR;
999}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001000
Svetoslavd85084b2014-03-20 10:28:31 -07001001status_t SurfaceFlinger::clearAnimationFrameStats() {
1002 Mutex::Autolock _l(mStateLock);
1003 mAnimFrameTracker.clearStats();
1004 return NO_ERROR;
1005}
1006
1007status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1008 Mutex::Autolock _l(mStateLock);
1009 mAnimFrameTracker.getStats(outStats);
1010 return NO_ERROR;
1011}
1012
Dan Stozac4f471e2016-03-24 09:31:08 -07001013status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1014 HdrCapabilities* outCapabilities) const {
1015 Mutex::Autolock _l(mStateLock);
1016
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001017 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001018 if (displayDevice == nullptr) {
1019 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1020 return BAD_VALUE;
1021 }
1022
1023 std::unique_ptr<HdrCapabilities> capabilities =
1024 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1025 if (capabilities) {
1026 std::swap(*outCapabilities, *capabilities);
1027 } else {
1028 return BAD_VALUE;
1029 }
1030
1031 return NO_ERROR;
1032}
1033
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001034status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1035 if (enable == mInjectVSyncs) {
1036 return NO_ERROR;
1037 }
1038
1039 if (enable) {
1040 mInjectVSyncs = enable;
1041 ALOGV("VSync Injections enabled");
1042 if (mVSyncInjector.get() == nullptr) {
1043 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -07001044 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001045 }
1046 mEventQueue.setEventThread(mInjectorEventThread);
1047 } else {
1048 mInjectVSyncs = enable;
1049 ALOGV("VSync Injections disabled");
1050 mEventQueue.setEventThread(mSFEventThread);
1051 mVSyncInjector.clear();
1052 }
1053 return NO_ERROR;
1054}
1055
1056status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1057 if (!mInjectVSyncs) {
1058 ALOGE("VSync Injections not enabled");
1059 return BAD_VALUE;
1060 }
1061 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1062 ALOGV("Injecting VSync inside SurfaceFlinger");
1063 mVSyncInjector->onInjectSyncEvent(when);
1064 }
1065 return NO_ERROR;
1066}
1067
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001068// ----------------------------------------------------------------------------
1069
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001070sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1071 ISurfaceComposer::VsyncSource vsyncSource) {
1072 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1073 return mSFEventThread->createEventConnection();
1074 } else {
1075 return mEventThread->createEventConnection();
1076 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001077}
1078
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001079// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001080
1081void SurfaceFlinger::waitForEvent() {
1082 mEventQueue.waitMessage();
1083}
1084
1085void SurfaceFlinger::signalTransaction() {
1086 mEventQueue.invalidate();
1087}
1088
1089void SurfaceFlinger::signalLayerUpdate() {
1090 mEventQueue.invalidate();
1091}
1092
1093void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001094 mRefreshPending = true;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001095 mEventQueue.refresh();
1096}
1097
1098status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001099 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001100 return mEventQueue.postMessage(msg, reltime);
1101}
1102
1103status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001104 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001105 status_t res = mEventQueue.postMessage(msg, reltime);
1106 if (res == NO_ERROR) {
1107 msg->wait();
1108 }
1109 return res;
1110}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001111
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001112void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001113 do {
1114 waitForEvent();
1115 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001116}
1117
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001118void SurfaceFlinger::enableHardwareVsync() {
1119 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001120 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001121 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001122 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1123 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001124 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001125 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001126}
1127
Jesse Hall948fe0c2013-10-14 12:56:09 -07001128void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001129 Mutex::Autolock _l(mHWVsyncLock);
1130
Jesse Hall948fe0c2013-10-14 12:56:09 -07001131 if (makeAvailable) {
1132 mHWVsyncAvailable = true;
1133 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001134 // Hardware vsync is not currently available, so abort the resync
1135 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001136 return;
1137 }
1138
Dan Stoza9e56aa02015-11-02 13:00:03 -08001139 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1140 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001141
1142 mPrimaryDispSync.reset();
1143 mPrimaryDispSync.setPeriod(period);
1144
1145 if (!mPrimaryHWVsyncEnabled) {
1146 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001147 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1148 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001149 mPrimaryHWVsyncEnabled = true;
1150 }
1151}
1152
Jesse Hall948fe0c2013-10-14 12:56:09 -07001153void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001154 Mutex::Autolock _l(mHWVsyncLock);
1155 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001156 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1157 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001158 mPrimaryDispSync.endResync();
1159 mPrimaryHWVsyncEnabled = false;
1160 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001161 if (makeUnavailable) {
1162 mHWVsyncAvailable = false;
1163 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001164}
1165
Tim Murray4a4e4a22016-04-19 16:29:23 +00001166void SurfaceFlinger::resyncWithRateLimit() {
1167 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001168
1169 // No explicit locking is needed here since EventThread holds a lock while calling this method
1170 static nsecs_t sLastResyncAttempted = 0;
1171 const nsecs_t now = systemTime();
1172 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001173 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001174 }
Dan Stoza57164302017-05-08 14:03:54 -07001175 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001176}
1177
Steven Thomasd7f49c52017-07-26 18:48:28 -07001178void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1179 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001180 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001181 // Ignore any vsyncs from a previous hardware composer.
1182 if (sequenceId != mComposerSequenceId) {
1183 return;
1184 }
1185
1186 int32_t type;
1187 if (!mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001188 return;
1189 }
1190
Jamie Gennisd1700752013-10-14 12:22:52 -07001191 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001192
Jamie Gennisd1700752013-10-14 12:22:52 -07001193 { // Scope for the lock
1194 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001195 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001196 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001197 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001198 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001199
1200 if (needsHwVsync) {
1201 enableHardwareVsync();
1202 } else {
1203 disableHardwareVsync(false);
1204 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001205}
1206
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001207void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
Brian Andersond0010582017-03-07 13:20:31 -08001208 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001209 *compositorTiming = mCompositorTiming;
1210}
1211
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001212void SurfaceFlinger::createDefaultDisplayDevice() {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001213 const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001214 wp<IBinder> token = mBuiltinDisplays[type];
1215
1216 // All non-virtual displays are currently considered secure.
1217 const bool isSecure = true;
1218
1219 sp<IGraphicBufferProducer> producer;
1220 sp<IGraphicBufferConsumer> consumer;
1221 BufferQueue::createBufferQueue(&producer, &consumer);
1222
1223 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1224
1225 bool hasWideColorModes = false;
1226 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1227 for (android_color_mode_t colorMode : modes) {
1228 switch (colorMode) {
1229 case HAL_COLOR_MODE_DISPLAY_P3:
1230 case HAL_COLOR_MODE_ADOBE_RGB:
1231 case HAL_COLOR_MODE_DCI_P3:
1232 hasWideColorModes = true;
1233 break;
1234 default:
1235 break;
1236 }
1237 }
1238 sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1239 token, fbs, producer, mRenderEngine->getEGLConfig(),
1240 hasWideColorModes && hasWideColorDisplay);
1241 mDisplays.add(token, hw);
Thierry Strudel2924d012017-08-14 15:19:37 -07001242 android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
1243 if (hasWideColorModes && hasWideColorDisplay) {
1244 defaultColorMode = HAL_COLOR_MODE_SRGB;
1245 }
1246 setActiveColorModeInternal(hw, defaultColorMode);
Courtney Goeltzenleuchter281e8112017-07-13 17:54:01 -06001247 hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001248
1249 // Add the primary display token to mDrawingState so we don't try to
1250 // recreate the DisplayDevice for the primary display.
1251 mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1252
1253 // make the GLContext current so that we can create textures when creating
1254 // Layers (which may happens before we render something)
1255 hw->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001256}
1257
Steven Thomasd7f49c52017-07-26 18:48:28 -07001258void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1259 hwc2_display_t display, HWC2::Connection connection,
1260 bool primaryDisplay) {
1261 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1262 sequenceId, display,
1263 connection == HWC2::Connection::Connected ?
1264 "connected" : "disconnected",
1265 primaryDisplay ? "primary" : "external");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001266
Steven Thomasd7f49c52017-07-26 18:48:28 -07001267 // Only lock if we're not on the main thread. This function is normally
1268 // called on a hwbinder thread, but for the primary display it's called on
1269 // the main thread with the state lock already held, so don't attempt to
1270 // acquire it here.
1271 ConditionalLock lock(mStateLock,
1272 std::this_thread::get_id() != mMainThreadId);
1273
1274 if (primaryDisplay) {
1275 mHwc->onHotplug(display, connection);
1276 if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1277 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001278 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001279 createDefaultDisplayDevice();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001280 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001281 if (sequenceId != mComposerSequenceId) {
1282 return;
1283 }
1284 if (mHwc->isUsingVrComposer()) {
1285 ALOGE("External displays are not supported by the vr hardware composer.");
1286 return;
1287 }
1288 mHwc->onHotplug(display, connection);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001289 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Steven Thomasd7f49c52017-07-26 18:48:28 -07001290 if (connection == HWC2::Connection::Connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001291 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001292 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001293 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1294 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001295 }
1296 setTransactionFlags(eDisplayTransactionNeeded);
1297
Andy McFadden9e9689c2012-10-10 18:17:51 -07001298 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001299 }
Mathias Agopian86303202012-07-24 22:46:10 -07001300}
1301
Steven Thomasd7f49c52017-07-26 18:48:28 -07001302void SurfaceFlinger::onRefreshReceived(int sequenceId,
1303 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001304 Mutex::Autolock lock(mStateLock);
Steven Thomasd7f49c52017-07-26 18:48:28 -07001305 if (sequenceId != mComposerSequenceId) {
1306 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001307 }
Steven Thomas6d8110b2017-08-31 18:24:21 -07001308 repaintEverythingLocked();
Steven Thomas3cfac282017-02-06 12:29:30 -08001309}
1310
Dan Stoza9e56aa02015-11-02 13:00:03 -08001311void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001312 ATRACE_CALL();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001313 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001314 getHwComposer().setVsyncEnabled(disp,
1315 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001316}
1317
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001318// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasd7f49c52017-07-26 18:48:28 -07001319void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001320 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001321 // Clear the drawing state so that the logic inside of
1322 // handleTransactionLocked will fire. It will determine the delta between
1323 // mCurrentState and mDrawingState and re-apply all changes when we make the
1324 // transition.
1325 mDrawingState.displays.clear();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001326 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001327 mDisplays.clear();
1328}
1329
Steven Thomas050b2c82017-03-06 11:45:16 -08001330void SurfaceFlinger::updateVrFlinger() {
1331 if (!mVrFlinger)
1332 return;
1333 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1334 if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001335 return;
1336 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001337
Steven Thomasd7f49c52017-07-26 18:48:28 -07001338 if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1339 ALOGE("Vr flinger is only supported for remote hardware composer"
1340 " service connections. Ignoring request to transition to vr"
1341 " flinger.");
1342 mVrFlingerRequestsDisplay = false;
1343 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001344 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001345
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001346 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001347
Steven Thomasd7f49c52017-07-26 18:48:28 -07001348 int currentDisplayPowerMode = getDisplayDeviceLocked(
1349 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001350
Steven Thomasd7f49c52017-07-26 18:48:28 -07001351 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001352 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasd7f49c52017-07-26 18:48:28 -07001353 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001354
Steven Thomasd7f49c52017-07-26 18:48:28 -07001355 resetDisplayState();
1356 mHwc.reset(); // Delete the current instance before creating the new one
1357 mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1358 mHwc->registerCallback(this, ++mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001359
Steven Thomasd7f49c52017-07-26 18:48:28 -07001360 LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1361 "Switched to non-remote hardware composer");
1362
1363 if (vrFlingerRequestsDisplay) {
1364 mVrFlinger->GrantDisplayOwnership();
1365 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001366 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001367 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001368
1369 mVisibleRegionsDirty = true;
1370 invalidateHwcGeometry();
1371
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001372 // Re-enable default display.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001373 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1374 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1375 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001376
Steven Thomasd7f49c52017-07-26 18:48:28 -07001377 // Reset the timing values to account for the period of the swapped in HWC
1378 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1379 const nsecs_t period = activeConfig->getVsyncPeriod();
1380 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001381
Steven Thomasd7f49c52017-07-26 18:48:28 -07001382 // Use phase of 0 since phase is not known.
1383 // Use latency of 0, which will snap to the ideal latency.
1384 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001385
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001386 android_atomic_or(1, &mRepaintEverything);
1387 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001388}
1389
Mathias Agopian4fec8732012-06-29 14:12:52 -07001390void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001391 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001392 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001393 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001394 bool frameMissed = !mHadClientComposition &&
1395 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396 (mPreviousPresentFence->getSignalTime() ==
1397 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001398 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001399 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001400 signalLayerUpdate();
1401 break;
1402 }
1403
Steven Thomas050b2c82017-03-06 11:45:16 -08001404 // Now that we're going to make it to the handleMessageTransaction()
1405 // call below it's safe to call updateVrFlinger(), which will
1406 // potentially trigger a display handoff.
1407 updateVrFlinger();
1408
Dan Stoza6b9454d2014-11-07 16:00:59 -08001409 bool refreshNeeded = handleMessageTransaction();
1410 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001411 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001412 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001413 // Signal a refresh if a transaction modified the window state,
1414 // a new buffer was latched, or if HWC has requested a full
1415 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001416 signalRefresh();
1417 }
1418 break;
1419 }
1420 case MessageQueue::REFRESH: {
1421 handleMessageRefresh();
1422 break;
1423 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424 }
1425}
1426
Dan Stoza6b9454d2014-11-07 16:00:59 -08001427bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001428 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001429 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001430 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001431 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001432 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001433 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001434}
1435
Dan Stoza6b9454d2014-11-07 16:00:59 -08001436bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001437 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001438 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001439}
1440
1441void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001442 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001443
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001444 mRefreshPending = false;
1445
Pablo Ceballos40845df2016-01-25 17:41:15 -08001446 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001447
Brian Andersond6927fb2016-07-23 23:37:30 -07001448 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001449 rebuildLayerStacks();
1450 setUpHWComposer();
1451 doDebugFlashRegions();
1452 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001453 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001454
Fabien Sanglard11d0fc32016-12-01 15:43:01 -08001455 mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001456
1457 mHadClientComposition = false;
1458 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1459 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1460 mHadClientComposition = mHadClientComposition ||
1461 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1462 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001463
Dan Stoza9e56aa02015-11-02 13:00:03 -08001464 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001465}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001466
Mathias Agopiancd60f992012-08-16 16:28:27 -07001467void SurfaceFlinger::doDebugFlashRegions()
1468{
1469 // is debugging enabled
1470 if (CC_LIKELY(!mDebugRegion))
1471 return;
1472
1473 const bool repaintEverything = mRepaintEverything;
1474 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1475 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001476 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001477 // transform the dirty region into this screen's coordinate space
1478 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1479 if (!dirtyRegion.isEmpty()) {
1480 // redraw the whole screen
1481 doComposeSurfaces(hw, Region(hw->bounds()));
1482
1483 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001484 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001485 RenderEngine& engine(getRenderEngine());
1486 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1487
Mathias Agopianda27af92012-09-13 18:17:13 -07001488 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001489 }
1490 }
1491 }
1492
1493 postFramebuffer();
1494
1495 if (mDebugRegion > 1) {
1496 usleep(mDebugRegion * 1000);
1497 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001498
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001500 auto& displayDevice = mDisplays[displayId];
1501 if (!displayDevice->isDisplayOn()) {
1502 continue;
1503 }
1504
1505 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001506 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1507 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001508 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509}
1510
Brian Andersond6927fb2016-07-23 23:37:30 -07001511void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001512{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001513 ATRACE_CALL();
1514 ALOGV("preComposition");
1515
Mathias Agopiancd60f992012-08-16 16:28:27 -07001516 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001517 mDrawingState.traverseInZOrder([&](Layer* layer) {
1518 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001519 needExtraInvalidate = true;
1520 }
Robert Carr2047fae2016-11-28 14:09:09 -08001521 });
1522
Mathias Agopiancd60f992012-08-16 16:28:27 -07001523 if (needExtraInvalidate) {
1524 signalLayerUpdate();
1525 }
1526}
1527
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001528void SurfaceFlinger::updateCompositorTiming(
1529 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1530 std::shared_ptr<FenceTime>& presentFenceTime) {
1531 // Update queue of past composite+present times and determine the
1532 // most recently known composite to present latency.
1533 mCompositePresentTimes.push({compositeTime, presentFenceTime});
1534 nsecs_t compositeToPresentLatency = -1;
1535 while (!mCompositePresentTimes.empty()) {
1536 CompositePresentTime& cpt = mCompositePresentTimes.front();
1537 // Cached values should have been updated before calling this method,
1538 // which helps avoid duplicate syscalls.
1539 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1540 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1541 break;
1542 }
1543 compositeToPresentLatency = displayTime - cpt.composite;
1544 mCompositePresentTimes.pop();
1545 }
1546
1547 // Don't let mCompositePresentTimes grow unbounded, just in case.
1548 while (mCompositePresentTimes.size() > 16) {
1549 mCompositePresentTimes.pop();
1550 }
1551
Brian Andersond0010582017-03-07 13:20:31 -08001552 setCompositorTimingSnapped(
1553 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1554}
1555
1556void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1557 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001558 // Integer division and modulo round toward 0 not -inf, so we need to
1559 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001560 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001561 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1562 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1563
Brian Andersond0010582017-03-07 13:20:31 -08001564 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1565 if (idealLatency <= 0) {
1566 idealLatency = vsyncInterval;
1567 }
1568
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001569 // Snap the latency to a value that removes scheduling jitter from the
1570 // composition and present times, which often have >1ms of jitter.
1571 // Reducing jitter is important if an app attempts to extrapolate
1572 // something (such as user input) to an accurate diasplay time.
1573 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1574 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001575 nsecs_t bias = vsyncInterval / 2;
1576 int64_t extraVsyncs =
1577 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1578 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1579 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001580
Brian Andersond0010582017-03-07 13:20:31 -08001581 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582 mCompositorTiming.deadline = vsyncPhase - idealLatency;
1583 mCompositorTiming.interval = vsyncInterval;
Brian Andersond0010582017-03-07 13:20:31 -08001584 mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585}
1586
1587void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001589 ATRACE_CALL();
1590 ALOGV("postComposition");
1591
Brian Anderson3546a3f2016-07-14 11:51:14 -07001592 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001593 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001594 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001595 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001596 }
1597
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001598 // |mStateLock| not needed as we are on the main thread
1599 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001600
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001601 mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001602 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1603 if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1604 glCompositionDoneFenceTime =
1605 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1606 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1607 } else {
1608 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1609 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001610
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001611 mDisplayTimeline.updateSignalTimes();
Brian Anderson4e606e32017-03-16 15:34:57 -07001612 sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1613 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1614 mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001615
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001616 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1617 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1618
1619 // We use the refreshStartTime which might be sampled a little later than
1620 // when we started doing work for this frame, but that should be okay
1621 // since updateCompositorTiming has snapping logic.
1622 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001623 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001624 CompositorTiming compositorTiming;
1625 {
1626 std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1627 compositorTiming = mCompositorTiming;
1628 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001629
Robert Carr2047fae2016-11-28 14:09:09 -08001630 mDrawingState.traverseInZOrder([&](Layer* layer) {
1631 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001632 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001633 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001634 recordBufferingStats(layer->getName().string(),
1635 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001636 }
Robert Carr2047fae2016-11-28 14:09:09 -08001637 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001638
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001639 if (presentFenceTime->isValid()) {
1640 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001641 enableHardwareVsync();
1642 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001643 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001644 }
1645 }
1646
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001647 if (!hasSyncFramework) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001648 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001649 enableHardwareVsync();
1650 }
1651 }
1652
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001653 if (mAnimCompositionPending) {
1654 mAnimCompositionPending = false;
1655
Brian Anderson4e606e32017-03-16 15:34:57 -07001656 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001657 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001658 std::move(presentFenceTime));
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001659 } else {
1660 // The HWC doesn't support present fences, so use the refresh
1661 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001662 nsecs_t presentTime =
1663 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001664 mAnimFrameTracker.setActualPresentTime(presentTime);
1665 }
1666 mAnimFrameTracker.advanceFrame();
1667 }
Dan Stozab90cf072015-03-05 11:05:59 -08001668
1669 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1670 return;
1671 }
1672
1673 nsecs_t currentTime = systemTime();
1674 if (mHasPoweredOff) {
1675 mHasPoweredOff = false;
1676 } else {
Dan Stozab90cf072015-03-05 11:05:59 -08001677 nsecs_t elapsedTime = currentTime - mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001678 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
Dan Stozab90cf072015-03-05 11:05:59 -08001679 if (numPeriods < NUM_BUCKETS - 1) {
1680 mFrameBuckets[numPeriods] += elapsedTime;
1681 } else {
1682 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1683 }
1684 mTotalTime += elapsedTime;
1685 }
1686 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001687}
1688
1689void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001690 ATRACE_CALL();
1691 ALOGV("rebuildLayerStacks");
1692
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001694 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1695 ATRACE_CALL();
1696 mVisibleRegionsDirty = false;
1697 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001698
Jeff Sharkey76488112017-02-27 14:15:18 -07001699 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1700 Region opaqueRegion;
1701 Region dirtyRegion;
1702 Vector<sp<Layer>> layersSortedByZ;
1703 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1704 const Transform& tr(displayDevice->getTransform());
1705 const Rect bounds(displayDevice->getBounds());
1706 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001707 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001708
Jeff Sharkey76488112017-02-27 14:15:18 -07001709 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001710 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1711 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001712 Region drawRegion(tr.transform(
1713 layer->visibleNonTransparentRegion));
1714 drawRegion.andSelf(bounds);
1715 if (!drawRegion.isEmpty()) {
1716 layersSortedByZ.add(layer);
1717 } else {
1718 // Clear out the HWC layer if this layer was
1719 // previously visible, but no longer is
Steven Thomasd7f49c52017-07-26 18:48:28 -07001720 layer->destroyHwcLayer(
1721 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001722 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001723 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001724 // WM changes displayDevice->layerStack upon sleep/awake.
1725 // Here we make sure we delete the HWC layers even if
1726 // WM changed their layer stack.
Steven Thomasd7f49c52017-07-26 18:48:28 -07001727 layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001728 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001729 });
1730 }
1731 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1732 displayDevice->undefinedRegion.set(bounds);
1733 displayDevice->undefinedRegion.subtractSelf(
1734 tr.transform(opaqueRegion));
1735 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001736 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001737 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001738}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001739
Romain Guy0147a172017-06-01 13:53:56 -07001740mat4 SurfaceFlinger::computeSaturationMatrix() const {
1741 if (mSaturation == 1.0f) {
1742 return mat4();
1743 }
1744
1745 // Rec.709 luma coefficients
1746 float3 luminance{0.213f, 0.715f, 0.072f};
1747 luminance *= 1.0f - mSaturation;
1748 return mat4(
1749 vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1750 vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1751 vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1752 vec4{0.0f, 0.0f, 0.0f, 1.0f}
1753 );
1754}
1755
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001756// pickColorMode translates a given dataspace into the best available color mode.
1757// Currently only support sRGB and Display-P3.
Romain Guy0147a172017-06-01 13:53:56 -07001758android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001759 switch (dataSpace) {
1760 // treat Unknown as regular SRGB buffer, since that's what the rest of the
1761 // system expects.
1762 case HAL_DATASPACE_UNKNOWN:
1763 case HAL_DATASPACE_SRGB:
1764 case HAL_DATASPACE_V0_SRGB:
1765 return HAL_COLOR_MODE_SRGB;
1766 break;
1767
1768 case HAL_DATASPACE_DISPLAY_P3:
1769 return HAL_COLOR_MODE_DISPLAY_P3;
1770 break;
1771
1772 default:
1773 // TODO (courtneygo): Do we want to assert an error here?
1774 ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1775 dataSpace);
1776 return HAL_COLOR_MODE_SRGB;
1777 break;
1778 }
1779}
1780
Romain Guy0147a172017-06-01 13:53:56 -07001781android_dataspace SurfaceFlinger::bestTargetDataSpace(
1782 android_dataspace a, android_dataspace b) const {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001783 // Only support sRGB and Display-P3 right now.
1784 if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1785 return HAL_DATASPACE_DISPLAY_P3;
1786 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001787 if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1788 return HAL_DATASPACE_DISPLAY_P3;
1789 }
1790 if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1791 return HAL_DATASPACE_DISPLAY_P3;
1792 }
1793
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001794 return HAL_DATASPACE_V0_SRGB;
1795}
1796
Mathias Agopiancd60f992012-08-16 16:28:27 -07001797void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001798 ATRACE_CALL();
1799 ALOGV("setUpHWComposer");
1800
Jesse Hall028dc8f2013-08-20 16:35:32 -07001801 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001802 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1803 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1804 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1805
1806 // If nothing has changed (!dirty), don't recompose.
1807 // If something changed, but we don't currently have any visible layers,
1808 // and didn't when we last did a composition, then skip it this time.
1809 // The second rule does two things:
1810 // - When all layers are removed from a display, we'll emit one black
1811 // frame, then nothing more until we get new layers.
1812 // - When a display is created with a private layer stack, we won't
1813 // emit any black frames until a layer is added to the layer stack.
1814 bool mustRecompose = dirty && !(empty && wasEmpty);
1815
1816 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1817 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1818 mustRecompose ? "doing" : "skipping",
1819 dirty ? "+" : "-",
1820 empty ? "+" : "-",
1821 wasEmpty ? "+" : "-");
1822
Dan Stoza71433162014-02-04 16:22:36 -08001823 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001824
1825 if (mustRecompose) {
1826 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1827 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001828 }
1829
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830 // build the h/w work list
1831 if (CC_UNLIKELY(mGeometryInvalid)) {
1832 mGeometryInvalid = false;
1833 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1834 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1835 const auto hwcId = displayDevice->getHwcDisplayId();
1836 if (hwcId >= 0) {
1837 const Vector<sp<Layer>>& currentLayers(
1838 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08001839 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001840 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08001841 if (!layer->hasHwcLayer(hwcId)) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07001842 if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001844 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001845 }
1846 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001847
Robert Carrae060832016-11-28 10:51:00 -08001848 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001849 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001850 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001851 }
1852 }
1853 }
1854 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 }
Riley Andrews03414a12014-07-01 14:22:59 -07001856
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001857
Romain Guy0147a172017-06-01 13:53:56 -07001858 mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001859
Dan Stoza9e56aa02015-11-02 13:00:03 -08001860 // Set the per-frame data
1861 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1862 auto& displayDevice = mDisplays[displayId];
1863 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001864
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 if (hwcId < 0) {
1866 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001867 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001868 if (colorMatrix != mPreviousColorMatrix) {
1869 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1870 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1871 "display %zd: %d", displayId, result);
1872 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001873 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1874 layer->setPerFrameData(displayDevice);
1875 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001876
1877 if (hasWideColorDisplay) {
1878 android_color_mode newColorMode;
1879 android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1880
1881 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1882 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1883 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1884 layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1885 layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1886 }
1887 newColorMode = pickColorMode(newDataSpace);
1888
Thierry Strudel2924d012017-08-14 15:19:37 -07001889 setActiveColorModeInternal(displayDevice, newColorMode);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001890 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001891 }
1892
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001893 mPreviousColorMatrix = colorMatrix;
1894
Dan Stoza9e56aa02015-11-02 13:00:03 -08001895 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001896 auto& displayDevice = mDisplays[displayId];
1897 if (!displayDevice->isDisplayOn()) {
1898 continue;
1899 }
1900
1901 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001902 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1903 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001904 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001905}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001906
Mathias Agopiancd60f992012-08-16 16:28:27 -07001907void SurfaceFlinger::doComposition() {
1908 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001909 ALOGV("doComposition");
1910
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001911 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001912 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001913 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001914 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001915 // transform the dirty region into this screen's coordinate space
1916 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001917
1918 // repaint the framebuffer (if needed)
1919 doDisplayComposition(hw, dirtyRegion);
1920
Mathias Agopiancd60f992012-08-16 16:28:27 -07001921 hw->dirtyRegion.clear();
1922 hw->flip(hw->swapRegion);
1923 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001924 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001925 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001926 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001927}
1928
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929void SurfaceFlinger::postFramebuffer()
1930{
Mathias Agopian841cde52012-03-01 15:44:37 -08001931 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001932 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001933
Mathias Agopiana44b0412011-10-16 18:46:35 -07001934 const nsecs_t now = systemTime();
1935 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001936
Dan Stoza9e56aa02015-11-02 13:00:03 -08001937 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1938 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001939 if (!displayDevice->isDisplayOn()) {
1940 continue;
1941 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001942 const auto hwcId = displayDevice->getHwcDisplayId();
1943 if (hwcId >= 0) {
Fabien Sanglarda87aa7b2016-11-30 16:27:22 -08001944 mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001945 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001946 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001947 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001948 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1949 sp<Fence> releaseFence = Fence::NO_FENCE;
1950 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1951 releaseFence = displayDevice->getClientTargetAcquireFence();
1952 } else {
1953 auto hwcLayer = layer->getHwcLayer(hwcId);
1954 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001955 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001956 layer->onLayerDisplayed(releaseFence);
1957 }
1958 if (hwcId >= 0) {
1959 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001960 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001961 }
1962
Mathias Agopiana44b0412011-10-16 18:46:35 -07001963 mLastSwapBufferTime = systemTime() - now;
1964 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001965
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001966 // |mStateLock| not needed as we are on the main thread
1967 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
Jamie Gennis6547ff42013-07-16 20:12:42 -07001968 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1969 logFrameStats();
1970 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001971}
1972
Mathias Agopian87baae12012-07-31 12:38:26 -07001973void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001974{
Mathias Agopian841cde52012-03-01 15:44:37 -08001975 ATRACE_CALL();
1976
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001977 // here we keep a copy of the drawing state (that is the state that's
1978 // going to be overwritten by handleTransactionLocked()) outside of
1979 // mStateLock so that the side-effects of the State assignment
1980 // don't happen with mStateLock held (which can cause deadlocks).
1981 State drawingState(mDrawingState);
1982
Mathias Agopianca4d3602011-05-19 15:38:14 -07001983 Mutex::Autolock _l(mStateLock);
1984 const nsecs_t now = systemTime();
1985 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986
Mathias Agopianca4d3602011-05-19 15:38:14 -07001987 // Here we're guaranteed that some transaction flags are set
1988 // so we can call handleTransactionLocked() unconditionally.
1989 // We call getTransactionFlags(), which will also clear the flags,
1990 // with mStateLock held to guarantee that mCurrentState won't change
1991 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001992
Mathias Agopiane57f2922012-08-09 16:29:12 -07001993 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001994 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001995
Mathias Agopianca4d3602011-05-19 15:38:14 -07001996 mLastTransactionTime = systemTime() - now;
1997 mDebugInTransaction = 0;
1998 invalidateHwcGeometry();
1999 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002000}
2001
Mathias Agopian87baae12012-07-31 12:38:26 -07002002void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002003{
Dan Stoza7dde5992015-05-22 09:51:44 -07002004 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002005 mCurrentState.traverseInZOrder([](Layer* layer) {
2006 layer->notifyAvailableFrames();
2007 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002008
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002009 /*
2010 * Traversal of the children
2011 * (perform the transaction for each of them if needed)
2012 */
2013
Mathias Agopian3559b072012-08-15 13:46:03 -07002014 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002015 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002016 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002017 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002018
2019 const uint32_t flags = layer->doTransaction(0);
2020 if (flags & Layer::eVisibleRegion)
2021 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002022 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002023 }
2024
2025 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002026 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002027 */
2028
Mathias Agopiane57f2922012-08-09 16:29:12 -07002029 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002030 // here we take advantage of Vector's copy-on-write semantics to
2031 // improve performance by skipping the transaction entirely when
2032 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07002033 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2034 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002035 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07002037 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07002038 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07002039
2040 // find the displays that were removed
2041 // (ie: in drawing state but not in current state)
2042 // also handle displays that changed
2043 // (ie: displays that are in both lists)
2044 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002045 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2046 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002047 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002048 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07002049 // Call makeCurrent() on the primary display so we can
2050 // be sure that nothing associated with this display
2051 // is current.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002052 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
Mathias Agopian875d8e12013-06-07 15:35:48 -07002053 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002054 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
Jesse Hall02d86562013-03-25 14:43:23 -07002055 if (hw != NULL)
2056 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07002057 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08002058 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07002059 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07002060 } else {
2061 ALOGW("trying to remove the main display");
2062 }
2063 } else {
2064 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07002065 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002066 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08002067 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2068 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07002069 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002070 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07002071 // recreating the DisplayDevice, so we just remove it
2072 // from the drawing state, so that it get re-added
2073 // below.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002074 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
Jesse Hall02d86562013-03-25 14:43:23 -07002075 if (hw != NULL)
2076 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07002077 mDisplays.removeItem(display);
2078 mDrawingState.displays.removeItemsAt(i);
2079 dc--; i--;
2080 // at this point we must loop to the next item
2081 continue;
2082 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002083
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002084 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07002085 if (disp != NULL) {
2086 if (state.layerStack != draw[i].layerStack) {
2087 disp->setLayerStack(state.layerStack);
2088 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002089 if ((state.orientation != draw[i].orientation)
2090 || (state.viewport != draw[i].viewport)
2091 || (state.frame != draw[i].frame))
2092 {
2093 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002094 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07002095 }
Michael Lentine47e45402014-07-18 15:34:25 -07002096 if (state.width != draw[i].width || state.height != draw[i].height) {
2097 disp->setDisplaySize(state.width, state.height);
2098 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002099 }
2100 }
2101 }
2102
2103 // find displays that were added
2104 // (ie: in current state but not in drawing state)
2105 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002106 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002107 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002108
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002109 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002110 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07002111 sp<IGraphicBufferProducer> bqProducer;
2112 sp<IGraphicBufferConsumer> bqConsumer;
Mathias Agopian0556d792017-03-22 15:49:32 -07002113 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002114
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002116 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07002117 // Virtual displays without a surface are dormant:
2118 // they have external state (layer stack, projection,
2119 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002120 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002121
Alex Sakhartchouk5cee1362017-03-26 12:28:34 -04002122 // Allow VR composer to use virtual displays.
Steven Thomasd7f49c52017-07-26 18:48:28 -07002123 if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
Dan Stoza8cf150a2016-08-02 10:27:31 -07002124 int width = 0;
2125 int status = state.surface->query(
2126 NATIVE_WINDOW_WIDTH, &width);
2127 ALOGE_IF(status != NO_ERROR,
2128 "Unable to query width (%d)", status);
2129 int height = 0;
2130 status = state.surface->query(
2131 NATIVE_WINDOW_HEIGHT, &height);
2132 ALOGE_IF(status != NO_ERROR,
2133 "Unable to query height (%d)", status);
2134 int intFormat = 0;
2135 status = state.surface->query(
2136 NATIVE_WINDOW_FORMAT, &intFormat);
2137 ALOGE_IF(status != NO_ERROR,
2138 "Unable to query format (%d)", status);
2139 auto format = static_cast<android_pixel_format_t>(
2140 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07002141
Dan Stoza8cf150a2016-08-02 10:27:31 -07002142 mHwc->allocateVirtualDisplay(width, height, &format,
2143 &hwcId);
2144 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002145
Dan Stoza5cf424b2016-05-20 14:02:39 -07002146 // TODO: Plumb requested format back up to consumer
2147
Dan Stoza9e56aa02015-11-02 13:00:03 -08002148 sp<VirtualDisplaySurface> vds =
2149 new VirtualDisplaySurface(*mHwc,
2150 hwcId, state.surface, bqProducer,
2151 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07002152
2153 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07002154 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002155 }
2156 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07002157 ALOGE_IF(state.surface!=NULL,
2158 "adding a supported display, but rendering "
2159 "surface is provided (%p), ignoring it",
2160 state.surface.get());
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08002161
2162 hwcId = state.type;
2163 dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
2164 producer = bqProducer;
Mathias Agopiancde87a32012-09-13 14:09:01 -07002165 }
2166
2167 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07002168 if (dispSurface != NULL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002169 sp<DisplayDevice> hw =
2170 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
2171 dispSurface, producer,
2172 mRenderEngine->getEGLConfig(),
2173 hasWideColorDisplay);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002174 hw->setLayerStack(state.layerStack);
2175 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07002176 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07002177 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07002178 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002179 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08002180 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07002181 }
Mathias Agopian93997a82012-08-29 17:30:36 -07002182 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07002183 }
2184 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002185 }
Mathias Agopian3559b072012-08-15 13:46:03 -07002186 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002187
Mathias Agopian84300952012-11-21 16:02:13 -08002188 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
2189 // The transform hint might have changed for some layers
2190 // (either because a display has changed, or because a layer
2191 // as changed).
2192 //
2193 // Walk through all the layers in currentLayers,
2194 // and update their transform hint.
2195 //
2196 // If a layer is visible only on a single display, then that
2197 // display is used to calculate the hint, otherwise we use the
2198 // default display.
2199 //
2200 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2201 // the hint is set before we acquire a buffer from the surface texture.
2202 //
2203 // NOTE: layer transactions have taken place already, so we use their
2204 // drawing state. However, SurfaceFlinger's own transaction has not
2205 // happened yet, so we must use the current state layer list
2206 // (soon to become the drawing state list).
2207 //
2208 sp<const DisplayDevice> disp;
2209 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002210 bool first = true;
2211 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002212 // NOTE: we rely on the fact that layers are sorted by
2213 // layerStack first (so we don't have to traverse the list
2214 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002215 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002216 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002217 currentlayerStack = layerStack;
2218 // figure out if this layerstack is mirrored
2219 // (more than one display) if so, pick the default display,
2220 // if not, pick the only display it's on.
2221 disp.clear();
2222 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2223 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002224 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian84300952012-11-21 16:02:13 -08002225 if (disp == NULL) {
2226 disp = hw;
2227 } else {
Chet Haase91d25932013-04-11 15:24:55 -07002228 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08002229 break;
2230 }
2231 }
2232 }
2233 }
Chet Haase91d25932013-04-11 15:24:55 -07002234 if (disp == NULL) {
2235 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2236 // redraw after transform hint changes. See bug 8508397.
2237
2238 // could be null when this layer is using a layerStack
2239 // that is not visible on any display. Also can occur at
2240 // screen off/on times.
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002241 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002242 }
Chet Haase91d25932013-04-11 15:24:55 -07002243 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08002244
2245 first = false;
2246 });
Mathias Agopian84300952012-11-21 16:02:13 -08002247 }
2248
2249
Mathias Agopian3559b072012-08-15 13:46:03 -07002250 /*
2251 * Perform our own transaction if needed
2252 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002253
2254 if (mLayersAdded) {
2255 mLayersAdded = false;
2256 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002257 mVisibleRegionsDirty = true;
2258 }
2259
2260 // some layers might have been removed, so
2261 // we need to update the regions they're exposing.
2262 if (mLayersRemoved) {
2263 mLayersRemoved = false;
2264 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002265 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002266 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002267 // this layer is not visible anymore
2268 // TODO: we could traverse the tree from front to back and
2269 // compute the actual visible region
2270 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002271 Region visibleReg;
2272 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002273 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002274 }
Robert Carr2047fae2016-11-28 14:09:09 -08002275 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002276 }
2277
2278 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002279
2280 updateCursorAsync();
2281}
2282
2283void SurfaceFlinger::updateCursorAsync()
2284{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002285 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2286 auto& displayDevice = mDisplays[displayId];
2287 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002288 continue;
2289 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002290
2291 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2292 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002293 }
2294 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002295}
2296
2297void SurfaceFlinger::commitTransaction()
2298{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002299 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002300 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002301 for (const auto& l : mLayersPendingRemoval) {
2302 recordBufferingStats(l->getName().string(),
2303 l->getOccupancyHistory(true));
2304 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002305 }
2306 mLayersPendingRemoval.clear();
2307 }
2308
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002309 // If this transaction is part of a window animation then the next frame
2310 // we composite should be considered an animation as well.
2311 mAnimCompositionPending = mAnimTransactionPending;
2312
Mathias Agopian4fec8732012-06-29 14:12:52 -07002313 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07002314 mDrawingState.traverseInZOrder([](Layer* layer) {
2315 layer->commitChildList();
2316 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002317 mTransactionPending = false;
2318 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002319 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002320}
2321
Chia-I Wuab0c3192017-08-01 11:29:00 -07002322void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002323 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002324{
Mathias Agopian841cde52012-03-01 15:44:37 -08002325 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002326 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328 Region aboveOpaqueLayers;
2329 Region aboveCoveredLayers;
2330 Region dirty;
2331
Mathias Agopian87baae12012-07-31 12:38:26 -07002332 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333
Robert Carr2047fae2016-11-28 14:09:09 -08002334 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002336 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337
Jesse Hall01e29052013-02-19 16:13:35 -08002338 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002339 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002340 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002341
Mathias Agopianab028732010-03-16 16:41:46 -07002342 /*
2343 * opaqueRegion: area of a surface that is fully opaque.
2344 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002346
2347 /*
2348 * visibleRegion: area of a surface that is visible on screen
2349 * and not fully transparent. This is essentially the layer's
2350 * footprint minus the opaque regions above it.
2351 * Areas covered by a translucent surface are considered visible.
2352 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002354
2355 /*
2356 * coveredRegion: area of a surface that is covered by all
2357 * visible regions above it (which includes the translucent areas).
2358 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002360
Jesse Halla8026d22012-09-25 13:25:04 -07002361 /*
2362 * transparentRegion: area of a surface that is hinted to be completely
2363 * transparent. This is only used to tell when the layer has no visible
2364 * non-transparent regions and can be removed from the layer list. It
2365 * does not affect the visibleRegion of this layer or any layers
2366 * beneath it. The hint may not be correct if apps don't respect the
2367 * SurfaceView restrictions (which, sadly, some don't).
2368 */
2369 Region transparentRegion;
2370
Mathias Agopianab028732010-03-16 16:41:46 -07002371
2372 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002373 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002374 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002375 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002377 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002378 if (!visibleRegion.isEmpty()) {
2379 // Remove the transparent area from the visible region
2380 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002381 if (tr.preserveRects()) {
2382 // transform the transparent region
2383 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002384 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002385 // transformation too complex, can't do the
2386 // transparent region optimization.
2387 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002388 }
Mathias Agopianab028732010-03-16 16:41:46 -07002389 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002390
Mathias Agopianab028732010-03-16 16:41:46 -07002391 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002392 const int32_t layerOrientation = tr.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002393 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002394 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2395 // the opaque region is the layer's footprint
2396 opaqueRegion = visibleRegion;
2397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398 }
2399 }
2400
Mathias Agopianab028732010-03-16 16:41:46 -07002401 // Clip the covered region to the visible region
2402 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2403
2404 // Update aboveCoveredLayers for next (lower) layer
2405 aboveCoveredLayers.orSelf(visibleRegion);
2406
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002407 // subtract the opaque region covered by the layers above us
2408 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002409
2410 // compute this layer's dirty region
2411 if (layer->contentDirty) {
2412 // we need to invalidate the whole region
2413 dirty = visibleRegion;
2414 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002415 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002416 layer->contentDirty = false;
2417 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002418 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002419 * the exposed region consists of two components:
2420 * 1) what's VISIBLE now and was COVERED before
2421 * 2) what's EXPOSED now less what was EXPOSED before
2422 *
2423 * note that (1) is conservative, we start with the whole
2424 * visible region but only keep what used to be covered by
2425 * something -- which mean it may have been exposed.
2426 *
2427 * (2) handles areas that were not covered by anything but got
2428 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002429 */
Mathias Agopianab028732010-03-16 16:41:46 -07002430 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002431 const Region oldVisibleRegion = layer->visibleRegion;
2432 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002433 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2434 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002435 }
2436 dirty.subtractSelf(aboveOpaqueLayers);
2437
2438 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002439 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440
Mathias Agopianab028732010-03-16 16:41:46 -07002441 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002442 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002443
Jesse Halla8026d22012-09-25 13:25:04 -07002444 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445 layer->setVisibleRegion(visibleRegion);
2446 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002447 layer->setVisibleNonTransparentRegion(
2448 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002449 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450
Mathias Agopian87baae12012-07-31 12:38:26 -07002451 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002452}
2453
Chia-I Wuab0c3192017-08-01 11:29:00 -07002454void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002455 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002456 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002457 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002458 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002459 }
2460 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002461}
2462
Dan Stoza6b9454d2014-11-07 16:00:59 -08002463bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002464{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002465 ALOGV("handlePageFlip");
2466
Brian Andersond6927fb2016-07-23 23:37:30 -07002467 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468
Mathias Agopian4fec8732012-06-29 14:12:52 -07002469 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002470 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002471 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002472
2473 // Store the set of layers that need updates. This set must not change as
2474 // buffers are being latched, as this could result in a deadlock.
2475 // Example: Two producers share the same command stream and:
2476 // 1.) Layer 0 is latched
2477 // 2.) Layer 0 gets a new frame
2478 // 2.) Layer 1 gets a new frame
2479 // 3.) Layer 1 is latched.
2480 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2481 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002482 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002483 if (layer->hasQueuedFrame()) {
2484 frameQueued = true;
2485 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002486 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002487 } else {
2488 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002489 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002490 } else {
2491 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002492 }
Robert Carr2047fae2016-11-28 14:09:09 -08002493 });
2494
Dan Stoza9e56aa02015-11-02 13:00:03 -08002495 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002496 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002497 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002498 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002499 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002500 newDataLatched = true;
2501 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002502 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002503
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002504 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002505
2506 // If we will need to wake up at some time in the future to deal with a
2507 // queued frame that shouldn't be displayed during this vsync period, wake
2508 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002509 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002510 signalLayerUpdate();
2511 }
2512
2513 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002514 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002515}
2516
Mathias Agopianad456f92011-01-13 17:53:01 -08002517void SurfaceFlinger::invalidateHwcGeometry()
2518{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002519 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002520}
2521
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002522
Fabien Sanglard830b8472016-11-30 16:35:58 -08002523void SurfaceFlinger::doDisplayComposition(
2524 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002525 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526{
Dan Stoza71433162014-02-04 16:22:36 -08002527 // We only need to actually compose the display if:
2528 // 1) It is being handled by hardware composer, which may need this to
2529 // keep its virtual display state machine in sync, or
2530 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002531 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002532 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002533 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002534 return;
2535 }
2536
Dan Stoza9e56aa02015-11-02 13:00:03 -08002537 ALOGV("doDisplayComposition");
2538
Mathias Agopian87baae12012-07-31 12:38:26 -07002539 Region dirtyRegion(inDirtyRegion);
2540
Mathias Agopianb8a55602009-06-26 19:06:36 -07002541 // compute the invalid region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002542 displayDevice->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543
Fabien Sanglard830b8472016-11-30 16:35:58 -08002544 uint32_t flags = displayDevice->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002545 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002546 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2547 // takes a rectangle, we must make sure to update that whole
2548 // rectangle in that case
Fabien Sanglard830b8472016-11-30 16:35:58 -08002549 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002550 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002551 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002552 // We need to redraw the rectangle that will be updated
2553 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002554 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002555 // rectangle instead of a region (see DisplayDevice::flip())
Fabien Sanglard830b8472016-11-30 16:35:58 -08002556 dirtyRegion.set(displayDevice->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002557 } else {
2558 // we need to redraw everything (the whole screen)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002559 dirtyRegion.set(displayDevice->bounds());
2560 displayDevice->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561 }
2562 }
2563
Fabien Sanglard830b8472016-11-30 16:35:58 -08002564 if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002566 // update the swap region and clear the dirty region
Fabien Sanglard830b8472016-11-30 16:35:58 -08002567 displayDevice->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002568
2569 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002570 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571}
2572
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573bool SurfaceFlinger::doComposeSurfaces(
2574 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002575{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002576 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002577
Dan Stoza9e56aa02015-11-02 13:00:03 -08002578 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002579
2580 mat4 oldColorMatrix;
2581 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2582 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2583 if (applyColorMatrix) {
2584 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2585 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2586 }
2587
Dan Stoza9e56aa02015-11-02 13:00:03 -08002588 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2589 if (hasClientComposition) {
2590 ALOGV("hasClientComposition");
2591
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002592#ifdef USE_HWC2
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002593 mRenderEngine->setWideColor(displayDevice->getWideColorSupport());
Romain Guy88d37dd2017-05-26 17:57:05 -07002594 mRenderEngine->setColorMode(displayDevice->getActiveColorMode());
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002595#endif
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002597 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002598 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002599 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002600
2601 // |mStateLock| not needed as we are on the main thread
2602 if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07002603 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2604 }
2605 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002606 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002607
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002608 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002609 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2610 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002611 // when using overlays, we assume a fully transparent framebuffer
2612 // NOTE: we could reduce how much we need to clear, for instance
2613 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002614 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002615 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002616 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002617 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002618 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002619 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002620
2621 // we remove the scissor part
2622 // we're left with the letterbox region
2623 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002624 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002625
2626 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002627 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002628
2629 // but limit it to the dirty region
2630 region.andSelf(dirty);
2631
Mathias Agopianb9494d52012-04-18 02:28:45 -07002632 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002633 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002634 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002635 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002636 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002637 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002638
Dan Stoza9e56aa02015-11-02 13:00:03 -08002639 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002640 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002641 // scissor on the main display. It should never be needed
2642 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002643 const Rect& bounds(displayDevice->getBounds());
2644 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002645 if (scissor != bounds) {
2646 // scissor doesn't match the screen's dimensions, so we
2647 // need to clear everything outside of it and enable
2648 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002649
Mathias Agopianf45c5102012-10-24 16:29:17 -07002650 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002651 const uint32_t height = displayDevice->getHeight();
2652 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002653 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002654 }
2655 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002656 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002657
Mathias Agopian85d751c2012-08-29 16:59:24 -07002658 /*
2659 * and then, render the layers targeted at the framebuffer
2660 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002661
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 ALOGV("Rendering client layers");
2663 const Transform& displayTransform = displayDevice->getTransform();
2664 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002665 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002666 bool firstLayer = true;
2667 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2668 const Region clip(dirty.intersect(
2669 displayTransform.transform(layer->visibleRegion)));
2670 ALOGV("Layer: %s", layer->getName().string());
2671 ALOGV(" Composition type: %s",
2672 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002673 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002674 switch (layer->getCompositionType(hwcId)) {
2675 case HWC2::Composition::Cursor:
2676 case HWC2::Composition::Device:
Gray Huang267ab792017-01-11 13:41:09 +08002677 case HWC2::Composition::Sideband:
Dan Stoza9e56aa02015-11-02 13:00:03 -08002678 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002679 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2681 layer->isOpaque(state) && (state.alpha == 1.0f)
2682 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002683 // never clear the very first layer since we're
2684 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002685 layer->clearWithOpenGL(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002686 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002687 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002688 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002689 case HWC2::Composition::Client: {
2690 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002691 break;
2692 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002694 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002695 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002696 } else {
2697 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002698 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002699 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002700 }
2701 } else {
2702 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002703 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002704 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002705 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002706 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002708 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002709 }
2710 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002711
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002712 if (applyColorMatrix) {
2713 getRenderEngine().setupColorTransform(oldColorMatrix);
2714 }
2715
Mathias Agopianf45c5102012-10-24 16:29:17 -07002716 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002717 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002718 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719}
2720
Fabien Sanglard830b8472016-11-30 16:35:58 -08002721void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
2722 const int32_t height = displayDevice->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002723 RenderEngine& engine(getRenderEngine());
2724 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725}
2726
Dan Stoza7d89d062015-04-30 13:29:25 -07002727status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002728 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002729 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002730 const sp<Layer>& lbc,
2731 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07002732{
Dan Stoza7d89d062015-04-30 13:29:25 -07002733 // add this layer to the current state list
2734 {
2735 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002736 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002737 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
2738 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002739 return NO_MEMORY;
2740 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741 if (parent == nullptr) {
2742 mCurrentState.layersSortedByZ.add(lbc);
2743 } else {
Chia-I Wu98f1c102017-05-30 14:54:08 -07002744 if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
2745 ALOGE("addClientLayer called with a removed parent");
2746 return NAME_NOT_FOUND;
2747 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002748 parent->addChild(lbc);
2749 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002750
Dan Stoza7d89d062015-04-30 13:29:25 -07002751 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002752 mLayersAdded = true;
2753 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07002754 }
2755
Mathias Agopian96f08192010-06-02 23:28:45 -07002756 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002757 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002758
Dan Stoza7d89d062015-04-30 13:29:25 -07002759 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002760}
2761
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002762status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08002763 Mutex::Autolock _l(mStateLock);
2764
Robert Carr1f0a16a2016-10-24 16:27:39 -07002765 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002766 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002767 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002768 if (topLevelOnly) {
2769 return NO_ERROR;
2770 }
2771
Chia-I Wu98f1c102017-05-30 14:54:08 -07002772 sp<Layer> ancestor = p;
2773 while (ancestor->getParent() != nullptr) {
2774 ancestor = ancestor->getParent();
2775 }
2776 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
2777 ALOGE("removeLayer called with a layer whose parent has been removed");
2778 return NAME_NOT_FOUND;
2779 }
Chia-I Wufae51c42017-06-15 12:53:59 -07002780
2781 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07002782 } else {
2783 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07002784 }
2785
Robert Carr136e2f62017-02-08 17:54:29 -08002786 // As a matter of normal operation, the LayerCleaner will produce a second
2787 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
2788 // so we will succeed in promoting it, but it's already been removed
2789 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
2790 // otherwise something has gone wrong and we are leaking the layer.
2791 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2793 layer->getName().string(),
2794 (p != nullptr) ? p->getName().string() : "no-parent");
2795 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08002796 } else if (index < 0) {
2797 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002798 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002799
Chia-I Wuc6657022017-08-15 11:18:17 -07002800 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002801 mLayersPendingRemoval.add(layer);
2802 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07002803 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002804 setTransactionFlags(eTransactionNeeded);
2805 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806}
2807
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002808uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002809 return android_atomic_release_load(&mTransactionFlags);
2810}
2811
Mathias Agopian3f844832013-08-07 21:24:32 -07002812uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2814}
2815
Mathias Agopian3f844832013-08-07 21:24:32 -07002816uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2818 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002819 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 }
2821 return old;
2822}
2823
Mathias Agopian8b33f032012-07-24 20:43:54 -07002824void SurfaceFlinger::setTransactionState(
2825 const Vector<ComposerState>& state,
2826 const Vector<DisplayState>& displays,
2827 uint32_t flags)
2828{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002829 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002830 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002831 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002832
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002833 if (flags & eAnimation) {
2834 // For window updates that are part of an animation we must wait for
2835 // previous animation "frames" to be handled.
2836 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002837 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002838 if (CC_UNLIKELY(err != NO_ERROR)) {
2839 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002840 // caller after a few seconds.
2841 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2842 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002843 mAnimTransactionPending = false;
2844 break;
2845 }
2846 }
2847 }
2848
Mathias Agopiane57f2922012-08-09 16:29:12 -07002849 size_t count = displays.size();
2850 for (size_t i=0 ; i<count ; i++) {
2851 const DisplayState& s(displays[i]);
2852 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002853 }
2854
Mathias Agopiane57f2922012-08-09 16:29:12 -07002855 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002856 for (size_t i=0 ; i<count ; i++) {
2857 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002858 // Here we need to check that the interface we're given is indeed
2859 // one of our own. A malicious client could give us a NULL
2860 // IInterface, or one of its own or even one of our own but a
2861 // different type. All these situations would cause us to crash.
2862 //
2863 // NOTE: it would be better to use RTTI as we could directly check
2864 // that we have a Client*. however, RTTI is disabled in Android.
2865 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002866 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002867 if (binder != NULL) {
Fabien Sanglard2ae83f42017-01-19 11:13:20 -08002868 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002869 sp<Client> client( static_cast<Client *>(s.client.get()) );
2870 transactionFlags |= setClientStateLocked(client, s.state);
2871 }
2872 }
2873 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002874 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002875
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002876 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2877 // anyway. This can be used as a flush mechanism for previous async transactions.
2878 // Empty animation transaction can be used to simulate back-pressure, so also force a
2879 // transaction for empty animation transactions.
2880 if (transactionFlags == 0 &&
2881 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002882 transactionFlags = eTransactionNeeded;
2883 }
2884
Mathias Agopian386aa982011-11-07 21:58:03 -08002885 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002886 if (mInterceptor.isEnabled()) {
2887 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2888 }
Irvel468051e2016-06-13 16:44:44 -07002889
Mathias Agopian386aa982011-11-07 21:58:03 -08002890 // this triggers the transaction
2891 setTransactionFlags(transactionFlags);
2892
2893 // if this is a synchronous transaction, wait for it to take effect
2894 // before returning.
2895 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002896 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002897 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002898 if (flags & eAnimation) {
2899 mAnimTransactionPending = true;
2900 }
2901 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002902 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2903 if (CC_UNLIKELY(err != NO_ERROR)) {
2904 // just in case something goes wrong in SF, return to the
2905 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002906 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2907 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002908 break;
2909 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002910 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911 }
2912}
2913
Mathias Agopiane57f2922012-08-09 16:29:12 -07002914uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2915{
Jesse Hall9a143922012-10-04 16:29:19 -07002916 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2917 if (dpyIdx < 0)
2918 return 0;
2919
Mathias Agopiane57f2922012-08-09 16:29:12 -07002920 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002921 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002922 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002923 const uint32_t what = s.what;
2924 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002925 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002926 disp.surface = s.surface;
2927 flags |= eDisplayTransactionNeeded;
2928 }
2929 }
2930 if (what & DisplayState::eLayerStackChanged) {
2931 if (disp.layerStack != s.layerStack) {
2932 disp.layerStack = s.layerStack;
2933 flags |= eDisplayTransactionNeeded;
2934 }
2935 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002936 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002937 if (disp.orientation != s.orientation) {
2938 disp.orientation = s.orientation;
2939 flags |= eDisplayTransactionNeeded;
2940 }
2941 if (disp.frame != s.frame) {
2942 disp.frame = s.frame;
2943 flags |= eDisplayTransactionNeeded;
2944 }
2945 if (disp.viewport != s.viewport) {
2946 disp.viewport = s.viewport;
2947 flags |= eDisplayTransactionNeeded;
2948 }
2949 }
Michael Lentine47e45402014-07-18 15:34:25 -07002950 if (what & DisplayState::eDisplaySizeChanged) {
2951 if (disp.width != s.width) {
2952 disp.width = s.width;
2953 flags |= eDisplayTransactionNeeded;
2954 }
2955 if (disp.height != s.height) {
2956 disp.height = s.height;
2957 flags |= eDisplayTransactionNeeded;
2958 }
2959 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002960 }
2961 return flags;
2962}
2963
2964uint32_t SurfaceFlinger::setClientStateLocked(
2965 const sp<Client>& client,
2966 const layer_state_t& s)
2967{
2968 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002969 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002970 if (layer != 0) {
2971 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002972 bool geometryAppliesWithResize =
2973 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002974 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002975 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002976 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002977 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002978 }
2979 if (what & layer_state_t::eLayerChanged) {
2980 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002981 const auto& p = layer->getParent();
2982 if (p == nullptr) {
2983 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2984 if (layer->setLayer(s.z) && idx >= 0) {
2985 mCurrentState.layersSortedByZ.removeAt(idx);
2986 mCurrentState.layersSortedByZ.add(layer);
2987 // we need traversal (state changed)
2988 // AND transaction (list changed)
2989 flags |= eTransactionNeeded|eTraversalNeeded;
2990 }
2991 } else {
2992 if (p->setChildLayer(layer, s.z)) {
2993 flags |= eTransactionNeeded|eTraversalNeeded;
2994 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002995 }
2996 }
Robert Carrdb66e622017-04-10 16:55:57 -07002997 if (what & layer_state_t::eRelativeLayerChanged) {
2998 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2999 flags |= eTransactionNeeded|eTraversalNeeded;
3000 }
3001 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003002 if (what & layer_state_t::eSizeChanged) {
3003 if (layer->setSize(s.w, s.h)) {
3004 flags |= eTraversalNeeded;
3005 }
3006 }
3007 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003009 flags |= eTraversalNeeded;
3010 }
3011 if (what & layer_state_t::eMatrixChanged) {
3012 if (layer->setMatrix(s.matrix))
3013 flags |= eTraversalNeeded;
3014 }
3015 if (what & layer_state_t::eTransparentRegionChanged) {
3016 if (layer->setTransparentRegionHint(s.transparentRegion))
3017 flags |= eTraversalNeeded;
3018 }
Dan Stoza23116082015-06-18 14:58:39 -07003019 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003020 if (layer->setFlags(s.flags, s.mask))
3021 flags |= eTraversalNeeded;
3022 }
3023 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07003024 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07003025 flags |= eTraversalNeeded;
3026 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003027 if (what & layer_state_t::eFinalCropChanged) {
Robert Carr8d5227b2017-03-16 15:41:03 -07003028 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
Pablo Ceballosacbe6782016-03-04 17:54:21 +00003029 flags |= eTraversalNeeded;
3030 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003031 if (what & layer_state_t::eLayerStackChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003032 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003033 // We only allow setting layer stacks for top level layers,
3034 // everything else inherits layer stack from its parent.
3035 if (layer->hasParent()) {
3036 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3037 layer->getName().string());
3038 } else if (idx < 0) {
3039 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3040 "that also does not appear in the top level layer list. Something"
3041 " has gone wrong.", layer->getName().string());
3042 } else if (layer->setLayerStack(s.layerStack)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003043 mCurrentState.layersSortedByZ.removeAt(idx);
3044 mCurrentState.layersSortedByZ.add(layer);
3045 // we need traversal (state changed)
3046 // AND transaction (list changed)
3047 flags |= eTransactionNeeded|eTraversalNeeded;
3048 }
3049 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003050 if (what & layer_state_t::eDeferTransaction) {
Robert Carr0d480722017-01-10 16:42:54 -08003051 if (s.barrierHandle != nullptr) {
3052 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3053 } else if (s.barrierGbp != nullptr) {
3054 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3055 if (authenticateSurfaceTextureLocked(gbp)) {
3056 const auto& otherLayer =
3057 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3058 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3059 } else {
3060 ALOGE("Attempt to defer transaction to to an"
3061 " unrecognized GraphicBufferProducer");
3062 }
3063 }
Dan Stoza7dde5992015-05-22 09:51:44 -07003064 // We don't trigger a traversal here because if no other state is
3065 // changed, we don't want this to cause any more work
3066 }
Robert Carr1db73f62016-12-21 12:58:51 -08003067 if (what & layer_state_t::eReparentChildren) {
3068 if (layer->reparentChildren(s.reparentHandle)) {
3069 flags |= eTransactionNeeded|eTraversalNeeded;
3070 }
3071 }
Robert Carr9524cb32017-02-13 11:32:32 -08003072 if (what & layer_state_t::eDetachChildren) {
3073 layer->detachChildren();
3074 }
Robert Carrc3574f72016-03-24 12:19:32 -07003075 if (what & layer_state_t::eOverrideScalingModeChanged) {
3076 layer->setOverrideScalingMode(s.overrideScalingMode);
3077 // 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 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003080 }
3081 return flags;
3082}
3083
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003084status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003085 const String8& name,
3086 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003087 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003088 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3089 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003091 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003092 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003093 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003094 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003095 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003096
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003097 status_t result = NO_ERROR;
3098
3099 sp<Layer> layer;
3100
Cody Northropbc755282017-03-31 12:00:08 -06003101 String8 uniqueName = getUniqueLayerName(name);
3102
Mathias Agopian3165cc22012-08-08 19:42:09 -07003103 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3104 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003105 result = createNormalLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003106 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003107 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07003109 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003110 result = createDimLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003111 uniqueName, w, h, flags,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003112 handle, gbp, &layer);
3113 break;
3114 default:
3115 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 break;
3117 }
3118
Dan Stoza7d89d062015-04-30 13:29:25 -07003119 if (result != NO_ERROR) {
3120 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003121 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003122
Chia-I Wuab0c3192017-08-01 11:29:00 -07003123 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3124 // TODO b/64227542
3125 if (windowType == 441731) {
3126 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3127 layer->setPrimaryDisplayOnly();
3128 }
3129
Albert Chaulk479c60c2017-01-27 14:21:34 -05003130 layer->setInfo(windowType, ownerUid);
3131
Robert Carr1f0a16a2016-10-24 16:27:39 -07003132 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003133 if (result != NO_ERROR) {
3134 return result;
3135 }
Irvelffc9efc2016-07-27 15:16:37 -07003136 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003137
3138 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003139 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140}
3141
Cody Northropbc755282017-03-31 12:00:08 -06003142String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3143{
3144 bool matchFound = true;
3145 uint32_t dupeCounter = 0;
3146
3147 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3148 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3149
3150 // Loop over layers until we're sure there is no matching name
3151 while (matchFound) {
3152 matchFound = false;
3153 mDrawingState.traverseInZOrder([&](Layer* layer) {
3154 if (layer->getName() == uniqueName) {
3155 matchFound = true;
3156 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3157 }
3158 });
3159 }
3160
3161 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3162
3163 return uniqueName;
3164}
3165
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003166status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3167 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3168 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169{
3170 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003171 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 case PIXEL_FORMAT_TRANSPARENT:
3173 case PIXEL_FORMAT_TRANSLUCENT:
3174 format = PIXEL_FORMAT_RGBA_8888;
3175 break;
3176 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003177 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 break;
3179 }
3180
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003181 *outLayer = new Layer(this, client, name, w, h, flags);
3182 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3183 if (err == NO_ERROR) {
3184 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003185 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003187
3188 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3189 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190}
3191
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003192status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3193 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3194 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003196 *outLayer = new LayerDim(this, client, name, w, h, flags);
3197 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07003198 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003199 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003200}
3201
Mathias Agopianac9fa422013-02-11 16:40:36 -08003202status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203{
Robert Carr9524cb32017-02-13 11:32:32 -08003204 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003205 status_t err = NO_ERROR;
3206 sp<Layer> l(client->getLayerUser(handle));
3207 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07003208 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003209 err = removeLayer(l);
3210 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3211 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003212 }
3213 return err;
3214}
3215
Mathias Agopian13127d82013-03-05 17:47:11 -08003216status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003217{
Mathias Agopian67106042013-03-14 19:18:13 -07003218 // called by ~LayerCleaner() when all references to the IBinder (handle)
3219 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003220 sp<Layer> l = layer.promote();
3221 if (l == nullptr) {
3222 // The layer has already been removed, carry on
3223 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003224 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003225 // If we have a parent, then we can continue to live as long as it does.
3226 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227}
3228
Mathias Agopianb60314a2012-04-10 22:09:54 -07003229// ---------------------------------------------------------------------------
3230
Andy McFadden13a082e2012-08-24 10:16:42 -07003231void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003232 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003233 Vector<ComposerState> state;
3234 Vector<DisplayState> displays;
3235 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003236 d.what = DisplayState::eDisplayProjectionChanged |
3237 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003238 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003239 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003240 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003241 d.frame.makeInvalid();
3242 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003243 d.width = 0;
3244 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003245 displays.add(d);
3246 setTransactionState(state, displays, 0);
Steven Thomasd7f49c52017-07-26 18:48:28 -07003247 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3248 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003249
Dan Stoza9e56aa02015-11-02 13:00:03 -08003250 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3251 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003252 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003253
Brian Andersond0010582017-03-07 13:20:31 -08003254 // Use phase of 0 since phase is not known.
3255 // Use latency of 0, which will snap to the ideal latency.
3256 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003257}
3258
3259void SurfaceFlinger::initializeDisplays() {
3260 class MessageScreenInitialized : public MessageBase {
3261 SurfaceFlinger* flinger;
3262 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003263 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003264 virtual bool handler() {
3265 flinger->onInitializeDisplays();
3266 return true;
3267 }
3268 };
3269 sp<MessageBase> msg = new MessageScreenInitialized(this);
3270 postMessageAsync(msg); // we may be called from main thread, use async message
3271}
3272
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003273void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasd7f49c52017-07-26 18:48:28 -07003274 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003275 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3276 this);
3277 int32_t type = hw->getDisplayType();
3278 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003279
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003280 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003281 return;
3282 }
3283
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003284 hw->setPowerMode(mode);
3285 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3286 ALOGW("Trying to set power mode for virtual display");
3287 return;
3288 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003289
Irvelffc9efc2016-07-27 15:16:37 -07003290 if (mInterceptor.isEnabled()) {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003291 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003292 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3293 if (idx < 0) {
3294 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3295 return;
3296 }
3297 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3298 }
3299
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003300 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003301 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003302 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003303 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3304 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003305 // FIXME: eventthread only knows about the main display right now
3306 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003307 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003308 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003310 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003311 mHasPoweredOff = true;
Steven Thomas6d8110b2017-08-31 18:24:21 -07003312 repaintEverythingLocked();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003313
3314 struct sched_param param = {0};
3315 param.sched_priority = 1;
3316 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3317 ALOGW("Couldn't set SCHED_FIFO on display on");
3318 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003319 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003320 // Turn off the display
3321 struct sched_param param = {0};
3322 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3323 ALOGW("Couldn't set SCHED_OTHER on display off");
3324 }
3325
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003326 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003327 disableHardwareVsync(true); // also cancels any in-progress resync
3328
Mathias Agopiancde87a32012-09-13 14:09:01 -07003329 // FIXME: eventthread only knows about the main display right now
3330 mEventThread->onScreenReleased();
3331 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003332
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003333 getHwComposer().setPowerMode(type, mode);
3334 mVisibleRegionsDirty = true;
3335 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003336 } else if (mode == HWC_POWER_MODE_DOZE ||
3337 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003338 // Update display while dozing
3339 getHwComposer().setPowerMode(type, mode);
3340 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3341 // FIXME: eventthread only knows about the main display right now
3342 mEventThread->onScreenAcquired();
3343 resyncToHardwareVsync(true);
3344 }
3345 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3346 // Leave display going to doze
3347 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3348 disableHardwareVsync(true); // also cancels any in-progress resync
3349 // FIXME: eventthread only knows about the main display right now
3350 mEventThread->onScreenReleased();
3351 }
3352 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003353 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003354 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003355 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003356 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003357}
3358
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003359void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3360 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003361 SurfaceFlinger& mFlinger;
3362 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003363 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003364 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003365 MessageSetPowerMode(SurfaceFlinger& flinger,
3366 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3367 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003368 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003369 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003370 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003371 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003372 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003373 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003374 ALOGW("Attempt to set power mode = %d for virtual display",
3375 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003376 } else {
Steven Thomasd7f49c52017-07-26 18:48:28 -07003377 mFlinger.setPowerModeInternal(
3378 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003379 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003380 return true;
3381 }
3382 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003383 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003384 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003385}
3386
3387// ---------------------------------------------------------------------------
3388
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003389status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3390{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003391 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003392
Mathias Agopianbd115332013-04-18 16:41:04 -07003393 IPCThreadState* ipc = IPCThreadState::self();
3394 const int pid = ipc->getCallingPid();
3395 const int uid = ipc->getCallingUid();
3396 if ((uid != AID_SHELL) &&
3397 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003398 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003399 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003400 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003401 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003402 // (this would indicate SF is stuck, but we want to be able to
3403 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003404 status_t err = mStateLock.timedLock(s2ns(1));
3405 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003406 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003407 result.appendFormat(
3408 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3409 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003410 }
3411
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003412 bool dumpAll = true;
3413 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003414 size_t numArgs = args.size();
3415 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003416 if ((index < numArgs) &&
3417 (args[index] == String16("--list"))) {
3418 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003419 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003420 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003421 }
3422
3423 if ((index < numArgs) &&
3424 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003425 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003426 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003427 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003428 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003429
3430 if ((index < numArgs) &&
3431 (args[index] == String16("--latency-clear"))) {
3432 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003433 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003434 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003435 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003436
3437 if ((index < numArgs) &&
3438 (args[index] == String16("--dispsync"))) {
3439 index++;
3440 mPrimaryDispSync.dump(result);
3441 dumpAll = false;
3442 }
Dan Stozab90cf072015-03-05 11:05:59 -08003443
3444 if ((index < numArgs) &&
3445 (args[index] == String16("--static-screen"))) {
3446 index++;
3447 dumpStaticScreenStats(result);
3448 dumpAll = false;
3449 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003450
3451 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003452 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003453 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003454 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003455 dumpAll = false;
3456 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003457
3458 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3459 index++;
3460 dumpWideColorInfo(result);
3461 dumpAll = false;
3462 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003463 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07003464
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003465 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003466 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003467 }
3468
Mathias Agopian9795c422009-08-26 16:36:26 -07003469 if (locked) {
3470 mStateLock.unlock();
3471 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472 }
3473 write(fd, result.string(), result.size());
3474 return NO_ERROR;
3475}
3476
Dan Stozac7014012014-02-14 15:03:43 -08003477void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3478 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003479{
Robert Carr2047fae2016-11-28 14:09:09 -08003480 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003481 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08003482 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003483}
3484
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003485void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02003486 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003487{
3488 String8 name;
3489 if (index < args.size()) {
3490 name = String8(args[index]);
3491 index++;
3492 }
3493
Dan Stoza9e56aa02015-11-02 13:00:03 -08003494 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3495 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08003496 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003497
3498 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003499 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003500 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08003501 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003502 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003503 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003504 }
Robert Carr2047fae2016-11-28 14:09:09 -08003505 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003506 }
3507}
3508
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003509void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08003510 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003511{
3512 String8 name;
3513 if (index < args.size()) {
3514 name = String8(args[index]);
3515 index++;
3516 }
3517
Robert Carr2047fae2016-11-28 14:09:09 -08003518 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003519 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07003520 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003521 }
Robert Carr2047fae2016-11-28 14:09:09 -08003522 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003523
Svetoslavd85084b2014-03-20 10:28:31 -07003524 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003525}
3526
Jamie Gennis6547ff42013-07-16 20:12:42 -07003527// This should only be called from the main thread. Otherwise it would need
3528// the lock and should use mCurrentState rather than mDrawingState.
3529void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003530 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003531 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003532 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003533
3534 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3535}
3536
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003537void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07003538{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003539 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003540 result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3541
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003542 if (isLayerTripleBufferingDisabled())
3543 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003544
3545 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07003546 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08003547 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08003548 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08003549 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3550 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003551 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003552}
3553
Dan Stozab90cf072015-03-05 11:05:59 -08003554void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3555{
3556 result.appendFormat("Static screen stats:\n");
3557 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3558 float bucketTimeSec = mFrameBuckets[b] / 1e9;
3559 float percent = 100.0f *
3560 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3561 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
3562 b + 1, bucketTimeSec, percent);
3563 }
3564 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3565 float percent = 100.0f *
3566 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3567 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
3568 NUM_BUCKETS - 1, bucketTimeSec, percent);
3569}
3570
Dan Stozae77c7662016-05-13 11:37:28 -07003571void SurfaceFlinger::recordBufferingStats(const char* layerName,
3572 std::vector<OccupancyTracker::Segment>&& history) {
3573 Mutex::Autolock lock(mBufferingStatsMutex);
3574 auto& stats = mBufferingStats[layerName];
3575 for (const auto& segment : history) {
3576 if (!segment.usedThirdBuffer) {
3577 stats.twoBufferTime += segment.totalTime;
3578 }
3579 if (segment.occupancyAverage < 1.0f) {
3580 stats.doubleBufferedTime += segment.totalTime;
3581 } else if (segment.occupancyAverage < 2.0f) {
3582 stats.tripleBufferedTime += segment.totalTime;
3583 }
3584 ++stats.numSegments;
3585 stats.totalTime += segment.totalTime;
3586 }
3587}
3588
Brian Andersond6927fb2016-07-23 23:37:30 -07003589void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3590 result.appendFormat("Layer frame timestamps:\n");
3591
3592 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3593 const size_t count = currentLayers.size();
3594 for (size_t i=0 ; i<count ; i++) {
3595 currentLayers[i]->dumpFrameEvents(result);
3596 }
3597}
3598
Dan Stozae77c7662016-05-13 11:37:28 -07003599void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3600 result.append("Buffering stats:\n");
3601 result.append(" [Layer name] <Active time> <Two buffer> "
3602 "<Double buffered> <Triple buffered>\n");
3603 Mutex::Autolock lock(mBufferingStatsMutex);
3604 typedef std::tuple<std::string, float, float, float> BufferTuple;
3605 std::map<float, BufferTuple, std::greater<float>> sorted;
3606 for (const auto& statsPair : mBufferingStats) {
3607 const char* name = statsPair.first.c_str();
3608 const BufferingStats& stats = statsPair.second;
3609 if (stats.numSegments == 0) {
3610 continue;
3611 }
3612 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3613 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3614 stats.totalTime;
3615 float doubleBufferRatio = static_cast<float>(
3616 stats.doubleBufferedTime) / stats.totalTime;
3617 float tripleBufferRatio = static_cast<float>(
3618 stats.tripleBufferedTime) / stats.totalTime;
3619 sorted.insert({activeTime, {name, twoBufferRatio,
3620 doubleBufferRatio, tripleBufferRatio}});
3621 }
3622 for (const auto& sortedPair : sorted) {
3623 float activeTime = sortedPair.first;
3624 const BufferTuple& values = sortedPair.second;
3625 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3626 std::get<0>(values).c_str(), activeTime,
3627 std::get<1>(values), std::get<2>(values),
3628 std::get<3>(values));
3629 }
3630 result.append("\n");
3631}
3632
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003633void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3634 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3635
3636 // TODO: print out if wide-color mode is active or not
3637
3638 for (size_t d = 0; d < mDisplays.size(); d++) {
3639 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3640 int32_t hwcId = displayDevice->getHwcDisplayId();
3641 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3642 continue;
3643 }
3644
3645 result.appendFormat("Display %d color modes:\n", hwcId);
3646 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3647 for (auto&& mode : modes) {
3648 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3649 }
3650
3651 android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3652 result.appendFormat(" Current color mode: %s (%d)\n",
3653 decodeColorMode(currentMode).c_str(), currentMode);
3654 }
3655 result.append("\n");
3656}
3657
Mathias Agopian74d211a2013-04-22 16:55:35 +02003658void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3659 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003660{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003661 bool colorize = false;
3662 if (index < args.size()
3663 && (args[index] == String16("--color"))) {
3664 colorize = true;
3665 index++;
3666 }
3667
3668 Colorizer colorizer(colorize);
3669
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003670 // figure out if we're stuck somewhere
3671 const nsecs_t now = systemTime();
3672 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3673 const nsecs_t inTransaction(mDebugInTransaction);
3674 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3675 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3676
3677 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003678 * Dump library configuration.
3679 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003680
3681 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003682 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003683 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003684 appendSfConfigString(result);
3685 appendUiConfigString(result);
3686 appendGuiConfigString(result);
3687 result.append("\n");
3688
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003689 result.append("\nWide-Color information:\n");
3690 dumpWideColorInfo(result);
3691
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003692 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003693 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003694 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003695 result.append(SyncFeatures::getInstance().toString());
3696 result.append("\n");
3697
Dan Stoza9e56aa02015-11-02 13:00:03 -08003698 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3699
Andy McFadden41d67d72014-04-25 16:58:34 -07003700 colorizer.bold(result);
3701 result.append("DispSync configuration: ");
3702 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003703 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003704 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003705 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003706 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003707 result.append("\n");
3708
Dan Stozab90cf072015-03-05 11:05:59 -08003709 // Dump static screen stats
3710 result.append("\n");
3711 dumpStaticScreenStats(result);
3712 result.append("\n");
3713
Dan Stozae77c7662016-05-13 11:37:28 -07003714 dumpBufferingStats(result);
3715
Andy McFadden4803b742012-09-24 19:07:20 -07003716 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003717 * Dump the visible layer list
3718 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003719 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003720 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003721 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003722 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003723 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003724 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003725
3726 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003727 * Dump Display state
3728 */
3729
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003730 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003731 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003732 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003733 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3734 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003735 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003736 }
3737
3738 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003739 * Dump SurfaceFlinger global state
3740 */
3741
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003742 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003743 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003744 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003745
Mathias Agopian888c8222012-08-04 21:10:38 -07003746 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003747 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07003748
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003749 colorizer.bold(result);
3750 result.appendFormat("EGL implementation : %s\n",
3751 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3752 colorizer.reset(result);
3753 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003754 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003755
Mathias Agopian875d8e12013-06-07 15:35:48 -07003756 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003757
Mathias Agopian42977342012-08-05 00:40:46 -07003758 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3760 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003761 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003762 " last eglSwapBuffers() time: %f us\n"
3763 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003764 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003765 " refresh-rate : %f fps\n"
3766 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003767 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003768 " gpu_to_cpu_unsupported : %d\n"
3769 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003770 mLastSwapBufferTime/1000.0,
3771 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003772 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003773 1e9 / activeConfig->getVsyncPeriod(),
3774 activeConfig->getDpiX(),
3775 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003776 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003777
Mathias Agopian74d211a2013-04-22 16:55:35 +02003778 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003779 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003780
Mathias Agopian74d211a2013-04-22 16:55:35 +02003781 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003782 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003783
3784 /*
3785 * VSYNC state
3786 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003787 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003788 result.append("\n");
3789
3790 /*
3791 * HWC layer minidump
3792 */
3793 for (size_t d = 0; d < mDisplays.size(); d++) {
3794 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3795 int32_t hwcId = displayDevice->getHwcDisplayId();
3796 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3797 continue;
3798 }
3799
3800 result.appendFormat("Display %d HWC layers:\n", hwcId);
3801 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003802 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07003803 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003804 });
Dan Stozae22aec72016-08-01 13:20:59 -07003805 result.append("\n");
3806 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003807
3808 /*
3809 * Dump HWComposer state
3810 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003811 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003812 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003813 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003814 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003815 result.appendFormat(" h/w composer %s\n",
3816 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003817 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003818
3819 /*
3820 * Dump gralloc state
3821 */
3822 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3823 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07003824
3825 /*
3826 * Dump VrFlinger state if in use.
3827 */
3828 if (mVrFlingerRequestsDisplay && mVrFlinger) {
3829 result.append("VrFlinger state:\n");
3830 result.append(mVrFlinger->Dump().c_str());
3831 result.append("\n");
3832 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003833}
3834
Mathias Agopian13127d82013-03-05 17:47:11 -08003835const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003836SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003837 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003838 wp<IBinder> dpy;
3839 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3840 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3841 dpy = mDisplays.keyAt(i);
3842 break;
3843 }
3844 }
3845 if (dpy == NULL) {
3846 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3847 // Just use the primary display so we have something to return
3848 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3849 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003850 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003851}
3852
Keun young Park63f165f2012-08-31 10:53:36 -07003853bool SurfaceFlinger::startDdmConnection()
3854{
3855 void* libddmconnection_dso =
3856 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3857 if (!libddmconnection_dso) {
3858 return false;
3859 }
3860 void (*DdmConnection_start)(const char* name);
3861 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003862 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003863 if (!DdmConnection_start) {
3864 dlclose(libddmconnection_dso);
3865 return false;
3866 }
3867 (*DdmConnection_start)(getServiceName());
3868 return true;
3869}
3870
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003871status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 switch (code) {
3873 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003874 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003875 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003876 case CLEAR_ANIMATION_FRAME_STATS:
3877 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003879 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880 {
3881 // codes that require permission check
3882 IPCThreadState* ipc = IPCThreadState::self();
3883 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003884 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003885 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003886 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003887 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003888 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003889 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003890 break;
3891 }
Robert Carr1db73f62016-12-21 12:58:51 -08003892 /*
3893 * Calling setTransactionState is safe, because you need to have been
3894 * granted a reference to Client* and Handle* to do anything with it.
3895 *
3896 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3897 */
3898 case SET_TRANSACTION_STATE:
3899 case CREATE_SCOPED_CONNECTION:
3900 {
3901 return OK;
3902 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003903 case CAPTURE_SCREEN:
3904 {
3905 // codes that require permission check
3906 IPCThreadState* ipc = IPCThreadState::self();
3907 const int pid = ipc->getCallingPid();
3908 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003909 if ((uid != AID_GRAPHICS) &&
3910 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003911 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003912 return PERMISSION_DENIED;
3913 }
3914 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003915 }
3916 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003917 return OK;
3918}
3919
3920status_t SurfaceFlinger::onTransact(
3921 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3922{
3923 status_t credentialCheck = CheckTransactCodeCredentials(code);
3924 if (credentialCheck != OK) {
3925 return credentialCheck;
3926 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003927
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3929 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003930 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07003931 IPCThreadState* ipc = IPCThreadState::self();
3932 const int uid = ipc->getCallingUid();
3933 if (CC_UNLIKELY(uid != AID_SYSTEM
3934 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003935 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003936 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003937 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003938 return PERMISSION_DENIED;
3939 }
3940 int n;
3941 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003942 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003943 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003944 return NO_ERROR;
3945 case 1002: // SHOW_UPDATES
3946 n = data.readInt32();
3947 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003948 invalidateHwcGeometry();
3949 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003952 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003953 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003954 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003955 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07003956 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003957 setTransactionFlags(
3958 eTransactionNeeded|
3959 eDisplayTransactionNeeded|
3960 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003961 return NO_ERROR;
3962 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003963 case 1006:{ // send empty update
3964 signalRefresh();
3965 return NO_ERROR;
3966 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003967 case 1008: // toggle use of hw composer
3968 n = data.readInt32();
3969 mDebugDisableHWC = n ? 1 : 0;
3970 invalidateHwcGeometry();
3971 repaintEverything();
3972 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003973 case 1009: // toggle use of transform hint
3974 n = data.readInt32();
3975 mDebugDisableTransformHint = n ? 1 : 0;
3976 invalidateHwcGeometry();
3977 repaintEverything();
3978 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003979 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003980 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003981 reply->writeInt32(0);
3982 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003983 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003984 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003985 return NO_ERROR;
3986 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00003987 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07003988 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003989 return NO_ERROR;
3990 }
3991 case 1014: {
3992 // daltonize
3993 n = data.readInt32();
3994 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003995 case 1:
3996 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3997 break;
3998 case 2:
3999 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4000 break;
4001 case 3:
4002 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4003 break;
4004 default:
4005 mDaltonizer.setType(ColorBlindnessType::None);
4006 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004007 }
4008 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004009 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004010 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004011 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004012 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07004013 invalidateHwcGeometry();
4014 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004015 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004016 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004017 case 1015: {
4018 // apply a color matrix
4019 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004020 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004021 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004022 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004023 for (size_t j = 0; j < 4; j++) {
4024 mColorMatrix[i][j] = data.readFloat();
4025 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004026 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004027 } else {
4028 mColorMatrix = mat4();
4029 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004030
4031 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4032 // the division by w in the fragment shader
4033 float4 lastRow(transpose(mColorMatrix)[3]);
4034 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4035 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4036 }
4037
Alan Viverette9c5a3332013-09-12 20:04:35 -07004038 invalidateHwcGeometry();
4039 repaintEverything();
4040 return NO_ERROR;
4041 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004042 // This is an experimental interface
4043 // Needs to be shifted to proper binder interface when we productize
4044 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004045 n = data.readInt32();
4046 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004047 return NO_ERROR;
4048 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004049 case 1017: {
4050 n = data.readInt32();
4051 mForceFullDamage = static_cast<bool>(n);
4052 return NO_ERROR;
4053 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004054 case 1018: { // Modify Choreographer's phase offset
4055 n = data.readInt32();
4056 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4057 return NO_ERROR;
4058 }
4059 case 1019: { // Modify SurfaceFlinger's phase offset
4060 n = data.readInt32();
4061 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4062 return NO_ERROR;
4063 }
Irvel468051e2016-06-13 16:44:44 -07004064 case 1020: { // Layer updates interceptor
4065 n = data.readInt32();
4066 if (n) {
4067 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07004068 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004069 }
4070 else{
4071 ALOGV("Interceptor disabled");
4072 mInterceptor.disable();
4073 }
4074 return NO_ERROR;
4075 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004076 case 1021: { // Disable HWC virtual displays
4077 n = data.readInt32();
4078 mUseHwcVirtualDisplays = !n;
4079 return NO_ERROR;
4080 }
Romain Guy0147a172017-06-01 13:53:56 -07004081 case 1022: { // Set saturation boost
4082 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4083
4084 invalidateHwcGeometry();
4085 repaintEverything();
4086 return NO_ERROR;
4087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088 }
4089 }
4090 return err;
4091}
4092
Steven Thomas6d8110b2017-08-31 18:24:21 -07004093void SurfaceFlinger::repaintEverythingLocked() {
Mathias Agopian87baae12012-07-31 12:38:26 -07004094 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08004095 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07004096}
4097
Steven Thomas6d8110b2017-08-31 18:24:21 -07004098void SurfaceFlinger::repaintEverything() {
4099 ConditionalLock _l(mStateLock,
4100 std::this_thread::get_id() != mMainThreadId);
4101 repaintEverythingLocked();
4102}
4103
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004104// Checks that the requested width and height are valid and updates them to the display dimensions
4105// if they are set to 0
4106static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4107 Transform::orientation_flags rotation,
4108 uint32_t* requestedWidth, uint32_t* requestedHeight) {
4109 // get screen geometry
4110 uint32_t displayWidth = displayDevice->getWidth();
4111 uint32_t displayHeight = displayDevice->getHeight();
Mathias Agopian9daa5c92010-10-12 16:05:48 -07004112
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004113 if (rotation & Transform::ROT_90) {
4114 std::swap(displayWidth, displayHeight);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004115 }
4116
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004117 if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4118 ALOGE("size mismatch (%d, %d) > (%d, %d)",
4119 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4120 return BAD_VALUE;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004121 }
4122
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004123 if (*requestedWidth == 0) {
4124 *requestedWidth = displayWidth;
4125 }
4126 if (*requestedHeight == 0) {
4127 *requestedHeight = displayHeight;
4128 }
4129
4130 return NO_ERROR;
4131}
4132
4133// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4134class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004135public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004136 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4137 ~WindowDisconnector() {
4138 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004139 }
4140
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004141private:
4142 ANativeWindow* mWindow;
4143 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004144};
4145
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004146static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4147 uint32_t requestedHeight, bool hasWideColorDisplay,
4148 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4149 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4150 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4151
4152 int err = 0;
4153 err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4154 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4155 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4156 err |= native_window_set_usage(window, usage);
4157
4158 if (hasWideColorDisplay) {
4159 err |= native_window_set_buffers_data_space(window,
4160 renderEngineUsesWideColor
4161 ? HAL_DATASPACE_DISPLAY_P3
4162 : HAL_DATASPACE_V0_SRGB);
4163 }
4164
4165 if (err != NO_ERROR) {
4166 return BAD_VALUE;
4167 }
4168
4169 /* TODO: Once we have the sync framework everywhere this can use
4170 * server-side waits on the fence that dequeueBuffer returns.
4171 */
4172 err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4173 if (err != NO_ERROR) {
4174 return err;
4175 }
4176
4177 return NO_ERROR;
4178}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004179
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004180status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4181 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07004182 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004183 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004184 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004185 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004186
4187 if (CC_UNLIKELY(display == 0))
4188 return BAD_VALUE;
4189
4190 if (CC_UNLIKELY(producer == 0))
4191 return BAD_VALUE;
4192
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004193 // if we have secure windows on this display, never allow the screen capture
4194 // unless the producer interface is local (i.e.: we can take a screenshot for
4195 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004196 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07004197
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004198 // Convert to surfaceflinger's internal rotation type.
4199 Transform::orientation_flags rotationFlags;
4200 switch (rotation) {
4201 case ISurfaceComposer::eRotateNone:
4202 rotationFlags = Transform::ROT_0;
4203 break;
4204 case ISurfaceComposer::eRotate90:
4205 rotationFlags = Transform::ROT_90;
4206 break;
4207 case ISurfaceComposer::eRotate180:
4208 rotationFlags = Transform::ROT_180;
4209 break;
4210 case ISurfaceComposer::eRotate270:
4211 rotationFlags = Transform::ROT_270;
4212 break;
4213 default:
4214 rotationFlags = Transform::ROT_0;
4215 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4216 break;
4217 }
4218
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004219 { // Autolock scope
4220 Mutex::Autolock lock(mStateLock);
4221 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4222 updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004223 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004224
4225 // create a surface (because we're a producer, and we need to
4226 // dequeue/queue a buffer)
4227 sp<Surface> surface = new Surface(producer, false);
4228
4229 // Put the screenshot Surface into async mode so that
4230 // Layer::headFenceHasSignaled will always return true and we'll latch the
4231 // first buffer regardless of whether or not its acquire fence has
4232 // signaled. This is needed to avoid a race condition in the rotation
4233 // animation. See b/30209608
4234 surface->setAsyncMode(true);
4235
4236 ANativeWindow* window = surface.get();
4237
4238 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4239 if (result != NO_ERROR) {
4240 return result;
4241 }
4242 WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4243
4244 ANativeWindowBuffer* buffer = nullptr;
4245 result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4246 getRenderEngine().usesWideColor(), &buffer);
4247 if (result != NO_ERROR) {
4248 return result;
4249 }
4250
4251 // This mutex protects syncFd and captureResult for communication of the return values from the
4252 // main thread back to this Binder thread
4253 std::mutex captureMutex;
4254 std::condition_variable captureCondition;
4255 std::unique_lock<std::mutex> captureLock(captureMutex);
4256 int syncFd = -1;
4257 std::optional<status_t> captureResult;
4258
4259 sp<LambdaMessage> message = new LambdaMessage([&]() {
4260 // If there is a refresh pending, bug out early and tell the binder thread to try again
4261 // after the refresh.
4262 if (mRefreshPending) {
4263 ATRACE_NAME("Skipping screenshot for now");
4264 std::unique_lock<std::mutex> captureLock(captureMutex);
4265 captureResult = std::make_optional<status_t>(EAGAIN);
4266 captureCondition.notify_one();
4267 return;
4268 }
4269
4270 status_t result = NO_ERROR;
4271 int fd = -1;
4272 {
4273 Mutex::Autolock _l(mStateLock);
4274 sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4275 result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4276 minLayerZ, maxLayerZ, useIdentityTransform,
4277 rotationFlags, isLocalScreenshot, &fd);
4278 }
4279
4280 {
4281 std::unique_lock<std::mutex> captureLock(captureMutex);
4282 syncFd = fd;
4283 captureResult = std::make_optional<status_t>(result);
4284 captureCondition.notify_one();
4285 }
4286 });
4287
4288 result = postMessageAsync(message);
4289 if (result == NO_ERROR) {
4290 captureCondition.wait(captureLock, [&]() { return captureResult; });
4291 while (*captureResult == EAGAIN) {
4292 captureResult.reset();
4293 result = postMessageAsync(message);
4294 if (result != NO_ERROR) {
4295 return result;
4296 }
4297 captureCondition.wait(captureLock, [&]() { return captureResult; });
4298 }
4299 result = *captureResult;
4300 }
4301
4302 if (result == NO_ERROR) {
4303 // queueBuffer takes ownership of syncFd
4304 result = window->queueBuffer(window, buffer, syncFd);
4305 }
4306
4307 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004308}
4309
Mathias Agopian180f10d2013-04-10 22:55:41 -07004310
4311void SurfaceFlinger::renderScreenImplLocked(
4312 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07004313 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08004314 int32_t minLayerZ, int32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004315 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07004316{
4317 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07004318 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07004319
4320 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08004321 const int32_t hw_w = hw->getWidth();
4322 const int32_t hw_h = hw->getHeight();
4323 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07004324 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004325
Dan Stozac1879002014-05-22 15:59:05 -07004326 // if a default or invalid sourceCrop is passed in, set reasonable values
4327 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4328 !sourceCrop.isValid()) {
4329 sourceCrop.setLeftTop(Point(0, 0));
4330 sourceCrop.setRightBottom(Point(hw_w, hw_h));
4331 }
4332
4333 // ensure that sourceCrop is inside screen
4334 if (sourceCrop.left < 0) {
4335 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4336 }
Dan Stozabe31f442014-06-11 11:20:54 -07004337 if (sourceCrop.right > hw_w) {
4338 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07004339 }
4340 if (sourceCrop.top < 0) {
4341 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4342 }
Dan Stozabe31f442014-06-11 11:20:54 -07004343 if (sourceCrop.bottom > hw_h) {
4344 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07004345 }
4346
Romain Guy88d37dd2017-05-26 17:57:05 -07004347#ifdef USE_HWC2
4348 engine.setWideColor(hw->getWideColorSupport());
4349 engine.setColorMode(hw->getActiveColorMode());
4350#endif
4351
Mathias Agopian180f10d2013-04-10 22:55:41 -07004352 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07004353 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004354
4355 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07004356 engine.setViewportAndProjection(
4357 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07004358 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004359
4360 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07004361 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07004362
Robert Carr1f0a16a2016-10-24 16:27:39 -07004363 // We loop through the first level of layers without traversing,
4364 // as we need to interpret min/max layer Z in the top level Z space.
4365 for (const auto& layer : mDrawingState.layersSortedByZ) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07004366 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004367 continue;
Mathias Agopian180f10d2013-04-10 22:55:41 -07004368 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07004369 const Layer::State& state(layer->getDrawingState());
4370 if (state.z < minLayerZ || state.z > maxLayerZ) {
4371 continue;
4372 }
Dan Stoza412903f2017-04-27 13:42:17 -07004373 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004374 if (!layer->isVisible()) {
4375 return;
4376 }
4377 if (filtering) layer->setFiltering(true);
4378 layer->draw(hw, useIdentityTransform);
4379 if (filtering) layer->setFiltering(false);
4380 });
4381 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004382
Mathias Agopian931bda12013-08-28 18:11:46 -07004383 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07004384}
4385
Dan Stozaabcda352017-06-01 14:37:39 -07004386// A simple RAII class that holds an EGLImage and destroys it either:
4387// a) When the destroy() method is called
4388// b) When the object goes out of scope
4389class ImageHolder {
4390public:
4391 ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4392 ~ImageHolder() { destroy(); }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004393
Dan Stozaabcda352017-06-01 14:37:39 -07004394 void destroy() {
4395 if (mImage != EGL_NO_IMAGE_KHR) {
4396 eglDestroyImageKHR(mDisplay, mImage);
4397 mImage = EGL_NO_IMAGE_KHR;
4398 }
4399 }
4400
4401private:
4402 const EGLDisplay mDisplay;
4403 EGLImageKHR mImage;
4404};
4405
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004406status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4407 ANativeWindowBuffer* buffer, Rect sourceCrop,
4408 uint32_t reqWidth, uint32_t reqHeight,
4409 int32_t minLayerZ, int32_t maxLayerZ,
4410 bool useIdentityTransform,
4411 Transform::orientation_flags rotation,
4412 bool isLocalScreenshot, int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004413 ATRACE_CALL();
4414
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004415 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004416 for (const auto& layer : mDrawingState.layersSortedByZ) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004417 const Layer::State& state(layer->getDrawingState());
Chia-I Wufc0b9112017-08-07 15:27:49 -07004418 if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
Robert Carr1f0a16a2016-10-24 16:27:39 -07004419 (state.z < minLayerZ || state.z > maxLayerZ)) {
4420 continue;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004421 }
Dan Stoza412903f2017-04-27 13:42:17 -07004422 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004423 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4424 layer->isSecure());
4425 });
4426 }
Pablo Ceballosb5b35632016-02-23 11:18:51 -08004427
4428 if (!isLocalScreenshot && secureLayerIsVisible) {
4429 ALOGW("FB is protected: PERMISSION_DENIED");
4430 return PERMISSION_DENIED;
4431 }
4432
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004433 int syncFd = -1;
4434 // create an EGLImage from the buffer so we can later
4435 // turn it into a texture
4436 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4437 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4438 if (image == EGL_NO_IMAGE_KHR) {
4439 return BAD_VALUE;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02004440 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07004441
Dan Stozaabcda352017-06-01 14:37:39 -07004442 // This will automatically destroy the image if we return before calling its destroy method
4443 ImageHolder imageHolder(mEGLDisplay, image);
4444
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004445 // this binds the given EGLImage as a framebuffer for the
4446 // duration of this scope.
4447 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
Dan Stozaabcda352017-06-01 14:37:39 -07004448 if (imageBond.getStatus() != NO_ERROR) {
4449 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07004450 return INVALID_OPERATION;
4451 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004452
Dan Stozaabcda352017-06-01 14:37:39 -07004453 // this will in fact render into our dequeued buffer
4454 // via an FBO, which means we didn't have to create
4455 // an EGLSurface and therefore we're not
4456 // dependent on the context's EGLConfig.
4457 renderScreenImplLocked(
4458 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4459 useIdentityTransform, rotation);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004460
Dan Stozaabcda352017-06-01 14:37:39 -07004461 // Attempt to create a sync khr object that can produce a sync point. If that
4462 // isn't available, create a non-dupable sync object in the fallback path and
4463 // wait on it directly.
4464 EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4465 if (!DEBUG_SCREENSHOTS) {
4466 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4467 // native fence fd will not be populated until flush() is done.
4468 getRenderEngine().flush();
4469 }
4470
4471 if (sync != EGL_NO_SYNC_KHR) {
4472 // get the sync fd
4473 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4474 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4475 ALOGW("captureScreen: failed to dup sync khr object");
4476 syncFd = -1;
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004477 }
Dan Stozaabcda352017-06-01 14:37:39 -07004478 eglDestroySyncKHR(mEGLDisplay, sync);
4479 } else {
4480 // fallback path
4481 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004482 if (sync != EGL_NO_SYNC_KHR) {
Dan Stozaabcda352017-06-01 14:37:39 -07004483 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4484 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4485 EGLint eglErr = eglGetError();
4486 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4487 ALOGW("captureScreen: fence wait timed out");
4488 } else {
4489 ALOGW_IF(eglErr != EGL_SUCCESS,
4490 "captureScreen: error waiting on EGL fence: %#x", eglErr);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004491 }
4492 eglDestroySyncKHR(mEGLDisplay, sync);
4493 } else {
Dan Stozaabcda352017-06-01 14:37:39 -07004494 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004495 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004496 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004497 *outSyncFd = syncFd;
Dan Stozaabcda352017-06-01 14:37:39 -07004498
4499 if (DEBUG_SCREENSHOTS) {
4500 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4501 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4502 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4503 hw, minLayerZ, maxLayerZ);
4504 delete [] pixels;
4505 }
4506
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004507 // destroy our image
Dan Stozaabcda352017-06-01 14:37:39 -07004508 imageHolder.destroy();
Dan Stozaa9b1aa02017-06-01 14:16:23 -07004509
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004510 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07004511}
4512
Mathias Agopiand5556842013-09-19 17:08:37 -07004513void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08004514 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004515 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07004516 for (size_t y=0 ; y<h ; y++) {
4517 uint32_t const * p = (uint32_t const *)vaddr + y*s;
4518 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004519 if (p[x] != 0xFF000000) return;
4520 }
4521 }
4522 ALOGE("*** we just took a black screenshot ***\n"
4523 "requested minz=%d, maxz=%d, layerStack=%d",
4524 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr1f0a16a2016-10-24 16:27:39 -07004525
Robert Carr2047fae2016-11-28 14:09:09 -08004526 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07004527 for (const auto& layer : mDrawingState.layersSortedByZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07004528 const Layer::State& state(layer->getDrawingState());
Chia-I Wuab0c3192017-08-01 11:29:00 -07004529 if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
Robert Carr1f0a16a2016-10-24 16:27:39 -07004530 state.z <= maxLayerZ) {
Dan Stoza412903f2017-04-27 13:42:17 -07004531 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07004532 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4533 layer->isVisible() ? '+' : '-',
4534 i, layer->getName().string(), layer->getLayerStack(), state.z,
Mathias Agopianfee2b462013-07-03 12:34:01 -07004535 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004536 i++;
4537 });
4538 }
4539 }
Mathias Agopianfee2b462013-07-03 12:34:01 -07004540 }
4541}
4542
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004543// ---------------------------------------------------------------------------
4544
Dan Stoza412903f2017-04-27 13:42:17 -07004545void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4546 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004547}
4548
Dan Stoza412903f2017-04-27 13:42:17 -07004549void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4550 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004551}
4552
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07004554
4555
4556#if defined(__gl_h_)
4557#error "don't include gl/gl.h in this file"
4558#endif
4559
4560#if defined(__gl2_h_)
4561#error "don't include gl2/gl2.h in this file"
4562#endif