blob: f52350474813f3b435b06089aec159a013df5add [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
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wu6d844112018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.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
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020066#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080067#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ContainerLayer.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070070#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070072#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080073#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.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"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070081#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070082#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070083#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
86
Mathias Agopian875d8e12013-06-07 15:35:48 -070087#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070088#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070089
Jiyong Park4b20c2e2017-01-14 19:45:11 +090090#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080091#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
92#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090093#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094
chaviw1d044282017-09-27 12:19:28 -070095#include <layerproto/LayerProtoParser.h>
96
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097#define DISPLAY_COUNT 1
98
Mathias Agopianfee2b462013-07-03 12:34:01 -070099/*
100 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
101 * black pixels.
102 */
103#define DEBUG_SCREENSHOTS false
104
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800105namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700106
Jaesoo Lee43518572017-01-23 19:03:16 +0900107using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900108using namespace android::hardware::configstore::V1_0;
Peiyong Linfd997e02018-03-28 15:29:00 -0700109using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700110using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700111using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700112using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113
Steven Thomasb02664d2017-07-26 18:48:28 -0700114namespace {
115class ConditionalLock {
116public:
117 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
118 if (lock) {
119 mMutex.lock();
120 }
121 }
122 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
123private:
124 Mutex& mMutex;
125 bool mLocked;
126};
127} // namespace anonymous
128
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800129// ---------------------------------------------------------------------------
130
Mathias Agopian99b49842011-06-27 16:05:52 -0700131const String16 sHardwareTest("android.permission.HARDWARE_TEST");
132const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
133const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
134const String16 sDump("android.permission.DUMP");
135
136// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800137int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
138int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700139int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700140bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800141uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800142bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800143bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800144int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800145// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600146bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700147
Kalle Raitaa099a242017-01-11 11:17:29 -0800148
149std::string getHwcServiceName() {
150 char value[PROPERTY_VALUE_MAX] = {};
151 property_get("debug.sf.hwc_service_name", value, "default");
152 ALOGI("Using HWComposer service: '%s'", value);
153 return std::string(value);
154}
155
156bool useTrebleTestingOverride() {
157 char value[PROPERTY_VALUE_MAX] = {};
158 property_get("debug.sf.treble_testing_override", value, "false");
159 ALOGI("Treble testing override: '%s'", value);
160 return std::string(value) == "true";
161}
162
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800163std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
164 switch(displayColorSetting) {
165 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700166 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800167 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700168 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800169 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700170 return std::string("Enhanced");
171 default:
172 return std::string("Unknown ") +
173 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800174 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800175}
176
Lloyd Pique09594832018-01-22 17:48:03 -0800177NativeWindowSurface::~NativeWindowSurface() = default;
178
179namespace impl {
180
181class NativeWindowSurface final : public android::NativeWindowSurface {
182public:
183 static std::unique_ptr<android::NativeWindowSurface> create(
184 const sp<IGraphicBufferProducer>& producer) {
185 return std::make_unique<NativeWindowSurface>(producer);
186 }
187
188 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
189 : surface(new Surface(producer, false)) {}
190
191 ~NativeWindowSurface() override = default;
192
193private:
194 sp<ANativeWindow> getNativeWindow() const override { return surface; }
195
196 void preallocateBuffers() override { surface->allocateBuffers(); }
197
198 sp<Surface> surface;
199};
200
201} // namespace impl
202
David Sodmanbc815282017-11-05 18:57:52 -0800203SurfaceFlingerBE::SurfaceFlingerBE()
204 : mHwcServiceName(getHwcServiceName()),
205 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800206 mFrameBuckets(),
207 mTotalTime(0),
208 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800209 mComposerSequenceId(0) {
210}
211
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800212SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800213 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700215 mTransactionPending(false),
216 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700217 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700218 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700219 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800220 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800221 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800223 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800224 mAnimCompositionPending(false),
Chia-I Wuad8d8272018-06-26 10:18:18 +0800225 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800226 mDebugRegion(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700227 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700228 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700229 mDebugInSwapBuffers(0),
230 mLastSwapBufferTime(0),
231 mDebugInTransaction(0),
232 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700233 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000234 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700235 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700236 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800237 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800238 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700239 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800240 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique09594832018-01-22 17:48:03 -0800241 mCreateBufferQueue(&BufferQueue::createBufferQueue),
242 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Pique2d3ee6d2018-01-17 13:42:24 -0800243
244SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800245 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800246
247 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
248 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
249
250 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
251 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
252
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800253 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
254 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800255
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700256 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
257 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
258
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700259 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
260 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
261
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800262 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
263 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
264
Steven Thomas050b2c82017-03-06 11:45:16 -0800265 // Vr flinger is only enabled on Daydream ready devices.
266 useVrFlinger = getBool< ISurfaceFlingerConfigs,
267 &ISurfaceFlingerConfigs::useVrFlinger>(false);
268
Fabien Sanglard1971b632017-03-10 14:50:03 -0800269 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
270 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
271
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600272 hasWideColorDisplay =
273 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
274
Iris Chang7501ed62018-04-30 14:45:42 +0800275 V1_1::DisplayOrientation primaryDisplayOrientation =
276 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
277 V1_1::DisplayOrientation::ORIENTATION_0);
278
279 switch (primaryDisplayOrientation) {
280 case V1_1::DisplayOrientation::ORIENTATION_90:
281 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
282 break;
283 case V1_1::DisplayOrientation::ORIENTATION_180:
284 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
285 break;
286 case V1_1::DisplayOrientation::ORIENTATION_270:
287 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
288 break;
289 default:
290 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
291 break;
292 }
293 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
294
David Sodman99974d22017-11-28 12:04:33 -0800295 mPrimaryDispSync.init(SurfaceFlinger::hasSyncFramework, SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700296
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800297 // debugging stuff...
298 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700299
Mathias Agopianb4b17302013-03-20 18:36:41 -0700300 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700301 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700302
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800303 property_get("debug.sf.showupdates", value, "0");
304 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700305
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700306 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodsonfb996e92019-02-04 09:36:10 +0000307
308 // DDMS debugging deprecated (b/120782499)
309 property_get("debug.sf.ddms", value, "0");
310 int debugDdms = atoi(value);
311 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700312
313 property_get("debug.sf.disable_backpressure", value, "0");
314 mPropagateBackpressure = !atoi(value);
315 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700316
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800317 property_get("debug.sf.enable_hwc_vds", value, "0");
318 mUseHwcVirtualDisplays = atoi(value);
319 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800320
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800321 property_get("ro.sf.disable_triple_buffer", value, "1");
322 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800323 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700324
Yiwei Zhang243b3782018-05-15 17:40:04 -0700325 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700326 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
327 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
328
Jorim Jaggie203e042018-06-19 15:57:08 +0200329 property_get("debug.sf.early_phase_offset_ns", value, "-1");
330 const int earlySfOffsetNs = atoi(value);
331
332 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
333 const int earlyGlSfOffsetNs = atoi(value);
334
335 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
336 const int earlyAppOffsetNs = atoi(value);
337
338 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
339 const int earlyGlAppOffsetNs = atoi(value);
340
341 const VSyncModulator::Offsets earlyOffsets =
342 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
343 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
344 const VSyncModulator::Offsets earlyGlOffsets =
345 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
346 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
347 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
348 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza2713c302018-03-28 17:07:36 -0700349
Romain Guy11d63f42017-07-20 12:47:14 -0700350 // We should be reading 'persist.sys.sf.color_saturation' here
351 // but since /data may be encrypted, we need to wait until after vold
352 // comes online to attempt to read the property. The property is
353 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800354
355 if (useTrebleTestingOverride()) {
356 // Without the override SurfaceFlinger cannot connect to HIDL
357 // services that are not listed in the manifests. Considered
358 // deriving the setting from the set service name, but it
359 // would be brittle if the name that's not 'default' is used
360 // for production purposes later on.
361 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
362 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800363}
364
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800365void SurfaceFlinger::onFirstRef()
366{
Lloyd Pique9123ae52018-01-22 17:14:00 -0800367 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800368}
369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370SurfaceFlinger::~SurfaceFlinger()
371{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372}
373
Dan Stozac7014012014-02-14 15:03:43 -0800374void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800375{
376 // the window manager died on us. prepare its eulogy.
377
Andy McFadden13a082e2012-08-24 10:16:42 -0700378 // restore initial conditions (default device unblank, etc)
379 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380
381 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700382 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800383}
384
Robert Carr1db73f62016-12-21 12:58:51 -0800385static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700386 status_t err = client->initCheck();
387 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800388 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 }
Robert Carr1db73f62016-12-21 12:58:51 -0800390 return nullptr;
391}
392
393sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
394 return initClient(new Client(this));
395}
396
397sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
398 const sp<IGraphicBufferProducer>& gbp) {
399 if (authenticateSurfaceTexture(gbp) == false) {
400 return nullptr;
401 }
402 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
403 if (layer == nullptr) {
404 return nullptr;
405 }
406
407 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408}
409
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700410sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
411 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700412{
413 class DisplayToken : public BBinder {
414 sp<SurfaceFlinger> flinger;
415 virtual ~DisplayToken() {
416 // no more references, this display must be terminated
417 Mutex::Autolock _l(flinger->mStateLock);
418 flinger->mCurrentState.displays.removeItem(this);
419 flinger->setTransactionFlags(eDisplayTransactionNeeded);
420 }
421 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700422 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700423 : flinger(flinger) {
424 }
425 };
426
427 sp<BBinder> token = new DisplayToken(this);
428
429 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700430 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700431 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700432 mCurrentState.displays.add(token, info);
Lloyd Pique4d234852018-01-22 17:21:36 -0800433 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434 return token;
435}
436
Jesse Hall6c913be2013-08-08 12:15:49 -0700437void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
438 Mutex::Autolock _l(mStateLock);
439
440 ssize_t idx = mCurrentState.displays.indexOfKey(display);
441 if (idx < 0) {
442 ALOGW("destroyDisplay: invalid display token");
443 return;
444 }
445
446 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
447 if (!info.isVirtualDisplay()) {
448 ALOGE("destroyDisplay called for non-virtual display");
449 return;
450 }
Lloyd Pique4d234852018-01-22 17:21:36 -0800451 mInterceptor->saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 mCurrentState.displays.removeItemsAt(idx);
453 setTransactionFlags(eDisplayTransactionNeeded);
454}
455
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700457 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800459 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 }
Jesse Hall692c7232012-11-08 15:41:56 -0800461 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700462}
463
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800464void SurfaceFlinger::bootFinished()
465{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700466 if (mStartPropertySetThread->join() != NO_ERROR) {
467 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800468 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800469 const nsecs_t now = systemTime();
470 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000471 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700472
473 // wait patiently for the window manager death
474 const String16 name("window");
475 sp<IBinder> window(defaultServiceManager()->getService(name));
476 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700477 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700478 }
479
Steven Thomas050b2c82017-03-06 11:45:16 -0800480 if (mVrFlinger) {
481 mVrFlinger->OnBootFinished();
482 }
483
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700484 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700485 // formerly we would just kill the process, but we now ask it to exit so it
486 // can choose where to stop the animation.
487 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700488
489 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
490 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
491 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700492
Thierry Strudel2924d012017-08-14 15:19:37 -0700493 sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
Romain Guy11d63f42017-07-20 12:47:14 -0700494 readPersistentProperties();
Chia-I Wuad8d8272018-06-26 10:18:18 +0800495 mBootStage = BootStage::FINISHED;
Romain Guy11d63f42017-07-20 12:47:14 -0700496 });
Thierry Strudel2924d012017-08-14 15:19:37 -0700497 postMessageAsync(readProperties);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498}
499
Dan Stoza9fdb7e02018-06-21 12:10:12 -0700500uint32_t SurfaceFlinger::getNewTexture() {
501 {
502 std::lock_guard lock(mTexturePoolMutex);
503 if (!mTexturePool.empty()) {
504 uint32_t name = mTexturePool.back();
505 mTexturePool.pop_back();
506 ATRACE_INT("TexturePoolSize", mTexturePool.size());
507 return name;
508 }
509
510 // The pool was too small, so increase it for the future
511 ++mTexturePoolSize;
512 }
513
514 // The pool was empty, so we need to get a new texture name directly using a
515 // blocking call to the main thread
516 uint32_t name = 0;
517 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
518 return name;
519}
520
Mathias Agopian3f844832013-08-07 21:24:32 -0700521void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700522 class MessageDestroyGLTexture : public MessageBase {
Lloyd Pique144e1162017-12-20 16:44:52 -0800523 RE::RenderEngine& engine;
Mathias Agopian3f844832013-08-07 21:24:32 -0700524 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700525 public:
Lloyd Pique144e1162017-12-20 16:44:52 -0800526 MessageDestroyGLTexture(RE::RenderEngine& engine, uint32_t texture)
527 : engine(engine), texture(texture) {}
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700528 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700529 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700530 return true;
531 }
532 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700533 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700534}
535
Lloyd Piquee83f9312018-02-01 12:53:17 -0800536class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700537public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700538 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000539 const char* name) :
540 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700541 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700542 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000543 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
544 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700545 mDispSync(dispSync),
546 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700547 mVsyncMutex(),
548 mPhaseOffset(phaseOffset),
549 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700550
Lloyd Piquee83f9312018-02-01 12:53:17 -0800551 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700552
Lloyd Piquee83f9312018-02-01 12:53:17 -0800553 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700554 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700555 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000556 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700557 static_cast<DispSync::Callback*>(this));
558 if (err != NO_ERROR) {
559 ALOGE("error registering vsync callback: %s (%d)",
560 strerror(-err), err);
561 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700562 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700563 } else {
564 status_t err = mDispSync->removeEventListener(
565 static_cast<DispSync::Callback*>(this));
566 if (err != NO_ERROR) {
567 ALOGE("error unregistering vsync callback: %s (%d)",
568 strerror(-err), err);
569 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700570 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700571 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700572 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700573 }
574
Lloyd Piquee83f9312018-02-01 12:53:17 -0800575 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700576 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577 mCallback = callback;
578 }
579
Lloyd Piquee83f9312018-02-01 12:53:17 -0800580 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700581 Mutex::Autolock lock(mVsyncMutex);
582
583 // Normalize phaseOffset to [0, period)
584 auto period = mDispSync->getPeriod();
585 phaseOffset %= period;
586 if (phaseOffset < 0) {
587 // If we're here, then phaseOffset is in (-period, 0). After this
588 // operation, it will be in (0, period)
589 phaseOffset += period;
590 }
591 mPhaseOffset = phaseOffset;
592
593 // If we're not enabled, we don't need to mess with the listeners
594 if (!mEnabled) {
595 return;
596 }
597
Dan Stoza2713c302018-03-28 17:07:36 -0700598 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
599 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700600 if (err != NO_ERROR) {
Dan Stoza2713c302018-03-28 17:07:36 -0700601 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700602 strerror(-err), err);
603 }
604 }
605
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700606private:
607 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800608 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700609 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700610 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611 callback = mCallback;
612
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700613 if (mTraceVsync) {
614 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700615 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700616 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617 }
618
Peiyong Lin566a3b42018-01-09 18:22:43 -0800619 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700620 callback->onVSyncEvent(when);
621 }
622 }
623
Tim Murray4a4e4a22016-04-19 16:29:23 +0000624 const char* const mName;
625
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700626 int mValue;
627
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700628 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700629 const String8 mVsyncOnLabel;
630 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700631
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700632 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700633
634 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800635 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700636
637 Mutex mVsyncMutex; // Protects the following
638 nsecs_t mPhaseOffset;
639 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700640};
641
Lloyd Piquee83f9312018-02-01 12:53:17 -0800642class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700643public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800644 InjectVSyncSource() = default;
645 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700646
Lloyd Piquee83f9312018-02-01 12:53:17 -0800647 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700648 std::lock_guard<std::mutex> lock(mCallbackMutex);
649 mCallback = callback;
650 }
651
Lloyd Piquee83f9312018-02-01 12:53:17 -0800652 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700653 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700654 if (mCallback) {
655 mCallback->onVSyncEvent(when);
656 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700657 }
658
Lloyd Piquee83f9312018-02-01 12:53:17 -0800659 void setVSyncEnabled(bool) override {}
660 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700661
662private:
663 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800664 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700665};
666
Wei Wangf9b05ee2017-07-19 20:59:39 -0700667// Do not call property_set on main thread which will be blocked by init
668// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700669void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700670 ALOGI( "SurfaceFlinger's main thread ready to run. "
671 "Initializing graphics H/W...");
672
Thierry Strudel2924d012017-08-14 15:19:37 -0700673 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676
Steven Thomasb02664d2017-07-26 18:48:28 -0700677 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800678 mEventThreadSource =
679 std::make_unique<DispSyncSource>(&mPrimaryDispSync, SurfaceFlinger::vsyncPhaseOffsetNs,
680 true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800681 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
682 [this]() { resyncWithRateLimit(); },
683 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800684 "appEventThread");
685 mSfEventThreadSource =
686 std::make_unique<DispSyncSource>(&mPrimaryDispSync,
687 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800688
Lloyd Pique24b0a482018-03-09 18:52:26 -0800689 mSFEventThread =
690 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
691 [this]() { resyncWithRateLimit(); },
692 [this](nsecs_t timestamp) {
693 mInterceptor->saveVSyncEvent(timestamp);
694 },
695 "sfEventThread");
Lloyd Pique9123ae52018-01-22 17:14:00 -0800696 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggie203e042018-06-19 15:57:08 +0200697 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800698
Steven Thomasb02664d2017-07-26 18:48:28 -0700699 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800700 getBE().mRenderEngine =
701 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
702 hasWideColorDisplay
703 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
704 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800705 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700706
707 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
708 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800709 getBE().mHwc.reset(
710 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700711 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800712 // Process any initial hotplug and resulting display changes.
713 processDisplayHotplugEventsLocked();
714 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY),
715 "Registered composer callback but didn't create the default primary display");
Jesse Hall692c7232012-11-08 15:41:56 -0800716
Lloyd Piquefcd86612017-12-14 17:15:36 -0800717 // make the default display GLContext current so that we can create textures
718 // when creating Layers (which may happens before we render something)
719 getDefaultDisplayDeviceLocked()->makeCurrent();
720
Steven Thomas050b2c82017-03-06 11:45:16 -0800721 if (useVrFlinger) {
722 auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700723 // This callback is called from the vr flinger dispatch thread. We
724 // need to call signalTransaction(), which requires holding
725 // mStateLock when we're not on the main thread. Acquiring
726 // mStateLock from the vr flinger dispatch thread might trigger a
727 // deadlock in surface flinger (see b/66916578), so post a message
728 // to be handled on the main thread instead.
729 sp<LambdaMessage> message = new LambdaMessage([=]() {
730 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
731 mVrFlingerRequestsDisplay = requestDisplay;
732 signalTransaction();
733 });
734 postMessageAsync(message);
Steven Thomas050b2c82017-03-06 11:45:16 -0800735 };
David Sodman105b7dc2017-11-04 20:28:14 -0700736 mVrFlinger = dvr::VrFlinger::Create(getBE().mHwc->getComposer(),
737 getBE().mHwc->getHwcDisplayId(HWC_DISPLAY_PRIMARY).value_or(0),
Steven Thomas6e8f7062017-11-22 14:15:29 -0800738 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800739 if (!mVrFlinger) {
740 ALOGE("Failed to start vrflinger");
741 }
742 }
743
Lloyd Pique0c3a8832018-01-22 17:31:47 -0800744 mEventControlThread = std::make_unique<impl::EventControlThread>(
745 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700746
Mathias Agopian92a979a2012-08-02 18:32:23 -0700747 // initialize our drawing state
748 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700749
Andy McFadden13a082e2012-08-24 10:16:42 -0700750 // set initial conditions (e.g. unblank default device)
751 initializeDisplays();
752
David Sodmanbc815282017-11-05 18:57:52 -0800753 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700754
Wei Wangf9b05ee2017-07-19 20:59:39 -0700755 // Inform native graphics APIs whether the present timestamp is supported:
756 if (getHwComposer().hasCapability(
757 HWC2::Capability::PresentFenceIsNotReliable)) {
758 mStartPropertySetThread = new StartPropertySetThread(false);
759 } else {
760 mStartPropertySetThread = new StartPropertySetThread(true);
761 }
762
763 if (mStartPropertySetThread->Start() != NO_ERROR) {
764 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800765 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800766
Chia-I Wu6d844112018-06-27 07:17:41 +0800767 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
768 // is used to saturate legacy sRGB content. However, to make sure the same color under
769 // Display P3 will be saturated to the same color, we intentionally break the API spec
770 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
771 // such saturation matrix on Display P3 is understood fully, the API should always return
772 // identify matrix.
773 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(HWC_DISPLAY_PRIMARY,
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800774 Dataspace::SRGB_LINEAR);
775
Chia-I Wu6d844112018-06-27 07:17:41 +0800776 // we will apply this on Display P3.
777 if (mEnhancedSaturationMatrix != mat4()) {
778 ColorSpace srgb(ColorSpace::sRGB());
779 ColorSpace displayP3(ColorSpace::DisplayP3());
780 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
781 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
782 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
783 }
784
Dan Stoza9e56aa02015-11-02 13:00:03 -0800785 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700786}
787
Romain Guy11d63f42017-07-20 12:47:14 -0700788void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700789 Mutex::Autolock _l(mStateLock);
790
Romain Guy11d63f42017-07-20 12:47:14 -0700791 char value[PROPERTY_VALUE_MAX];
792
793 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800794 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700795 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800796 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100797
798 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700799 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700800}
801
Mathias Agopiana67e4182012-06-19 17:26:12 -0700802void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800803 // Start boot animation service by setting a property mailbox
804 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700805 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800806 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700807 if (mStartPropertySetThread->join() != NO_ERROR) {
808 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800809 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700810}
811
Mathias Agopian875d8e12013-06-07 15:35:48 -0700812size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800813 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700814}
815
Mathias Agopian875d8e12013-06-07 15:35:48 -0700816size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800817 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700818}
819
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800820// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800821
Jamie Gennis582270d2011-08-17 18:19:00 -0700822bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800823 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800824 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800825 return authenticateSurfaceTextureLocked(bufferProducer);
826}
827
828bool SurfaceFlinger::authenticateSurfaceTextureLocked(
829 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800830 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800831 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800832}
833
Brian Anderson6b376712017-04-04 10:51:39 -0700834status_t SurfaceFlinger::getSupportedFrameTimestamps(
835 std::vector<FrameEvent>* outSupported) const {
836 *outSupported = {
837 FrameEvent::REQUESTED_PRESENT,
838 FrameEvent::ACQUIRE,
839 FrameEvent::LATCH,
840 FrameEvent::FIRST_REFRESH_START,
841 FrameEvent::LAST_REFRESH_START,
842 FrameEvent::GPU_COMPOSITION_DONE,
843 FrameEvent::DEQUEUE_READY,
844 FrameEvent::RELEASE,
845 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700848 if (!getHwComposer().hasCapability(
849 HWC2::Capability::PresentFenceIsNotReliable)) {
850 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
851 }
852 return NO_ERROR;
853}
854
Dan Stoza7f7da322014-05-02 15:26:25 -0700855status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
856 Vector<DisplayInfo>* configs) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800857 if (configs == nullptr || display.get() == nullptr) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 return BAD_VALUE;
859 }
860
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500861 if (!display.get())
862 return NAME_NOT_FOUND;
863
Jesse Hall692c7232012-11-08 15:41:56 -0800864 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700865 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800866 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700867 type = i;
868 break;
869 }
870 }
871
872 if (type < 0) {
873 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700874 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700875
Mathias Agopian8b736f12012-08-13 17:54:26 -0700876 // TODO: Not sure if display density should handled by SF any longer
877 class Density {
878 static int getDensityFromProperty(char const* propName) {
879 char property[PROPERTY_VALUE_MAX];
880 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800881 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700882 density = atoi(property);
883 }
884 return density;
885 }
886 public:
887 static int getEmuDensity() {
888 return getDensityFromProperty("qemu.sf.lcd_density"); }
889 static int getBuildDensity() {
890 return getDensityFromProperty("ro.sf.lcd_density"); }
891 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700894
Steven Thomas6d8110b2017-08-31 18:24:21 -0700895 ConditionalLock _l(mStateLock,
896 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 DisplayInfo info = DisplayInfo();
899
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900 float xdpi = hwConfig->getDpiX();
901 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
903 if (type == DisplayDevice::DISPLAY_PRIMARY) {
904 // The density of the device is provided by a build property
905 float density = Density::getBuildDensity() / 160.0f;
906 if (density == 0) {
907 // the build doesn't provide a density -- this is wrong!
908 // use xdpi instead
909 ALOGE("ro.sf.lcd_density must be defined as a build property");
910 density = xdpi / 160.0f;
911 }
912 if (Density::getEmuDensity()) {
913 // if "qemu.sf.lcd_density" is specified, it overrides everything
914 xdpi = ydpi = density = Density::getEmuDensity();
915 density /= 160.0f;
916 }
917 info.density = density;
918
919 // TODO: this needs to go away (currently needed only by webkit)
Steven Thomas6d8110b2017-08-31 18:24:21 -0700920 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -0800921 info.orientation = hw ? hw->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700922 } else {
923 // TODO: where should this value come from?
924 static const int TV_DENSITY = 213;
925 info.density = TV_DENSITY / 160.0f;
926 info.orientation = 0;
927 }
928
Dan Stoza9e56aa02015-11-02 13:00:03 -0800929 info.w = hwConfig->getWidth();
930 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700931 info.xdpi = xdpi;
932 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800933 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900934 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800935
Andy McFadden91b2ca82014-06-13 14:04:23 -0700936 // This is how far in advance a buffer must be queued for
937 // presentation at a given time. If you want a buffer to appear
938 // on the screen at time N, you must submit the buffer before
939 // (N - presentationDeadline).
940 //
941 // Normally it's one full refresh period (to give SF a chance to
942 // latch the buffer), but this can be reduced by configuring a
943 // DispSync offset. Any additional delays introduced by the hardware
944 // composer or panel must be accounted for here.
945 //
946 // We add an additional 1ms to allow for processing time and
947 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800948 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800949 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700950
951 // All non-virtual displays are currently considered secure.
952 info.secure = true;
953
Iris Chang7501ed62018-04-30 14:45:42 +0800954 if (type == DisplayDevice::DISPLAY_PRIMARY &&
955 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
956 std::swap(info.w, info.h);
957 }
958
Michael Wright28f24d02016-07-12 13:30:53 -0700959 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700960 }
961
Dan Stoza7f7da322014-05-02 15:26:25 -0700962 return NO_ERROR;
963}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700964
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800965status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700966 DisplayStatInfo* stats) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800967 if (stats == nullptr) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700968 return BAD_VALUE;
969 }
970
971 // FIXME for now we always return stats for the primary display
972 memset(stats, 0, sizeof(*stats));
973 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
974 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
975 return NO_ERROR;
976}
977
Yiwei Zhang1d465af2018-08-21 15:15:42 -0700978status_t SurfaceFlinger::getDisplayViewport(const sp<IBinder>& display, Rect* outViewport) {
979 if (outViewport == nullptr || display.get() == nullptr) {
980 return BAD_VALUE;
981 }
982
983 sp<const DisplayDevice> device(getDisplayDevice(display));
984 if (device == nullptr) {
985 return BAD_VALUE;
986 }
987
988 *outViewport = device->getViewport();
989
990 return NO_ERROR;
991}
992
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700993int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Peiyong Lin566a3b42018-01-09 18:22:43 -0800994 if (display == nullptr) {
995 ALOGE("%s : display is nullptr", __func__);
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800996 return BAD_VALUE;
997 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700998
999 sp<const DisplayDevice> device(getDisplayDevice(display));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001000 if (device != nullptr) {
Dan Stoza24a42e92015-03-09 10:04:11 -07001001 return device->getActiveConfig();
1002 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001003
Dan Stoza24a42e92015-03-09 10:04:11 -07001004 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -07001005}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001006
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001007void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
1008 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
1009 this);
1010 int32_t type = hw->getDisplayType();
1011 int currentMode = hw->getActiveConfig();
1012
1013 if (mode == currentMode) {
1014 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
1015 return;
1016 }
1017
1018 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1019 ALOGW("Trying to set config for virtual display");
1020 return;
1021 }
1022
1023 hw->setActiveConfig(mode);
1024 getHwComposer().setActiveConfig(type, mode);
1025}
1026
1027status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
1028 class MessageSetActiveConfig: public MessageBase {
1029 SurfaceFlinger& mFlinger;
1030 sp<IBinder> mDisplay;
1031 int mMode;
1032 public:
1033 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
1034 int mode) :
1035 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1036 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -07001037 Vector<DisplayInfo> configs;
1038 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -07001039 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -07001040 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -07001041 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -07001042 return true;
Michael Lentine7306c672014-07-30 13:00:37 -07001043 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001044 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08001045 if (hw == nullptr) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001046 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07001047 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001048 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1049 ALOGW("Attempt to set active config = %d for virtual display",
1050 mMode);
1051 } else {
1052 mFlinger.setActiveConfigInternal(hw, mMode);
1053 }
1054 return true;
1055 }
1056 };
1057 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
1058 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -07001059 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001060}
Michael Wright28f24d02016-07-12 13:30:53 -07001061status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001062 Vector<ColorMode>* outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001063 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
1064 return BAD_VALUE;
1065 }
1066
1067 if (!display.get()) {
1068 return NAME_NOT_FOUND;
1069 }
1070
1071 int32_t type = NAME_NOT_FOUND;
1072 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
1073 if (display == mBuiltinDisplays[i]) {
1074 type = i;
1075 break;
1076 }
1077 }
1078
1079 if (type < 0) {
1080 return type;
1081 }
1082
Peiyong Lina52f0292018-03-14 17:26:31 -07001083 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001084 {
1085 ConditionalLock _l(mStateLock,
1086 std::this_thread::get_id() != mMainThreadId);
1087 modes = getHwComposer().getColorModes(type);
1088 }
Michael Wright28f24d02016-07-12 13:30:53 -07001089 outColorModes->clear();
1090 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1091
1092 return NO_ERROR;
1093}
1094
Peiyong Lina52f0292018-03-14 17:26:31 -07001095ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001096 sp<const DisplayDevice> device(getDisplayDevice(display));
Michael Wright28f24d02016-07-12 13:30:53 -07001097 if (device != nullptr) {
1098 return device->getActiveColorMode();
1099 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001100 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001101}
1102
1103void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001104 ColorMode mode, Dataspace dataSpace,
1105 RenderIntent renderIntent) {
Michael Wright28f24d02016-07-12 13:30:53 -07001106 int32_t type = hw->getDisplayType();
Peiyong Lina52f0292018-03-14 17:26:31 -07001107 ColorMode currentMode = hw->getActiveColorMode();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001108 Dataspace currentDataSpace = hw->getCompositionDataSpace();
Peiyong Lin38e9a562018-04-10 16:24:20 -07001109 RenderIntent currentRenderIntent = hw->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001110
Peiyong Lin38e9a562018-04-10 16:24:20 -07001111 if (mode == currentMode && dataSpace == currentDataSpace &&
1112 renderIntent == currentRenderIntent) {
1113 return;
1114 }
1115
1116 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1117 ALOGW("Trying to set config for virtual display");
1118 return;
1119 }
1120
1121 hw->setActiveColorMode(mode);
1122 hw->setCompositionDataSpace(dataSpace);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001123 hw->setActiveRenderIntent(renderIntent);
1124 getHwComposer().setActiveColorMode(type, mode, renderIntent);
1125
1126 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
1127 decodeColorMode(mode).c_str(), mode,
1128 decodeRenderIntent(renderIntent).c_str(), renderIntent,
1129 hw->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001130}
1131
1132
1133status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
Peiyong Lina52f0292018-03-14 17:26:31 -07001134 ColorMode colorMode) {
Michael Wright28f24d02016-07-12 13:30:53 -07001135 class MessageSetActiveColorMode: public MessageBase {
1136 SurfaceFlinger& mFlinger;
1137 sp<IBinder> mDisplay;
Peiyong Lina52f0292018-03-14 17:26:31 -07001138 ColorMode mMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001139 public:
1140 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
Peiyong Lina52f0292018-03-14 17:26:31 -07001141 ColorMode mode) :
Michael Wright28f24d02016-07-12 13:30:53 -07001142 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
1143 virtual bool handler() {
Peiyong Lina52f0292018-03-14 17:26:31 -07001144 Vector<ColorMode> modes;
Michael Wright28f24d02016-07-12 13:30:53 -07001145 mFlinger.getDisplayColorModes(mDisplay, &modes);
1146 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
Peiyong Lina52f0292018-03-14 17:26:31 -07001147 if (mMode < ColorMode::NATIVE || !exists) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001148 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
1149 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001150 return true;
1151 }
1152 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
1153 if (hw == nullptr) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001154 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
1155 decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
Michael Wright28f24d02016-07-12 13:30:53 -07001156 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001157 ALOGW("Attempt to set active color mode %s %d for virtual display",
1158 decodeColorMode(mMode).c_str(), mMode);
Michael Wright28f24d02016-07-12 13:30:53 -07001159 } else {
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001160 mFlinger.setActiveColorModeInternal(hw, mMode, Dataspace::UNKNOWN,
1161 RenderIntent::COLORIMETRIC);
Michael Wright28f24d02016-07-12 13:30:53 -07001162 }
1163 return true;
1164 }
1165 };
1166 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
1167 postMessageSync(msg);
1168 return NO_ERROR;
1169}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001170
Svetoslavd85084b2014-03-20 10:28:31 -07001171status_t SurfaceFlinger::clearAnimationFrameStats() {
1172 Mutex::Autolock _l(mStateLock);
1173 mAnimFrameTracker.clearStats();
1174 return NO_ERROR;
1175}
1176
1177status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1178 Mutex::Autolock _l(mStateLock);
1179 mAnimFrameTracker.getStats(outStats);
1180 return NO_ERROR;
1181}
1182
Dan Stozac4f471e2016-03-24 09:31:08 -07001183status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1184 HdrCapabilities* outCapabilities) const {
1185 Mutex::Autolock _l(mStateLock);
1186
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001187 sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
Dan Stozac4f471e2016-03-24 09:31:08 -07001188 if (displayDevice == nullptr) {
1189 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1190 return BAD_VALUE;
1191 }
1192
Peiyong Linfb069302018-04-25 14:34:31 -07001193 // At this point the DisplayDeivce should already be set up,
1194 // meaning the luminance information is already queried from
1195 // hardware composer and stored properly.
1196 const HdrCapabilities& capabilities = displayDevice->getHdrCapabilities();
1197 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1198 capabilities.getDesiredMaxLuminance(),
1199 capabilities.getDesiredMaxAverageLuminance(),
1200 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001201
1202 return NO_ERROR;
1203}
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001206 sp<LambdaMessage> enableVSyncInjections = new LambdaMessage([&]() {
1207 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001208
Chia-I Wu90f669f2017-10-05 14:24:41 -07001209 if (mInjectVSyncs == enable) {
1210 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001212
1213 if (enable) {
1214 ALOGV("VSync Injections enabled");
1215 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001216 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001217 mInjectorEventThread = std::make_unique<
1218 impl::EventThread>(mVSyncInjector.get(),
1219 [this]() { resyncWithRateLimit(); },
1220 impl::EventThread::InterceptVSyncsCallback(),
1221 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001222 }
Lloyd Pique9123ae52018-01-22 17:14:00 -08001223 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001224 } else {
1225 ALOGV("VSync Injections disabled");
Lloyd Pique9123ae52018-01-22 17:14:00 -08001226 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001227 }
1228
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229 mInjectVSyncs = enable;
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230 });
1231 postMessageSync(enableVSyncInjections);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001232 return NO_ERROR;
1233}
1234
1235status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001236 Mutex::Autolock _l(mStateLock);
1237
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001238 if (!mInjectVSyncs) {
1239 ALOGE("VSync Injections not enabled");
1240 return BAD_VALUE;
1241 }
1242 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1243 ALOGV("Injecting VSync inside SurfaceFlinger");
1244 mVSyncInjector->onInjectSyncEvent(when);
1245 }
1246 return NO_ERROR;
1247}
1248
Lloyd Pique755e3192018-01-31 16:46:15 -08001249status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1250 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001251 IPCThreadState* ipc = IPCThreadState::self();
1252 const int pid = ipc->getCallingPid();
1253 const int uid = ipc->getCallingUid();
1254 if ((uid != AID_SHELL) &&
1255 !PermissionCache::checkPermission(sDump, pid, uid)) {
1256 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1257 return PERMISSION_DENIED;
1258 }
1259
1260 // Try to acquire a lock for 1s, fail gracefully
1261 const status_t err = mStateLock.timedLock(s2ns(1));
1262 const bool locked = (err == NO_ERROR);
1263 if (!locked) {
1264 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1265 return TIMED_OUT;
1266 }
1267
1268 outLayers->clear();
1269 mCurrentState.traverseInZOrder([&](Layer* layer) {
1270 outLayers->push_back(layer->getLayerDebugInfo());
1271 });
1272
1273 mStateLock.unlock();
1274 return NO_ERROR;
1275}
1276
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001277// ----------------------------------------------------------------------------
1278
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001279sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1280 ISurfaceComposer::VsyncSource vsyncSource) {
1281 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1282 return mSFEventThread->createEventConnection();
1283 } else {
1284 return mEventThread->createEventConnection();
1285 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001286}
1287
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001288// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001289
1290void SurfaceFlinger::waitForEvent() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001291 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001292}
1293
1294void SurfaceFlinger::signalTransaction() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001295 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001296}
1297
1298void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001299 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001300}
1301
1302void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001303 mRefreshPending = true;
Lloyd Pique9123ae52018-01-22 17:14:00 -08001304 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001305}
1306
1307status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001308 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001309 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001310}
1311
1312status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001313 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique9123ae52018-01-22 17:14:00 -08001314 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315 if (res == NO_ERROR) {
1316 msg->wait();
1317 }
1318 return res;
1319}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001321void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001322 do {
1323 waitForEvent();
1324 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001325}
1326
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001327void SurfaceFlinger::enableHardwareVsync() {
1328 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001329 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001331 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1332 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001334 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335}
1336
Jesse Hall948fe0c2013-10-14 12:56:09 -07001337void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338 Mutex::Autolock _l(mHWVsyncLock);
1339
Jesse Hall948fe0c2013-10-14 12:56:09 -07001340 if (makeAvailable) {
1341 mHWVsyncAvailable = true;
1342 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001343 // Hardware vsync is not currently available, so abort the resync
1344 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001345 return;
1346 }
1347
David Sodman105b7dc2017-11-04 20:28:14 -07001348 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001349 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001350
1351 mPrimaryDispSync.reset();
1352 mPrimaryDispSync.setPeriod(period);
1353
1354 if (!mPrimaryHWVsyncEnabled) {
1355 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001356 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1357 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001358 mPrimaryHWVsyncEnabled = true;
1359 }
1360}
1361
Jesse Hall948fe0c2013-10-14 12:56:09 -07001362void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001363 Mutex::Autolock _l(mHWVsyncLock);
1364 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001365 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1366 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001367 mPrimaryDispSync.endResync();
1368 mPrimaryHWVsyncEnabled = false;
1369 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001370 if (makeUnavailable) {
1371 mHWVsyncAvailable = false;
1372 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001373}
1374
Tim Murray4a4e4a22016-04-19 16:29:23 +00001375void SurfaceFlinger::resyncWithRateLimit() {
1376 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001377
1378 // No explicit locking is needed here since EventThread holds a lock while calling this method
1379 static nsecs_t sLastResyncAttempted = 0;
1380 const nsecs_t now = systemTime();
1381 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001382 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001383 }
Dan Stoza57164302017-05-08 14:03:54 -07001384 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001385}
1386
Steven Thomasb02664d2017-07-26 18:48:28 -07001387void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1388 hwc2_display_t displayId, int64_t timestamp) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001389 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001391 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001392 return;
1393 }
1394
1395 int32_t type;
David Sodman105b7dc2017-11-04 20:28:14 -07001396 if (!getBE().mHwc->onVsync(displayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001397 return;
1398 }
1399
Jamie Gennisd1700752013-10-14 12:22:52 -07001400 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001401
Jamie Gennisd1700752013-10-14 12:22:52 -07001402 { // Scope for the lock
1403 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001405 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001406 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001407 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001408
1409 if (needsHwVsync) {
1410 enableHardwareVsync();
1411 } else {
1412 disableHardwareVsync(false);
1413 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001414}
1415
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001416void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001417 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1418 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001419}
1420
Lloyd Pique715a2c12017-12-14 17:18:08 -08001421void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
1422 HWC2::Connection connection) {
1423 ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s)", sequenceId, display,
1424 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001425
Lloyd Piqueba04e622017-12-14 17:11:26 -08001426 // Ignore events that do not have the right sequenceId.
1427 if (sequenceId != getBE().mComposerSequenceId) {
1428 return;
1429 }
1430
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 // Only lock if we're not on the main thread. This function is normally
1432 // called on a hwbinder thread, but for the primary display it's called on
1433 // the main thread with the state lock already held, so don't attempt to
1434 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001435 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001436
Lloyd Pique715a2c12017-12-14 17:18:08 -08001437 mPendingHotplugEvents.emplace_back(HotplugEvent{display, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001438
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001439 if (std::this_thread::get_id() == mMainThreadId) {
1440 // Process all pending hot plug events immediately if we are on the main thread.
1441 processDisplayHotplugEventsLocked();
1442 }
1443
Lloyd Piqueba04e622017-12-14 17:11:26 -08001444 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001445}
1446
Steven Thomasb02664d2017-07-26 18:48:28 -07001447void SurfaceFlinger::onRefreshReceived(int sequenceId,
1448 hwc2_display_t /*display*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001449 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001450 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001451 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001452 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001453 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001454}
1455
Dan Stoza9e56aa02015-11-02 13:00:03 -08001456void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001457 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001458 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001459 getHwComposer().setVsyncEnabled(disp,
1460 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001461}
1462
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001464void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001466 // Clear the drawing state so that the logic inside of
1467 // handleTransactionLocked will fire. It will determine the delta between
1468 // mCurrentState and mDrawingState and re-apply all changes when we make the
1469 // transition.
1470 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001471 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472 mDisplays.clear();
1473}
1474
Steven Thomas050b2c82017-03-06 11:45:16 -08001475void SurfaceFlinger::updateVrFlinger() {
1476 if (!mVrFlinger)
1477 return;
1478 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001479 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001480 return;
1481 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482
David Sodman105b7dc2017-11-04 20:28:14 -07001483 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 ALOGE("Vr flinger is only supported for remote hardware composer"
1485 " service connections. Ignoring request to transition to vr"
1486 " flinger.");
1487 mVrFlingerRequestsDisplay = false;
1488 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001489 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001490
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001492
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 int currentDisplayPowerMode = getDisplayDeviceLocked(
1494 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001495
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001499
Steven Thomasb02664d2017-07-26 18:48:28 -07001500 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001501 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001502 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1503 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001504 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001505
David Sodman105b7dc2017-11-04 20:28:14 -07001506 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1507 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001508
1509 if (vrFlingerRequestsDisplay) {
1510 mVrFlinger->GrantDisplayOwnership();
1511 } else {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001512 enableHardwareVsync();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001513 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001514
1515 mVisibleRegionsDirty = true;
1516 invalidateHwcGeometry();
1517
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001518 // Re-enable default display.
Steven Thomasb02664d2017-07-26 18:48:28 -07001519 sp<DisplayDevice> hw(getDisplayDeviceLocked(
1520 mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1521 setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001522
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 // Reset the timing values to account for the period of the swapped in HWC
David Sodman105b7dc2017-11-04 20:28:14 -07001524 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Steven Thomasb02664d2017-07-26 18:48:28 -07001525 const nsecs_t period = activeConfig->getVsyncPeriod();
1526 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001527
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 // Use phase of 0 since phase is not known.
1529 // Use latency of 0, which will snap to the ideal latency.
1530 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001531
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001532 android_atomic_or(1, &mRepaintEverything);
1533 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001534}
1535
Mathias Agopian4fec8732012-06-29 14:12:52 -07001536void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001537 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001539 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001540 bool frameMissed = !mHadClientComposition &&
1541 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 (mPreviousPresentFence->getSignalTime() ==
1543 Fence::SIGNAL_TIME_PENDING);
Dan Stoza50182882016-07-08 12:02:20 -07001544 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001545 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001546 mTimeStats.incrementMissedFrames();
1547 if (mPropagateBackpressure) {
1548 signalLayerUpdate();
1549 break;
1550 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001551 }
Dan Stoza50182882016-07-08 12:02:20 -07001552
Steven Thomas050b2c82017-03-06 11:45:16 -08001553 // Now that we're going to make it to the handleMessageTransaction()
1554 // call below it's safe to call updateVrFlinger(), which will
1555 // potentially trigger a display handoff.
1556 updateVrFlinger();
1557
Dan Stoza6b9454d2014-11-07 16:00:59 -08001558 bool refreshNeeded = handleMessageTransaction();
1559 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001560 refreshNeeded |= mRepaintEverything;
Chia-I Wuad8d8272018-06-26 10:18:18 +08001561 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001562 // Signal a refresh if a transaction modified the window state,
1563 // a new buffer was latched, or if HWC has requested a full
1564 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001565 signalRefresh();
1566 }
1567 break;
1568 }
1569 case MessageQueue::REFRESH: {
1570 handleMessageRefresh();
1571 break;
1572 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001573 }
1574}
1575
Dan Stoza6b9454d2014-11-07 16:00:59 -08001576bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001577 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001578 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001579 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001580 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001581 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001582 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001583}
1584
Dan Stoza6b9454d2014-11-07 16:00:59 -08001585bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001586 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001587 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001588}
1589
1590void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001591 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001592
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001593 mRefreshPending = false;
1594
Pablo Ceballos40845df2016-01-25 17:41:15 -08001595 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001596
Brian Andersond6927fb2016-07-23 23:37:30 -07001597 preComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001598 rebuildLayerStacks();
1599 setUpHWComposer();
1600 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001601 doTracing("handleRefresh");
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001602 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001603 doComposition();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001604 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001605
David Sodman105b7dc2017-11-04 20:28:14 -07001606 mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001607
1608 mHadClientComposition = false;
1609 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1610 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1611 mHadClientComposition = mHadClientComposition ||
David Sodman105b7dc2017-11-04 20:28:14 -07001612 getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001613 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001614 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001615
Dan Stoza9e56aa02015-11-02 13:00:03 -08001616 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001617}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001618
Mathias Agopiancd60f992012-08-16 16:28:27 -07001619void SurfaceFlinger::doDebugFlashRegions()
1620{
1621 // is debugging enabled
1622 if (CC_LIKELY(!mDebugRegion))
1623 return;
1624
1625 const bool repaintEverything = mRepaintEverything;
1626 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1627 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001628 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001629 // transform the dirty region into this screen's coordinate space
1630 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1631 if (!dirtyRegion.isEmpty()) {
1632 // redraw the whole screen
Chia-I Wub02087d2017-11-09 10:19:54 -08001633 doComposeSurfaces(hw);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001634
1635 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636 const int32_t height = hw->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001637 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001638 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1639
Mathias Agopianda27af92012-09-13 18:17:13 -07001640 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001641 }
1642 }
1643 }
1644
1645 postFramebuffer();
1646
1647 if (mDebugRegion > 1) {
1648 usleep(mDebugRegion * 1000);
1649 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001650
Dan Stoza9e56aa02015-11-02 13:00:03 -08001651 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001652 auto& displayDevice = mDisplays[displayId];
1653 if (!displayDevice->isDisplayOn()) {
1654 continue;
1655 }
1656
David Sodman105b7dc2017-11-04 20:28:14 -07001657 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
1658 ALOGE_IF(result != NO_ERROR,
1659 "prepareFrame for display %zd failed:"
1660 " %d (%s)",
1661 displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001662 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001663}
1664
Adrian Roos1e1a1282017-11-01 19:05:31 +01001665void SurfaceFlinger::doTracing(const char* where) {
1666 ATRACE_CALL();
1667 ATRACE_NAME(where);
1668 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001669 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001670 }
1671}
1672
Yiwei Zhang068e31b2018-02-21 13:02:45 -08001673void SurfaceFlinger::logLayerStats() {
1674 ATRACE_CALL();
1675 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1676 int32_t hwcId = -1;
1677 for (size_t dpy = 0; dpy < mDisplays.size(); ++dpy) {
1678 const sp<const DisplayDevice>& displayDevice(mDisplays[dpy]);
1679 if (displayDevice->isPrimary()) {
1680 hwcId = displayDevice->getHwcDisplayId();
1681 break;
1682 }
1683 }
1684 if (hwcId < 0) {
1685 ALOGE("LayerStats: Hmmm, no primary display?");
1686 return;
1687 }
1688 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(hwcId));
1689 }
1690}
1691
Brian Andersond6927fb2016-07-23 23:37:30 -07001692void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 ATRACE_CALL();
1695 ALOGV("preComposition");
1696
Mathias Agopiancd60f992012-08-16 16:28:27 -07001697 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001698 mDrawingState.traverseInZOrder([&](Layer* layer) {
1699 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001700 needExtraInvalidate = true;
1701 }
Robert Carr2047fae2016-11-28 14:09:09 -08001702 });
1703
Mathias Agopiancd60f992012-08-16 16:28:27 -07001704 if (needExtraInvalidate) {
1705 signalLayerUpdate();
1706 }
1707}
1708
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001709void SurfaceFlinger::updateCompositorTiming(
1710 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1711 std::shared_ptr<FenceTime>& presentFenceTime) {
1712 // Update queue of past composite+present times and determine the
1713 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001714 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001715 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001716 while (!getBE().mCompositePresentTimes.empty()) {
1717 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 // Cached values should have been updated before calling this method,
1719 // which helps avoid duplicate syscalls.
1720 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1721 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1722 break;
1723 }
1724 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001725 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001726 }
1727
1728 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001729 while (getBE().mCompositePresentTimes.size() > 16) {
1730 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001731 }
1732
Brian Andersond0010582017-03-07 13:20:31 -08001733 setCompositorTimingSnapped(
1734 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1735}
1736
1737void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1738 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739 // Integer division and modulo round toward 0 not -inf, so we need to
1740 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001741 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001742 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1743 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1744
Brian Andersond0010582017-03-07 13:20:31 -08001745 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1746 if (idealLatency <= 0) {
1747 idealLatency = vsyncInterval;
1748 }
1749
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001750 // Snap the latency to a value that removes scheduling jitter from the
1751 // composition and present times, which often have >1ms of jitter.
1752 // Reducing jitter is important if an app attempts to extrapolate
1753 // something (such as user input) to an accurate diasplay time.
1754 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1755 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001756 nsecs_t bias = vsyncInterval / 2;
1757 int64_t extraVsyncs =
1758 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1759 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1760 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001761
David Sodman99974d22017-11-28 12:04:33 -08001762 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1763 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1764 getBE().mCompositorTiming.interval = vsyncInterval;
1765 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766}
1767
1768void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001769{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001770 ATRACE_CALL();
1771 ALOGV("postComposition");
1772
Brian Anderson3546a3f2016-07-14 11:51:14 -07001773 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001774 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001775 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001776 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001777 }
1778
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001779 // |mStateLock| not needed as we are on the main thread
1780 const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Brian Anderson3d4039d2016-09-23 16:31:30 -07001781
David Sodman73beded2017-11-15 11:56:06 -08001782 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001783 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001784 if (hw && getBE().mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001785 glCompositionDoneFenceTime =
1786 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001787 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001788 } else {
1789 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1790 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001791
David Sodman73beded2017-11-15 11:56:06 -08001792 getBE().mDisplayTimeline.updateSignalTimes();
David Sodman105b7dc2017-11-04 20:28:14 -07001793 sp<Fence> presentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
Brian Anderson4e606e32017-03-16 15:34:57 -07001794 auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
David Sodman73beded2017-11-15 11:56:06 -08001795 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001796
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1798 nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1799
1800 // We use the refreshStartTime which might be sampled a little later than
1801 // when we started doing work for this frame, but that should be okay
1802 // since updateCompositorTiming has snapping logic.
1803 updateCompositorTiming(
Brian Anderson4e606e32017-03-16 15:34:57 -07001804 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001805 CompositorTiming compositorTiming;
1806 {
David Sodman99974d22017-11-28 12:04:33 -08001807 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1808 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001809 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001810
Robert Carr2047fae2016-11-28 14:09:09 -08001811 mDrawingState.traverseInZOrder([&](Layer* layer) {
1812 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001813 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001814 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001815 recordBufferingStats(layer->getName().string(),
1816 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001817 }
Robert Carr2047fae2016-11-28 14:09:09 -08001818 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001819
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001820 if (presentFenceTime->isValid()) {
1821 if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001822 enableHardwareVsync();
1823 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001824 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001825 }
1826 }
1827
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001828 if (!hasSyncFramework) {
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001829 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) && hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001830 enableHardwareVsync();
1831 }
1832 }
1833
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001834 if (mAnimCompositionPending) {
1835 mAnimCompositionPending = false;
1836
Brian Anderson4e606e32017-03-16 15:34:57 -07001837 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001838 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001839 std::move(presentFenceTime));
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001840 } else if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001841 // The HWC doesn't support present fences, so use the refresh
1842 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001843 nsecs_t presentTime =
David Sodman105b7dc2017-11-04 20:28:14 -07001844 getBE().mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001845 mAnimFrameTracker.setActualPresentTime(presentTime);
1846 }
1847 mAnimFrameTracker.advanceFrame();
1848 }
Dan Stozab90cf072015-03-05 11:05:59 -08001849
Yiwei Zhang0102ad22018-05-02 17:37:17 -07001850 mTimeStats.incrementTotalFrames();
1851 if (mHadClientComposition) {
1852 mTimeStats.incrementClientCompositionFrames();
1853 }
1854
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08001855 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY) &&
1856 hw->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001857 return;
1858 }
1859
1860 nsecs_t currentTime = systemTime();
1861 if (mHasPoweredOff) {
1862 mHasPoweredOff = false;
1863 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001864 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001866 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1867 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001868 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001869 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001870 }
David Sodman4a36e932017-11-07 14:29:47 -08001871 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001872 }
David Sodman4a36e932017-11-07 14:29:47 -08001873 getBE().mLastSwapTime = currentTime;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07001874
1875 {
1876 std::lock_guard lock(mTexturePoolMutex);
1877 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1878 if (refillCount > 0) {
1879 const size_t offset = mTexturePool.size();
1880 mTexturePool.resize(mTexturePoolSize);
1881 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1882 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1883 }
1884 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001885}
1886
1887void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001888 ATRACE_CALL();
1889 ALOGV("rebuildLayerStacks");
1890
Mathias Agopiancd60f992012-08-16 16:28:27 -07001891 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001892 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001893 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001894 mVisibleRegionsDirty = false;
1895 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001896
Jeff Sharkey76488112017-02-27 14:15:18 -07001897 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1898 Region opaqueRegion;
1899 Region dirtyRegion;
1900 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001901 Vector<sp<Layer>> layersNeedingFences;
Jeff Sharkey76488112017-02-27 14:15:18 -07001902 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1903 const Transform& tr(displayDevice->getTransform());
1904 const Rect bounds(displayDevice->getBounds());
1905 if (displayDevice->isDisplayOn()) {
Chia-I Wuab0c3192017-08-01 11:29:00 -07001906 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001907
Jeff Sharkey76488112017-02-27 14:15:18 -07001908 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001909 bool hwcLayerDestroyed = false;
Chia-I Wuab0c3192017-08-01 11:29:00 -07001910 if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1911 displayDevice->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001912 Region drawRegion(tr.transform(
1913 layer->visibleNonTransparentRegion));
1914 drawRegion.andSelf(bounds);
1915 if (!drawRegion.isEmpty()) {
1916 layersSortedByZ.add(layer);
1917 } else {
1918 // Clear out the HWC layer if this layer was
1919 // previously visible, but no longer is
Chia-I Wu83806892017-11-16 10:50:20 -08001920 hwcLayerDestroyed = layer->destroyHwcLayer(
Steven Thomasb02664d2017-07-26 18:48:28 -07001921 displayDevice->getHwcDisplayId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001922 }
Fabien Sanglard06a76c02017-03-03 11:19:30 -08001923 } else {
Fabien Sanglard82260512017-03-03 14:58:52 -08001924 // WM changes displayDevice->layerStack upon sleep/awake.
1925 // Here we make sure we delete the HWC layers even if
1926 // WM changed their layer stack.
Chia-I Wu83806892017-11-16 10:50:20 -08001927 hwcLayerDestroyed = layer->destroyHwcLayer(
1928 displayDevice->getHwcDisplayId());
1929 }
1930
1931 // If a layer is not going to get a release fence because
1932 // it is invisible, but it is also going to release its
1933 // old buffer, add it to the list of layers needing
1934 // fences.
1935 if (hwcLayerDestroyed) {
1936 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1937 mLayersWithQueuedFrames.cend(), layer);
1938 if (found != mLayersWithQueuedFrames.cend()) {
1939 layersNeedingFences.add(layer);
1940 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001941 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001942 });
1943 }
1944 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
Chia-I Wu83806892017-11-16 10:50:20 -08001945 displayDevice->setLayersNeedingFences(layersNeedingFences);
Jeff Sharkey76488112017-02-27 14:15:18 -07001946 displayDevice->undefinedRegion.set(bounds);
1947 displayDevice->undefinedRegion.subtractSelf(
1948 tr.transform(opaqueRegion));
1949 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001950 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001951 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001953
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001954// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001955// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001956// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001957// - Dataspace::DISPLAY_P3
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001958// The returned HDR data space is one of
1959// - Dataspace::UNKNOWN
1960// - Dataspace::BT2020_HLG
1961// - Dataspace::BT2020_PQ
1962Dataspace SurfaceFlinger::getBestDataspace(
1963 const sp<const DisplayDevice>& displayDevice, Dataspace* outHdrDataSpace) const {
1964 Dataspace bestDataSpace = Dataspace::SRGB;
1965 *outHdrDataSpace = Dataspace::UNKNOWN;
1966
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001967 for (const auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu1b6bafc2018-05-22 12:03:00 -07001968 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001969 case Dataspace::V0_SCRGB:
1970 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001971 case Dataspace::DISPLAY_P3:
Chia-I Wu0607fbe2018-05-18 10:59:36 -07001972 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001973 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001974 case Dataspace::BT2020_PQ:
1975 case Dataspace::BT2020_ITU_PQ:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001976 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001977 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001978 case Dataspace::BT2020_HLG:
1979 case Dataspace::BT2020_ITU_HLG:
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001980 // When there's mixed PQ content and HLG content, we set the HDR
1981 // data space to be BT2020_PQ and convert HLG to PQ.
1982 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1983 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001984 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001985 break;
1986 default:
1987 break;
1988 }
Romain Guy54f154a2017-10-24 21:40:32 +01001989 }
1990
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001991 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001992}
1993
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001994// Pick the ColorMode / Dataspace for the display device.
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001995void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& displayDevice,
Peiyong Lind6fa4a72018-04-17 15:09:44 -07001996 ColorMode* outMode, Dataspace* outDataSpace,
1997 RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001998 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1999 *outMode = ColorMode::NATIVE;
2000 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002001 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002002 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002003 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002004
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002005 Dataspace hdrDataSpace;
2006 Dataspace bestDataSpace = getBestDataspace(displayDevice, &hdrDataSpace);
2007
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002008 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002009 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lin3c6b7ef2018-06-05 10:58:41 -07002010 !displayDevice->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002011 if (isHdr) {
2012 bestDataSpace = hdrDataSpace;
2013 }
2014
Chia-I Wu0d711262018-05-21 15:19:35 -07002015 RenderIntent intent;
2016 switch (mDisplayColorSetting) {
2017 case DisplayColorSetting::MANAGED:
2018 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002019 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002020 break;
2021 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002022 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002023 break;
2024 default: // vendor display color setting
2025 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2026 break;
2027 }
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002028
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002029 displayDevice->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002030}
2031
Mathias Agopiancd60f992012-08-16 16:28:27 -07002032void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002033 ATRACE_CALL();
2034 ALOGV("setUpHWComposer");
2035
Jesse Hall028dc8f2013-08-20 16:35:32 -07002036 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Dan Stozac7a25ad2018-04-12 11:45:09 -07002037 bool dirty = !mDisplays[dpy]->getDirtyRegion(mRepaintEverything).isEmpty();
Jesse Hallb7a05492014-08-14 15:45:06 -07002038 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
2039 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
2040
2041 // If nothing has changed (!dirty), don't recompose.
2042 // If something changed, but we don't currently have any visible layers,
2043 // and didn't when we last did a composition, then skip it this time.
2044 // The second rule does two things:
2045 // - When all layers are removed from a display, we'll emit one black
2046 // frame, then nothing more until we get new layers.
2047 // - When a display is created with a private layer stack, we won't
2048 // emit any black frames until a layer is added to the layer stack.
2049 bool mustRecompose = dirty && !(empty && wasEmpty);
2050
2051 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2052 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
2053 mustRecompose ? "doing" : "skipping",
2054 dirty ? "+" : "-",
2055 empty ? "+" : "-",
2056 wasEmpty ? "+" : "-");
2057
Dan Stoza71433162014-02-04 16:22:36 -08002058 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002059
2060 if (mustRecompose) {
2061 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
2062 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002063 }
2064
Dan Stoza9e56aa02015-11-02 13:00:03 -08002065 // build the h/w work list
2066 if (CC_UNLIKELY(mGeometryInvalid)) {
2067 mGeometryInvalid = false;
2068 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2069 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
2070 const auto hwcId = displayDevice->getHwcDisplayId();
2071 if (hwcId >= 0) {
2072 const Vector<sp<Layer>>& currentLayers(
2073 displayDevice->getVisibleLayersSortedByZ());
Robert Carrae060832016-11-28 10:51:00 -08002074 for (size_t i = 0; i < currentLayers.size(); i++) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002075 const auto& layer = currentLayers[i];
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 if (!layer->hasHwcLayer(hwcId)) {
David Sodman105b7dc2017-11-04 20:28:14 -07002077 if (!layer->createHwcLayer(getBE().mHwc.get(), hwcId)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 layer->forceClientComposition(hwcId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002079 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07002080 }
2081 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07002082
Robert Carrae060832016-11-28 10:51:00 -08002083 layer->setGeometry(displayDevice, i);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002084 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002085 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07002086 }
2087 }
2088 }
2089 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002090 }
Riley Andrews03414a12014-07-01 14:22:59 -07002091
Dan Stoza9e56aa02015-11-02 13:00:03 -08002092 // Set the per-frame data
2093 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2094 auto& displayDevice = mDisplays[displayId];
2095 const auto hwcId = displayDevice->getHwcDisplayId();
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002096
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 if (hwcId < 0) {
2098 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07002099 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07002100 if (mDrawingState.colorMatrixChanged) {
2101 displayDevice->setColorTransform(mDrawingState.colorMatrix);
2102 status_t result = getBE().mHwc->setColorTransform(hwcId, mDrawingState.colorMatrix);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002103 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
2104 "display %zd: %d", displayId, result);
2105 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002106 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu07376a92018-06-05 15:46:58 -07002107 if (layer->isHdrY410()) {
2108 layer->forceClientComposition(hwcId);
2109 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2110 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Peiyong Lin62665892018-04-16 11:07:44 -07002111 !displayDevice->hasHDR10Support()) {
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002112 layer->forceClientComposition(hwcId);
Chia-I Wu07376a92018-06-05 15:46:58 -07002113 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2114 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Peiyong Linf59a7192018-04-25 11:19:31 -07002115 !displayDevice->hasHLGSupport()) {
2116 layer->forceClientComposition(hwcId);
2117 }
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002118
chaviwc9232ed2017-11-14 15:31:15 -08002119 if (layer->getForceClientComposition(hwcId)) {
2120 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2121 layer->setCompositionType(hwcId, HWC2::Composition::Client);
2122 continue;
2123 }
2124
Dan Stoza9e56aa02015-11-02 13:00:03 -08002125 layer->setPerFrameData(displayDevice);
2126 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002127
2128 if (hasWideColorDisplay) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002129 ColorMode colorMode;
2130 Dataspace dataSpace;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002131 RenderIntent renderIntent;
2132 pickColorMode(displayDevice, &colorMode, &dataSpace, &renderIntent);
2133 setActiveColorModeInternal(displayDevice, colorMode, dataSpace, renderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002134 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002135 }
2136
Chia-I Wu28f320b2018-05-03 11:02:56 -07002137 mDrawingState.colorMatrixChanged = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002138
Dan Stoza9e56aa02015-11-02 13:00:03 -08002139 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002140 auto& displayDevice = mDisplays[displayId];
2141 if (!displayDevice->isDisplayOn()) {
2142 continue;
2143 }
2144
David Sodman105b7dc2017-11-04 20:28:14 -07002145 status_t result = displayDevice->prepareFrame(*getBE().mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002146 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
2147 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002148 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002149}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002150
Mathias Agopiancd60f992012-08-16 16:28:27 -07002151void SurfaceFlinger::doComposition() {
2152 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002153 ALOGV("doComposition");
2154
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002155 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002156 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002157 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002158 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002159 // transform the dirty region into this screen's coordinate space
2160 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002161
2162 // repaint the framebuffer (if needed)
2163 doDisplayComposition(hw, dirtyRegion);
2164
Mathias Agopiancd60f992012-08-16 16:28:27 -07002165 hw->dirtyRegion.clear();
Chia-I Wub02087d2017-11-09 10:19:54 -08002166 hw->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002167 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002168 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002169 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002170}
2171
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002172void SurfaceFlinger::postFramebuffer()
2173{
Mathias Agopian841cde52012-03-01 15:44:37 -08002174 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002176
Mathias Agopiana44b0412011-10-16 18:46:35 -07002177 const nsecs_t now = systemTime();
2178 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002179
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2181 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002182 if (!displayDevice->isDisplayOn()) {
2183 continue;
2184 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 const auto hwcId = displayDevice->getHwcDisplayId();
2186 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002187 getBE().mHwc->presentAndGetReleaseFences(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002188 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07002189 displayDevice->onSwapBuffersCompleted();
Chia-I Wu7f402902017-11-09 12:51:10 -08002190 displayDevice->makeCurrent();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002191 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Chia-I Wu99b46192018-06-21 15:52:50 +08002192 sp<Fence> releaseFence = Fence::NO_FENCE;
2193
Chia-I Wu7b549592017-11-15 09:14:57 -08002194 // The layer buffer from the previous frame (if any) is released
2195 // by HWC only when the release fence from this frame (if any) is
2196 // signaled. Always get the release fence from HWC first.
2197 auto hwcLayer = layer->getHwcLayer(hwcId);
Chia-I Wu99b46192018-06-21 15:52:50 +08002198 if (hwcId >= 0) {
2199 releaseFence = getBE().mHwc->getLayerReleaseFence(hwcId, hwcLayer);
2200 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002201
2202 // If the layer was client composited in the previous frame, we
2203 // need to merge with the previous client target acquire fence.
2204 // Since we do not track that, always merge with the current
2205 // client target acquire fence when it is available, even though
2206 // this is suboptimal.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002208 releaseFence = Fence::merge("LayerRelease", releaseFence,
2209 displayDevice->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002210 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002211
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 layer->onLayerDisplayed(releaseFence);
2213 }
Chia-I Wu83806892017-11-16 10:50:20 -08002214
2215 // We've got a list of layers needing fences, that are disjoint with
2216 // displayDevice->getVisibleLayersSortedByZ. The best we can do is to
2217 // supply them with the present fence.
2218 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
David Sodman105b7dc2017-11-04 20:28:14 -07002219 sp<Fence> presentFence = getBE().mHwc->getPresentFence(hwcId);
Chia-I Wu83806892017-11-16 10:50:20 -08002220 for (auto& layer : displayDevice->getLayersNeedingFences()) {
2221 layer->onLayerDisplayed(presentFence);
2222 }
2223 }
2224
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 if (hwcId >= 0) {
David Sodman105b7dc2017-11-04 20:28:14 -07002226 getBE().mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07002227 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002228 }
2229
Mathias Agopiana44b0412011-10-16 18:46:35 -07002230 mLastSwapBufferTime = systemTime() - now;
2231 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002232
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002233 // |mStateLock| not needed as we are on the main thread
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002234 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2235 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2236 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2237 logFrameStats();
2238 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002240}
2241
Mathias Agopian87baae12012-07-31 12:38:26 -07002242void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243{
Mathias Agopian841cde52012-03-01 15:44:37 -08002244 ATRACE_CALL();
2245
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002246 // here we keep a copy of the drawing state (that is the state that's
2247 // going to be overwritten by handleTransactionLocked()) outside of
2248 // mStateLock so that the side-effects of the State assignment
2249 // don't happen with mStateLock held (which can cause deadlocks).
2250 State drawingState(mDrawingState);
2251
Mathias Agopianca4d3602011-05-19 15:38:14 -07002252 Mutex::Autolock _l(mStateLock);
2253 const nsecs_t now = systemTime();
2254 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255
Mathias Agopianca4d3602011-05-19 15:38:14 -07002256 // Here we're guaranteed that some transaction flags are set
2257 // so we can call handleTransactionLocked() unconditionally.
2258 // We call getTransactionFlags(), which will also clear the flags,
2259 // with mStateLock held to guarantee that mCurrentState won't change
2260 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002261
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002262 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002263 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002264 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002265
Mathias Agopianca4d3602011-05-19 15:38:14 -07002266 mLastTransactionTime = systemTime() - now;
2267 mDebugInTransaction = 0;
2268 invalidateHwcGeometry();
2269 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002270}
2271
Lloyd Pique715a2c12017-12-14 17:18:08 -08002272DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t display,
Lloyd Pique09594832018-01-22 17:48:03 -08002273 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002274 // Figure out whether the event is for the primary display or an
2275 // external display by matching the Hwc display id against one for a
2276 // connected display. If we did not find a match, we then check what
2277 // displays are not already connected to determine the type. If we don't
2278 // have a connected primary display, we assume the new display is meant to
2279 // be the primary display, and then if we don't have an external display,
2280 // we assume it is that.
2281 const auto primaryDisplayId =
2282 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2283 const auto externalDisplayId =
2284 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
2285 if (primaryDisplayId && primaryDisplayId == display) {
2286 return DisplayDevice::DISPLAY_PRIMARY;
2287 } else if (externalDisplayId && externalDisplayId == display) {
2288 return DisplayDevice::DISPLAY_EXTERNAL;
2289 } else if (connection == HWC2::Connection::Connected && !primaryDisplayId) {
2290 return DisplayDevice::DISPLAY_PRIMARY;
2291 } else if (connection == HWC2::Connection::Connected && !externalDisplayId) {
2292 return DisplayDevice::DISPLAY_EXTERNAL;
2293 }
2294
2295 return DisplayDevice::DISPLAY_ID_INVALID;
2296}
2297
Lloyd Piqueba04e622017-12-14 17:11:26 -08002298void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2299 for (const auto& event : mPendingHotplugEvents) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002300 auto displayType = determineDisplayType(event.display, event.connection);
2301 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
2302 ALOGW("Unable to determine the display type for display %" PRIu64, event.display);
2303 continue;
2304 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002305
2306 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2307 ALOGE("External displays are not supported by the vr hardware composer.");
2308 continue;
2309 }
2310
Lloyd Pique715a2c12017-12-14 17:18:08 -08002311 getBE().mHwc->onHotplug(event.display, displayType, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002312
2313 if (event.connection == HWC2::Connection::Connected) {
Steven Thomas3bed0522018-03-20 15:40:48 -07002314 if (!mBuiltinDisplays[displayType].get()) {
2315 ALOGV("Creating built in display %d", displayType);
2316 mBuiltinDisplays[displayType] = new BBinder();
2317 // All non-virtual displays are currently considered secure.
2318 DisplayDeviceState info(displayType, true);
2319 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2320 "Built-in Screen" : "External Screen";
2321 mCurrentState.displays.add(mBuiltinDisplays[displayType], info);
Lloyd Pique4d234852018-01-22 17:21:36 -08002322 mInterceptor->saveDisplayCreation(info);
Steven Thomas3bed0522018-03-20 15:40:48 -07002323 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002324 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002325 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002326
Lloyd Piquefcd86612017-12-14 17:15:36 -08002327 ssize_t idx = mCurrentState.displays.indexOfKey(mBuiltinDisplays[displayType]);
2328 if (idx >= 0) {
2329 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Lloyd Pique4d234852018-01-22 17:21:36 -08002330 mInterceptor->saveDisplayDeletion(info.displayId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002331 mCurrentState.displays.removeItemsAt(idx);
2332 }
2333 mBuiltinDisplays[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002334 }
2335
2336 processDisplayChangesLocked();
2337 }
2338
2339 mPendingHotplugEvents.clear();
2340}
2341
Lloyd Pique09594832018-01-22 17:48:03 -08002342sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2343 const wp<IBinder>& display, int hwcId, const DisplayDeviceState& state,
2344 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345 bool hasWideColorGamut = false;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002346 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu99b46192018-06-21 15:52:50 +08002347 HdrCapabilities hdrCapabilities;
2348 int32_t supportedPerFrameMetadata = 0;
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002349
Chia-I Wu99b46192018-06-21 15:52:50 +08002350 if (hasWideColorDisplay && hwcId >= 0) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Lloyd Pique09594832018-01-22 17:48:03 -08002352 for (ColorMode colorMode : modes) {
2353 switch (colorMode) {
2354 case ColorMode::DISPLAY_P3:
2355 case ColorMode::ADOBE_RGB:
2356 case ColorMode::DCI_P3:
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 hasWideColorGamut = true;
Lloyd Pique09594832018-01-22 17:48:03 -08002358 break;
2359 default:
2360 break;
2361 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362
2363 std::vector<RenderIntent> renderIntents = getHwComposer().getRenderIntents(hwcId,
2364 colorMode);
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002365 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique09594832018-01-22 17:48:03 -08002366 }
2367 }
2368
Chia-I Wu99b46192018-06-21 15:52:50 +08002369 if (hwcId >= 0) {
2370 getHwComposer().getHdrCapabilities(hwcId, &hdrCapabilities);
2371 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(hwcId);
2372 }
Lloyd Pique09594832018-01-22 17:48:03 -08002373
2374 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2375 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2376
2377 /*
2378 * Create our display's surface
2379 */
2380 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2381 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
2382 renderSurface->setAsync(state.type >= DisplayDevice::DISPLAY_VIRTUAL);
2383 renderSurface->setNativeWindow(nativeWindow.get());
2384 const int displayWidth = renderSurface->queryWidth();
2385 const int displayHeight = renderSurface->queryHeight();
2386
2387 // Make sure that composition can never be stalled by a virtual display
2388 // consumer that isn't processing buffers fast enough. We have to do this
2389 // in two places:
2390 // * Here, in case the display is composed entirely by HWC.
2391 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2392 // window's swap interval in eglMakeCurrent, so they'll override the
2393 // interval we set here.
2394 if (state.type >= DisplayDevice::DISPLAY_VIRTUAL) {
2395 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2396 }
2397
2398 // virtual displays are always considered enabled
2399 auto initialPowerMode = (state.type >= DisplayDevice::DISPLAY_VIRTUAL) ? HWC_POWER_MODE_NORMAL
2400 : HWC_POWER_MODE_OFF;
2401
2402 sp<DisplayDevice> hw =
2403 new DisplayDevice(this, state.type, hwcId, state.isSecure, display, nativeWindow,
2404 dispSurface, std::move(renderSurface), displayWidth, displayHeight,
Peiyong Lin2c327ac2018-04-19 22:06:34 -07002405 hasWideColorGamut, hdrCapabilities,
Chia-I Wu99b46192018-06-21 15:52:50 +08002406 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique09594832018-01-22 17:48:03 -08002407
2408 if (maxFrameBufferAcquiredBuffers >= 3) {
2409 nativeWindowSurface->preallocateBuffers();
2410 }
2411
2412 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002413 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2414 if (hasWideColorGamut) {
Lloyd Pique09594832018-01-22 17:48:03 -08002415 defaultColorMode = ColorMode::SRGB;
Chia-I Wu0607fbe2018-05-18 10:59:36 -07002416 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique09594832018-01-22 17:48:03 -08002417 }
Peiyong Lind6fa4a72018-04-17 15:09:44 -07002418 setActiveColorModeInternal(hw, defaultColorMode, defaultDataSpace,
2419 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002420 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
2421 hw->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
2422 }
Lloyd Pique09594832018-01-22 17:48:03 -08002423 hw->setLayerStack(state.layerStack);
2424 hw->setProjection(state.orientation, state.viewport, state.frame);
2425 hw->setDisplayName(state.displayName);
2426
2427 return hw;
2428}
2429
Lloyd Pique347200f2017-12-14 17:00:15 -08002430void SurfaceFlinger::processDisplayChangesLocked() {
2431 // here we take advantage of Vector's copy-on-write semantics to
2432 // improve performance by skipping the transaction entirely when
2433 // know that the lists are identical
2434 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2435 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2436 if (!curr.isIdenticalTo(draw)) {
2437 mVisibleRegionsDirty = true;
2438 const size_t cc = curr.size();
2439 size_t dc = draw.size();
2440
2441 // find the displays that were removed
2442 // (ie: in drawing state but not in current state)
2443 // also handle displays that changed
2444 // (ie: displays that are in both lists)
2445 for (size_t i = 0; i < dc;) {
2446 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2447 if (j < 0) {
2448 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002449 // Call makeCurrent() on the primary display so we can
2450 // be sure that nothing associated with this display
2451 // is current.
2452 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
2453 if (defaultDisplay != nullptr) defaultDisplay->makeCurrent();
2454 sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
2455 if (hw != nullptr) hw->disconnect(getHwComposer());
2456 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
2457 mEventThread->onHotplugReceived(draw[i].type, false);
2458 mDisplays.removeItem(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002459 } else {
2460 // this display is in both lists. see if something changed.
2461 const DisplayDeviceState& state(curr[j]);
2462 const wp<IBinder>& display(curr.keyAt(j));
2463 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2464 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2465 if (state_binder != draw_binder) {
2466 // changing the surface is like destroying and
2467 // recreating the DisplayDevice, so we just remove it
2468 // from the drawing state, so that it get re-added
2469 // below.
2470 sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
2471 if (hw != nullptr) hw->disconnect(getHwComposer());
2472 mDisplays.removeItem(display);
2473 mDrawingState.displays.removeItemsAt(i);
2474 dc--;
2475 // at this point we must loop to the next item
2476 continue;
2477 }
2478
2479 const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
2480 if (disp != nullptr) {
2481 if (state.layerStack != draw[i].layerStack) {
2482 disp->setLayerStack(state.layerStack);
2483 }
2484 if ((state.orientation != draw[i].orientation) ||
2485 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2486 disp->setProjection(state.orientation, state.viewport, state.frame);
2487 }
2488 if (state.width != draw[i].width || state.height != draw[i].height) {
2489 disp->setDisplaySize(state.width, state.height);
2490 }
2491 }
2492 }
2493 ++i;
2494 }
2495
2496 // find displays that were added
2497 // (ie: in current state but not in drawing state)
2498 for (size_t i = 0; i < cc; i++) {
2499 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2500 const DisplayDeviceState& state(curr[i]);
2501
2502 sp<DisplaySurface> dispSurface;
2503 sp<IGraphicBufferProducer> producer;
2504 sp<IGraphicBufferProducer> bqProducer;
2505 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002506 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507
2508 int32_t hwcId = -1;
2509 if (state.isVirtualDisplay()) {
2510 // Virtual displays without a surface are dormant:
2511 // they have external state (layer stack, projection,
2512 // etc.) but no internal state (i.e. a DisplayDevice).
2513 if (state.surface != nullptr) {
2514 // Allow VR composer to use virtual displays.
2515 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2516 int width = 0;
2517 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2518 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2519 int height = 0;
2520 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2521 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2522 int intFormat = 0;
2523 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2524 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002525 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002526
2527 getBE().mHwc->allocateVirtualDisplay(width, height, &format, &hwcId);
2528 }
2529
2530 // TODO: Plumb requested format back up to consumer
2531
2532 sp<VirtualDisplaySurface> vds =
2533 new VirtualDisplaySurface(*getBE().mHwc, hwcId, state.surface,
2534 bqProducer, bqConsumer,
2535 state.displayName);
2536
2537 dispSurface = vds;
2538 producer = vds;
2539 }
2540 } else {
2541 ALOGE_IF(state.surface != nullptr,
2542 "adding a supported display, but rendering "
2543 "surface is provided (%p), ignoring it",
2544 state.surface.get());
2545
2546 hwcId = state.type;
2547 dispSurface = new FramebufferSurface(*getBE().mHwc, hwcId, bqConsumer);
2548 producer = bqProducer;
2549 }
2550
2551 const wp<IBinder>& display(curr.keyAt(i));
2552 if (dispSurface != nullptr) {
Lloyd Pique09594832018-01-22 17:48:03 -08002553 mDisplays.add(display,
2554 setupNewDisplayDeviceInternal(display, hwcId, state, dispSurface,
2555 producer));
Lloyd Pique347200f2017-12-14 17:00:15 -08002556 if (!state.isVirtualDisplay()) {
2557 mEventThread->onHotplugReceived(state.type, true);
2558 }
2559 }
2560 }
2561 }
2562 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002563
2564 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002565}
2566
Mathias Agopian87baae12012-07-31 12:38:26 -07002567void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002568{
Dan Stoza7dde5992015-05-22 09:51:44 -07002569 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002570 mCurrentState.traverseInZOrder([](Layer* layer) {
2571 layer->notifyAvailableFrames();
2572 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002573
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574 /*
2575 * Traversal of the children
2576 * (perform the transaction for each of them if needed)
2577 */
2578
Mathias Agopian3559b072012-08-15 13:46:03 -07002579 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002580 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002582 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
2584 const uint32_t flags = layer->doTransaction(0);
2585 if (flags & Layer::eVisibleRegion)
2586 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002587 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002588 }
2589
2590 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002591 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 */
2593
Mathias Agopiane57f2922012-08-09 16:29:12 -07002594 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002595 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002596 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002597 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002599 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002600 // The transform hint might have changed for some layers
2601 // (either because a display has changed, or because a layer
2602 // as changed).
2603 //
2604 // Walk through all the layers in currentLayers,
2605 // and update their transform hint.
2606 //
2607 // If a layer is visible only on a single display, then that
2608 // display is used to calculate the hint, otherwise we use the
2609 // default display.
2610 //
2611 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2612 // the hint is set before we acquire a buffer from the surface texture.
2613 //
2614 // NOTE: layer transactions have taken place already, so we use their
2615 // drawing state. However, SurfaceFlinger's own transaction has not
2616 // happened yet, so we must use the current state layer list
2617 // (soon to become the drawing state list).
2618 //
2619 sp<const DisplayDevice> disp;
2620 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002621 bool first = true;
2622 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002623 // NOTE: we rely on the fact that layers are sorted by
2624 // layerStack first (so we don't have to traverse the list
2625 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002626 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002627 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002628 currentlayerStack = layerStack;
2629 // figure out if this layerstack is mirrored
2630 // (more than one display) if so, pick the default display,
2631 // if not, pick the only display it's on.
2632 disp.clear();
2633 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2634 sp<const DisplayDevice> hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002635 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002636 if (disp == nullptr) {
George Burgess IV406a2852017-08-29 17:57:25 -07002637 disp = std::move(hw);
Mathias Agopian84300952012-11-21 16:02:13 -08002638 } else {
Peiyong Lin566a3b42018-01-09 18:22:43 -08002639 disp = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002640 break;
2641 }
2642 }
2643 }
2644 }
Chet Haase91d25932013-04-11 15:24:55 -07002645
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002646 if (disp == nullptr) {
2647 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2648 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002649
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002650 // could be null when this layer is using a layerStack
2651 // that is not visible on any display. Also can occur at
2652 // screen off/on times.
2653 disp = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002654 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002655
2656 // disp can be null if there is no display available at all to get
2657 // the transform hint from.
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002658 if (disp != nullptr) {
2659 layer->updateTransformHint(disp);
2660 }
Robert Carr2047fae2016-11-28 14:09:09 -08002661
2662 first = false;
2663 });
Mathias Agopian84300952012-11-21 16:02:13 -08002664 }
2665
2666
Mathias Agopian3559b072012-08-15 13:46:03 -07002667 /*
2668 * Perform our own transaction if needed
2669 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002670
2671 if (mLayersAdded) {
2672 mLayersAdded = false;
2673 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002674 mVisibleRegionsDirty = true;
2675 }
2676
2677 // some layers might have been removed, so
2678 // we need to update the regions they're exposing.
2679 if (mLayersRemoved) {
2680 mLayersRemoved = false;
2681 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002682 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002683 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002684 // this layer is not visible anymore
2685 // TODO: we could traverse the tree from front to back and
2686 // compute the actual visible region
2687 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002688 Region visibleReg;
2689 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002690 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002691 }
Robert Carr2047fae2016-11-28 14:09:09 -08002692 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002693 }
2694
2695 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002696
2697 updateCursorAsync();
2698}
2699
2700void SurfaceFlinger::updateCursorAsync()
2701{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002702 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
2703 auto& displayDevice = mDisplays[displayId];
2704 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002705 continue;
2706 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002707
2708 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2709 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07002710 }
2711 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712}
2713
2714void SurfaceFlinger::commitTransaction()
2715{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002716 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002718 for (const auto& l : mLayersPendingRemoval) {
2719 recordBufferingStats(l->getName().string(),
2720 l->getOccupancyHistory(true));
2721 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002722 }
2723 mLayersPendingRemoval.clear();
2724 }
2725
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002726 // If this transaction is part of a window animation then the next frame
2727 // we composite should be considered an animation as well.
2728 mAnimCompositionPending = mAnimTransactionPending;
2729
Mathias Agopian4fec8732012-06-29 14:12:52 -07002730 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002731 // clear the "changed" flags in current state
2732 mCurrentState.colorMatrixChanged = false;
2733
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 mDrawingState.traverseInZOrder([](Layer* layer) {
2735 layer->commitChildList();
2736 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002737 mTransactionPending = false;
2738 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740}
2741
Chia-I Wuab0c3192017-08-01 11:29:00 -07002742void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002743 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744{
Mathias Agopian841cde52012-03-01 15:44:37 -08002745 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002746 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002747
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002748 Region aboveOpaqueLayers;
2749 Region aboveCoveredLayers;
2750 Region dirty;
2751
Mathias Agopian87baae12012-07-31 12:38:26 -07002752 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753
Robert Carr2047fae2016-11-28 14:09:09 -08002754 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002756 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757
Jesse Hall01e29052013-02-19 16:13:35 -08002758 // only consider the layers on the given layer stack
Chia-I Wuab0c3192017-08-01 11:29:00 -07002759 if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
Robert Carr2047fae2016-11-28 14:09:09 -08002760 return;
Mathias Agopian87baae12012-07-31 12:38:26 -07002761
Mathias Agopianab028732010-03-16 16:41:46 -07002762 /*
2763 * opaqueRegion: area of a surface that is fully opaque.
2764 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002765 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002766
2767 /*
2768 * visibleRegion: area of a surface that is visible on screen
2769 * and not fully transparent. This is essentially the layer's
2770 * footprint minus the opaque regions above it.
2771 * Areas covered by a translucent surface are considered visible.
2772 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002774
2775 /*
2776 * coveredRegion: area of a surface that is covered by all
2777 * visible regions above it (which includes the translucent areas).
2778 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002780
Jesse Halla8026d22012-09-25 13:25:04 -07002781 /*
2782 * transparentRegion: area of a surface that is hinted to be completely
2783 * transparent. This is only used to tell when the layer has no visible
2784 * non-transparent regions and can be removed from the layer list. It
2785 * does not affect the visibleRegion of this layer or any layers
2786 * beneath it. The hint may not be correct if apps don't respect the
2787 * SurfaceView restrictions (which, sadly, some don't).
2788 */
2789 Region transparentRegion;
2790
Mathias Agopianab028732010-03-16 16:41:46 -07002791
2792 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002793 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002794 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002796 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002797 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002798 if (!visibleRegion.isEmpty()) {
2799 // Remove the transparent area from the visible region
2800 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002801 if (tr.preserveRects()) {
2802 // transform the transparent region
2803 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002804 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002805 // transformation too complex, can't do the
2806 // transparent region optimization.
2807 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002808 }
Mathias Agopianab028732010-03-16 16:41:46 -07002809 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810
Mathias Agopianab028732010-03-16 16:41:46 -07002811 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002812 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002813 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002814 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2815 // the opaque region is the layer's footprint
2816 opaqueRegion = visibleRegion;
2817 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 }
2819 }
2820
Robert Carre5f4f692018-01-12 13:12:28 -08002821 if (visibleRegion.isEmpty()) {
2822 layer->clearVisibilityRegions();
2823 return;
2824 }
2825
Mathias Agopianab028732010-03-16 16:41:46 -07002826 // Clip the covered region to the visible region
2827 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2828
2829 // Update aboveCoveredLayers for next (lower) layer
2830 aboveCoveredLayers.orSelf(visibleRegion);
2831
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 // subtract the opaque region covered by the layers above us
2833 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834
2835 // compute this layer's dirty region
2836 if (layer->contentDirty) {
2837 // we need to invalidate the whole region
2838 dirty = visibleRegion;
2839 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002840 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 layer->contentDirty = false;
2842 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002843 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002844 * the exposed region consists of two components:
2845 * 1) what's VISIBLE now and was COVERED before
2846 * 2) what's EXPOSED now less what was EXPOSED before
2847 *
2848 * note that (1) is conservative, we start with the whole
2849 * visible region but only keep what used to be covered by
2850 * something -- which mean it may have been exposed.
2851 *
2852 * (2) handles areas that were not covered by anything but got
2853 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002854 */
Mathias Agopianab028732010-03-16 16:41:46 -07002855 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002856 const Region oldVisibleRegion = layer->visibleRegion;
2857 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002858 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2859 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 }
2861 dirty.subtractSelf(aboveOpaqueLayers);
2862
2863 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002864 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865
Mathias Agopianab028732010-03-16 16:41:46 -07002866 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002868
Jesse Halla8026d22012-09-25 13:25:04 -07002869 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 layer->setVisibleRegion(visibleRegion);
2871 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002872 layer->setVisibleNonTransparentRegion(
2873 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002874 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875
Mathias Agopian87baae12012-07-31 12:38:26 -07002876 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877}
2878
Chia-I Wuab0c3192017-08-01 11:29:00 -07002879void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07002880 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07002881 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Chia-I Wuab0c3192017-08-01 11:29:00 -07002882 if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
Mathias Agopian42977342012-08-05 00:40:46 -07002883 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002884 }
2885 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002886}
2887
Dan Stoza6b9454d2014-11-07 16:00:59 -08002888bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002890 ALOGV("handlePageFlip");
2891
Brian Andersond6927fb2016-07-23 23:37:30 -07002892 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Mathias Agopian4fec8732012-06-29 14:12:52 -07002894 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002895 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002896 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002897
2898 // Store the set of layers that need updates. This set must not change as
2899 // buffers are being latched, as this could result in a deadlock.
2900 // Example: Two producers share the same command stream and:
2901 // 1.) Layer 0 is latched
2902 // 2.) Layer 0 gets a new frame
2903 // 2.) Layer 1 gets a new frame
2904 // 3.) Layer 1 is latched.
2905 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2906 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002907 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002908 if (layer->hasQueuedFrame()) {
2909 frameQueued = true;
2910 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002911 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002912 } else {
2913 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002914 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002915 } else {
2916 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002917 }
Robert Carr2047fae2016-11-28 14:09:09 -08002918 });
2919
Dan Stoza9e56aa02015-11-02 13:00:03 -08002920 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002921 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002922 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002923 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002924 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002925 newDataLatched = true;
2926 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002927 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002928
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002929 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002930
2931 // If we will need to wake up at some time in the future to deal with a
2932 // queued frame that shouldn't be displayed during this vsync period, wake
2933 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002934 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002935 signalLayerUpdate();
2936 }
2937
Chia-I Wuad8d8272018-06-26 10:18:18 +08002938 // enter boot animation on first buffer latch
2939 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2940 ALOGI("Enter boot animation");
2941 mBootStage = BootStage::BOOTANIMATION;
2942 }
2943
Dan Stoza6b9454d2014-11-07 16:00:59 -08002944 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002945 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946}
2947
Mathias Agopianad456f92011-01-13 17:53:01 -08002948void SurfaceFlinger::invalidateHwcGeometry()
2949{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002950 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002951}
2952
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002953
Fabien Sanglard830b8472016-11-30 16:35:58 -08002954void SurfaceFlinger::doDisplayComposition(
2955 const sp<const DisplayDevice>& displayDevice,
Mathias Agopian87baae12012-07-31 12:38:26 -07002956 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957{
Dan Stoza71433162014-02-04 16:22:36 -08002958 // We only need to actually compose the display if:
2959 // 1) It is being handled by hardware composer, which may need this to
2960 // keep its virtual display state machine in sync, or
2961 // 2) There is work to be done (the dirty region isn't empty)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002962 bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002963 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002964 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002965 return;
2966 }
2967
Dan Stoza9e56aa02015-11-02 13:00:03 -08002968 ALOGV("doDisplayComposition");
Chia-I Wub02087d2017-11-09 10:19:54 -08002969 if (!doComposeSurfaces(displayDevice)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002970
2971 // swap buffers (presentation)
Fabien Sanglard830b8472016-11-30 16:35:58 -08002972 displayDevice->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973}
2974
Chia-I Wub02087d2017-11-09 10:19:54 -08002975bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& displayDevice)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002976{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002978
Chia-I Wub02087d2017-11-09 10:19:54 -08002979 const Region bounds(displayDevice->bounds());
chaviwa76b2712017-09-20 12:02:26 -07002980 const DisplayRenderArea renderArea(displayDevice);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002981 const auto hwcId = displayDevice->getHwcDisplayId();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002982 const bool hasClientComposition = getBE().mHwc->hasClientComposition(hwcId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002983 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002984
Chia-I Wu8e50e692018-05-04 10:12:37 -07002985 bool applyColorMatrix = false;
Chia-I Wu6d844112018-06-27 07:17:41 +08002986 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002987
Dan Stoza9e56aa02015-11-02 13:00:03 -08002988 if (hasClientComposition) {
2989 ALOGV("hasClientComposition");
2990
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002991 Dataspace outputDataspace = Dataspace::UNKNOWN;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002992 if (displayDevice->hasWideColorGamut()) {
2993 outputDataspace = displayDevice->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002994 }
2995 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002996 getBE().mRenderEngine->setDisplayMaxLuminance(
2997 displayDevice->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002998
Chia-I Wu8e50e692018-05-04 10:12:37 -07002999 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(hwcId);
3000 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3001 HWC2::Capability::SkipClientColorTransform);
3002
Chia-I Wu6d844112018-06-27 07:17:41 +08003003 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003004 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3005 if (applyColorMatrix) {
Chia-I Wu6d844112018-06-27 07:17:41 +08003006 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003007 }
3008
Chia-I Wu6d844112018-06-27 07:17:41 +08003009 // The current enhanced saturation matrix is designed to enhance Display P3,
3010 // thus we only apply this matrix when the render intent is not colorimetric
3011 // and the output color space is Display P3.
3012 needsEnhancedColorMatrix =
Chia-I Wu0d711262018-05-21 15:19:35 -07003013 (displayDevice->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
Chia-I Wu6d844112018-06-27 07:17:41 +08003014 outputDataspace == Dataspace::DISPLAY_P3);
3015 if (needsEnhancedColorMatrix) {
3016 colorMatrix *= mEnhancedSaturationMatrix;
3017 }
3018
3019 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003020
Chia-I Wu7f402902017-11-09 12:51:10 -08003021 if (!displayDevice->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003022 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003023 displayDevice->getDisplayName().string());
Chia-I Wu7f402902017-11-09 12:51:10 -08003024 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003025
3026 // |mStateLock| not needed as we are on the main thread
Chia-I Wu7f402902017-11-09 12:51:10 -08003027 if(!getDefaultDisplayDeviceLocked()->makeCurrent()) {
Michael Lentine3f121fc2014-10-01 11:17:28 -07003028 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
3029 }
3030 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003031 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003032
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003033 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003034 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003035 // when using overlays, we assume a fully transparent framebuffer
3036 // NOTE: we could reduce how much we need to clear, for instance
3037 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003038 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003039 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003040 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003041 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003042 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003043 // we're left with the letterbox region
3044 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003045 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07003046
3047 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07003049
Mathias Agopianb9494d52012-04-18 02:28:45 -07003050 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003051 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003052 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08003053 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003054 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003055 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003056
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003057 const Rect& bounds(displayDevice->getBounds());
3058 const Rect& scissor(displayDevice->getScissor());
3059 if (scissor != bounds) {
3060 // scissor doesn't match the screen's dimensions, so we
3061 // need to clear everything outside of it and enable
3062 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003063
Yiwei Zhangcf39b7b2018-08-22 13:59:12 -07003064 // enable scissor for this frame
3065 const uint32_t height = displayDevice->getHeight();
3066 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3067 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003068 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003069 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003070
Mathias Agopian85d751c2012-08-29 16:59:24 -07003071 /*
3072 * and then, render the layers targeted at the framebuffer
3073 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003074
Dan Stoza9e56aa02015-11-02 13:00:03 -08003075 ALOGV("Rendering client layers");
3076 const Transform& displayTransform = displayDevice->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003077 bool firstLayer = true;
3078 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3079 const Region clip(bounds.intersect(
3080 displayTransform.transform(layer->visibleRegion)));
3081 ALOGV("Layer: %s", layer->getName().string());
3082 ALOGV(" Composition type: %s",
3083 to_string(layer->getCompositionType(hwcId)).c_str());
3084 if (!clip.isEmpty()) {
3085 switch (layer->getCompositionType(hwcId)) {
3086 case HWC2::Composition::Cursor:
3087 case HWC2::Composition::Device:
3088 case HWC2::Composition::Sideband:
3089 case HWC2::Composition::SolidColor: {
3090 const Layer::State& state(layer->getDrawingState());
3091 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
3092 layer->isOpaque(state) && (state.color.a == 1.0f)
3093 && hasClientComposition) {
3094 // never clear the very first layer since we're
3095 // guaranteed the FB is already cleared
3096 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003097 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003098 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003099 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003100 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003101 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003102 break;
3103 }
3104 default:
3105 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003106 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003107 } else {
3108 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003109 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003110 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003111 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003112
Chia-I Wu6d844112018-06-27 07:17:41 +08003113 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003114 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003115 }
3116
Mathias Agopianf45c5102012-10-24 16:29:17 -07003117 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003118 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003119 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003120}
3121
Fabien Sanglard830b8472016-11-30 16:35:58 -08003122void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
3123 const int32_t height = displayDevice->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003124 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003125 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003126}
3127
Dan Stoza7d89d062015-04-30 13:29:25 -07003128status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003129 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003130 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003131 const sp<Layer>& lbc,
3132 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003133{
Dan Stoza7d89d062015-04-30 13:29:25 -07003134 // add this layer to the current state list
3135 {
3136 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003138 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3139 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003140 return NO_MEMORY;
3141 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003142 if (parent == nullptr) {
3143 mCurrentState.layersSortedByZ.add(lbc);
3144 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003145 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003146 ALOGE("addClientLayer called with a removed parent");
3147 return NAME_NOT_FOUND;
3148 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003149 parent->addChild(lbc);
3150 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003151
Yiwei Zhang243b3782018-05-15 17:40:04 -07003152 if (gbc != nullptr) {
3153 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3154 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3155 mMaxGraphicBufferProducerListSize,
3156 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3157 mGraphicBufferProducerList.size(),
3158 mMaxGraphicBufferProducerListSize, mNumLayers);
3159 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003160 mLayersAdded = true;
3161 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003162 }
3163
Mathias Agopian96f08192010-06-02 23:28:45 -07003164 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003165 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003166
Dan Stoza7d89d062015-04-30 13:29:25 -07003167 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003168}
3169
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003170status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003171 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003172 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3173}
Robert Carr7f9b8992017-03-10 11:08:39 -08003174
chaviwca27f252018-02-06 16:46:39 -08003175status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3176 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003177 if (layer->isPendingRemoval()) {
3178 return NO_ERROR;
3179 }
3180
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003182 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003183 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003184 if (topLevelOnly) {
3185 return NO_ERROR;
3186 }
3187
Chia-I Wu98f1c102017-05-30 14:54:08 -07003188 sp<Layer> ancestor = p;
3189 while (ancestor->getParent() != nullptr) {
3190 ancestor = ancestor->getParent();
3191 }
3192 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3193 ALOGE("removeLayer called with a layer whose parent has been removed");
3194 return NAME_NOT_FOUND;
3195 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003196
3197 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003198 } else {
3199 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003200 }
3201
Robert Carr136e2f62017-02-08 17:54:29 -08003202 // As a matter of normal operation, the LayerCleaner will produce a second
3203 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3204 // so we will succeed in promoting it, but it's already been removed
3205 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3206 // otherwise something has gone wrong and we are leaking the layer.
3207 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003208 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3209 layer->getName().string(),
3210 (p != nullptr) ? p->getName().string() : "no-parent");
3211 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003212 } else if (index < 0) {
3213 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003214 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003215
Chia-I Wuc6657022017-08-15 11:18:17 -07003216 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003217 mLayersPendingRemoval.add(layer);
3218 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003219 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 setTransactionFlags(eTransactionNeeded);
3221 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222}
3223
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003224uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003225 return android_atomic_release_load(&mTransactionFlags);
3226}
3227
Mathias Agopian3f844832013-08-07 21:24:32 -07003228uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3230}
3231
Mathias Agopian3f844832013-08-07 21:24:32 -07003232uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza2713c302018-03-28 17:07:36 -07003233 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3234}
3235
3236uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3237 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza2713c302018-03-28 17:07:36 -07003239 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003241 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242 }
3243 return old;
3244}
3245
chaviwca27f252018-02-06 16:46:39 -08003246bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3247 for (const ComposerState& state : states) {
3248 // Here we need to check that the interface we're given is indeed
3249 // one of our own. A malicious client could give us a nullptr
3250 // IInterface, or one of its own or even one of our own but a
3251 // different type. All these situations would cause us to crash.
3252 if (state.client == nullptr) {
3253 return true;
3254 }
3255
3256 sp<IBinder> binder = IInterface::asBinder(state.client);
3257 if (binder == nullptr) {
3258 return true;
3259 }
3260
3261 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3262 return true;
3263 }
3264 }
3265 return false;
3266}
3267
Mathias Agopian8b33f032012-07-24 20:43:54 -07003268void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003269 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003270 const Vector<DisplayState>& displays,
3271 uint32_t flags)
3272{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003273 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003274 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003275 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003276
chaviwca27f252018-02-06 16:46:39 -08003277 if (containsAnyInvalidClientState(states)) {
3278 return;
3279 }
3280
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003281 if (flags & eAnimation) {
3282 // For window updates that are part of an animation we must wait for
3283 // previous animation "frames" to be handled.
3284 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003285 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003286 if (CC_UNLIKELY(err != NO_ERROR)) {
3287 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003288 // caller after a few seconds.
3289 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3290 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003291 mAnimTransactionPending = false;
3292 break;
3293 }
3294 }
3295 }
3296
chaviwca27f252018-02-06 16:46:39 -08003297 for (const DisplayState& display : displays) {
3298 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003299 }
3300
chaviwca27f252018-02-06 16:46:39 -08003301 for (const ComposerState& state : states) {
3302 transactionFlags |= setClientStateLocked(state);
3303 }
3304
3305 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3306 // as destroyed should only occur after setting all other states. This is to allow for a
3307 // child re-parent to happen before marking its original parent as destroyed (which would
3308 // then mark the child as destroyed).
3309 for (const ComposerState& state : states) {
3310 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003311 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003312
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003313 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3314 // anyway. This can be used as a flush mechanism for previous async transactions.
3315 // Empty animation transaction can be used to simulate back-pressure, so also force a
3316 // transaction for empty animation transactions.
3317 if (transactionFlags == 0 &&
3318 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003319 transactionFlags = eTransactionNeeded;
3320 }
3321
Mathias Agopian386aa982011-11-07 21:58:03 -08003322 if (transactionFlags) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003323 if (mInterceptor->isEnabled()) {
3324 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003325 }
Irvel468051e2016-06-13 16:44:44 -07003326
Mathias Agopian386aa982011-11-07 21:58:03 -08003327 // this triggers the transaction
Dan Stoza2713c302018-03-28 17:07:36 -07003328 const auto start = (flags & eEarlyWakeup)
3329 ? VSyncModulator::TransactionStart::EARLY
3330 : VSyncModulator::TransactionStart::NORMAL;
3331 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003332
3333 // if this is a synchronous transaction, wait for it to take effect
3334 // before returning.
3335 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003336 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003337 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003338 if (flags & eAnimation) {
3339 mAnimTransactionPending = true;
3340 }
3341 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003342 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3343 if (CC_UNLIKELY(err != NO_ERROR)) {
3344 // just in case something goes wrong in SF, return to the
3345 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003346 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3347 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003348 break;
3349 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003350 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003351 }
3352}
3353
Mathias Agopiane57f2922012-08-09 16:29:12 -07003354uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
3355{
Jesse Hall9a143922012-10-04 16:29:19 -07003356 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
3357 if (dpyIdx < 0)
3358 return 0;
3359
Mathias Agopiane57f2922012-08-09 16:29:12 -07003360 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003361 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003362 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 const uint32_t what = s.what;
3364 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003365 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003366 disp.surface = s.surface;
3367 flags |= eDisplayTransactionNeeded;
3368 }
3369 }
3370 if (what & DisplayState::eLayerStackChanged) {
3371 if (disp.layerStack != s.layerStack) {
3372 disp.layerStack = s.layerStack;
3373 flags |= eDisplayTransactionNeeded;
3374 }
3375 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07003376 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003377 if (disp.orientation != s.orientation) {
3378 disp.orientation = s.orientation;
3379 flags |= eDisplayTransactionNeeded;
3380 }
3381 if (disp.frame != s.frame) {
3382 disp.frame = s.frame;
3383 flags |= eDisplayTransactionNeeded;
3384 }
3385 if (disp.viewport != s.viewport) {
3386 disp.viewport = s.viewport;
3387 flags |= eDisplayTransactionNeeded;
3388 }
3389 }
Michael Lentine47e45402014-07-18 15:34:25 -07003390 if (what & DisplayState::eDisplaySizeChanged) {
3391 if (disp.width != s.width) {
3392 disp.width = s.width;
3393 flags |= eDisplayTransactionNeeded;
3394 }
3395 if (disp.height != s.height) {
3396 disp.height = s.height;
3397 flags |= eDisplayTransactionNeeded;
3398 }
3399 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003400 }
3401 return flags;
3402}
3403
Robert Carrd4ae7f32018-06-07 16:10:57 -07003404bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3405 IPCThreadState* ipc = IPCThreadState::self();
3406 const int pid = ipc->getCallingPid();
3407 const int uid = ipc->getCallingUid();
3408
3409 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3410 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3411 return false;
3412 }
3413 return true;
3414}
3415
chaviwca27f252018-02-06 16:46:39 -08003416uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3417 const layer_state_t& s = composerState.state;
3418 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3419
Mathias Agopian13127d82013-03-05 17:47:11 -08003420 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003421 if (layer == nullptr) {
3422 return 0;
3423 }
3424
3425 if (layer->isPendingRemoval()) {
3426 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3427 return 0;
3428 }
3429
3430 uint32_t flags = 0;
3431
3432 const uint32_t what = s.what;
3433 bool geometryAppliesWithResize =
3434 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003435
3436 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3437 // pending state will also be deferred.
3438 if (what & layer_state_t::eDeferTransaction) {
3439 layer->pushPendingState();
3440 }
3441
chaviw8b3871a2017-11-01 17:41:01 -07003442 if (what & layer_state_t::ePositionChanged) {
3443 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3444 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003445 }
chaviw8b3871a2017-11-01 17:41:01 -07003446 }
3447 if (what & layer_state_t::eLayerChanged) {
3448 // NOTE: index needs to be calculated before we update the state
3449 const auto& p = layer->getParent();
3450 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003451 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003452 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003453 mCurrentState.layersSortedByZ.removeAt(idx);
3454 mCurrentState.layersSortedByZ.add(layer);
3455 // we need traversal (state changed)
3456 // AND transaction (list changed)
3457 flags |= eTransactionNeeded|eTraversalNeeded;
3458 }
chaviw8b3871a2017-11-01 17:41:01 -07003459 } else {
3460 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003461 flags |= eTransactionNeeded|eTraversalNeeded;
3462 }
3463 }
chaviw8b3871a2017-11-01 17:41:01 -07003464 }
3465 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003466 // NOTE: index needs to be calculated before we update the state
3467 const auto& p = layer->getParent();
3468 if (p == nullptr) {
3469 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3470 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3471 mCurrentState.layersSortedByZ.removeAt(idx);
3472 mCurrentState.layersSortedByZ.add(layer);
3473 // we need traversal (state changed)
3474 // AND transaction (list changed)
3475 flags |= eTransactionNeeded|eTraversalNeeded;
3476 }
3477 } else {
3478 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3479 flags |= eTransactionNeeded|eTraversalNeeded;
3480 }
chaviw8b3871a2017-11-01 17:41:01 -07003481 }
3482 }
3483 if (what & layer_state_t::eSizeChanged) {
3484 if (layer->setSize(s.w, s.h)) {
3485 flags |= eTraversalNeeded;
3486 }
3487 }
3488 if (what & layer_state_t::eAlphaChanged) {
3489 if (layer->setAlpha(s.alpha))
3490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eColorChanged) {
3493 if (layer->setColor(s.color))
3494 flags |= eTraversalNeeded;
3495 }
3496 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003497 // TODO: b/109894387
3498 //
3499 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3500 // rotation. To see the problem observe that if we have a square parent, and a child
3501 // of the same size, then we rotate the child 45 degrees around it's center, the child
3502 // must now be cropped to a non rectangular 8 sided region.
3503 //
3504 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3505 // private API, and the WindowManager only uses rotation in one case, which is on a top
3506 // level layer in which cropping is not an issue.
3507 //
3508 // However given that abuse of rotation matrices could lead to surfaces extending outside
3509 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3510 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3511 // transformations.
3512 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003513 flags |= eTraversalNeeded;
3514 }
3515 if (what & layer_state_t::eTransparentRegionChanged) {
3516 if (layer->setTransparentRegionHint(s.transparentRegion))
3517 flags |= eTraversalNeeded;
3518 }
3519 if (what & layer_state_t::eFlagsChanged) {
3520 if (layer->setFlags(s.flags, s.mask))
3521 flags |= eTraversalNeeded;
3522 }
3523 if (what & layer_state_t::eCropChanged) {
3524 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3525 flags |= eTraversalNeeded;
3526 }
3527 if (what & layer_state_t::eFinalCropChanged) {
3528 if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3529 flags |= eTraversalNeeded;
3530 }
3531 if (what & layer_state_t::eLayerStackChanged) {
3532 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3533 // We only allow setting layer stacks for top level layers,
3534 // everything else inherits layer stack from its parent.
3535 if (layer->hasParent()) {
3536 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3537 layer->getName().string());
3538 } else if (idx < 0) {
3539 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3540 "that also does not appear in the top level layer list. Something"
3541 " has gone wrong.", layer->getName().string());
3542 } else if (layer->setLayerStack(s.layerStack)) {
3543 mCurrentState.layersSortedByZ.removeAt(idx);
3544 mCurrentState.layersSortedByZ.add(layer);
3545 // we need traversal (state changed)
3546 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003547 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003548 }
3549 }
3550 if (what & layer_state_t::eDeferTransaction) {
3551 if (s.barrierHandle != nullptr) {
3552 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3553 } else if (s.barrierGbp != nullptr) {
3554 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3555 if (authenticateSurfaceTextureLocked(gbp)) {
3556 const auto& otherLayer =
3557 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3558 layer->deferTransactionUntil(otherLayer, s.frameNumber);
3559 } else {
3560 ALOGE("Attempt to defer transaction to to an"
3561 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003562 }
3563 }
chaviw8b3871a2017-11-01 17:41:01 -07003564 // We don't trigger a traversal here because if no other state is
3565 // changed, we don't want this to cause any more work
3566 }
3567 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003568 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003569 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003570 if (!hadParent) {
3571 mCurrentState.layersSortedByZ.remove(layer);
3572 }
chaviw8b3871a2017-11-01 17:41:01 -07003573 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003574 }
chaviw8b3871a2017-11-01 17:41:01 -07003575 }
3576 if (what & layer_state_t::eReparentChildren) {
3577 if (layer->reparentChildren(s.reparentHandle)) {
3578 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003579 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003580 }
chaviw8b3871a2017-11-01 17:41:01 -07003581 if (what & layer_state_t::eDetachChildren) {
3582 layer->detachChildren();
3583 }
3584 if (what & layer_state_t::eOverrideScalingModeChanged) {
3585 layer->setOverrideScalingMode(s.overrideScalingMode);
3586 // We don't trigger a traversal here because if no other state is
3587 // changed, we don't want this to cause any more work
3588 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003589 return flags;
3590}
3591
chaviwca27f252018-02-06 16:46:39 -08003592void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3593 const layer_state_t& state = composerState.state;
3594 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3595
3596 sp<Layer> layer(client->getLayerUser(state.surface));
3597 if (layer == nullptr) {
3598 return;
3599 }
3600
3601 if (layer->isPendingRemoval()) {
3602 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3603 return;
3604 }
3605
3606 if (state.what & layer_state_t::eDestroySurface) {
3607 removeLayerLocked(mStateLock, layer);
3608 }
3609}
3610
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003611status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003612 const String8& name,
3613 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliuccd34842018-03-14 12:26:23 -07003615 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003616 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003617{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003618 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003619 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003620 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003621 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003622 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003623
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 status_t result = NO_ERROR;
3625
3626 sp<Layer> layer;
3627
Cody Northropbc755282017-03-31 12:00:08 -06003628 String8 uniqueName = getUniqueLayerName(name);
3629
Mathias Agopian3165cc22012-08-08 19:42:09 -07003630 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3631 case ISurfaceComposerClient::eFXSurfaceNormal:
David Sodman0c69cad2017-08-21 12:12:51 -07003632 result = createBufferLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003633 uniqueName, w, h, flags, format,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003634 handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 break;
chaviw13fdc492017-06-27 12:40:18 -07003637 case ISurfaceComposerClient::eFXSurfaceColor:
3638 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003639 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003640 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003641 break;
Robert Carrd6f70352018-08-13 13:05:17 -07003642 case ISurfaceComposerClient::eFXSurfaceContainer:
3643 result = createContainerLayer(client,
3644 uniqueName, w, h, flags,
3645 handle, &layer);
3646 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003647 default:
3648 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003649 break;
3650 }
3651
Dan Stoza7d89d062015-04-30 13:29:25 -07003652 if (result != NO_ERROR) {
3653 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003655
Chia-I Wuab0c3192017-08-01 11:29:00 -07003656 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3657 // TODO b/64227542
3658 if (windowType == 441731) {
3659 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3660 layer->setPrimaryDisplayOnly();
3661 }
3662
Albert Chaulk479c60c2017-01-27 14:21:34 -05003663 layer->setInfo(windowType, ownerUid);
3664
Robert Carr1f0a16a2016-10-24 16:27:39 -07003665 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003666 if (result != NO_ERROR) {
3667 return result;
3668 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003669 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003670
3671 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003673}
3674
Cody Northropbc755282017-03-31 12:00:08 -06003675String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3676{
3677 bool matchFound = true;
3678 uint32_t dupeCounter = 0;
3679
3680 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3681 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3682
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003683 // Grab the state lock since we're accessing mCurrentState
3684 Mutex::Autolock lock(mStateLock);
3685
Cody Northropbc755282017-03-31 12:00:08 -06003686 // Loop over layers until we're sure there is no matching name
3687 while (matchFound) {
3688 matchFound = false;
Dan Stoza9fdb7e02018-06-21 12:10:12 -07003689 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003690 if (layer->getName() == uniqueName) {
3691 matchFound = true;
3692 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3693 }
3694 });
3695 }
3696
3697 ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3698
3699 return uniqueName;
3700}
3701
David Sodman0c69cad2017-08-21 12:12:51 -07003702status_t SurfaceFlinger::createBufferLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003703 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3704 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705{
3706 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003707 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708 case PIXEL_FORMAT_TRANSPARENT:
3709 case PIXEL_FORMAT_TRANSLUCENT:
3710 format = PIXEL_FORMAT_RGBA_8888;
3711 break;
3712 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003713 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 break;
3715 }
3716
David Sodman0c69cad2017-08-21 12:12:51 -07003717 sp<BufferLayer> layer = new BufferLayer(this, client, name, w, h, flags);
3718 status_t err = layer->setBuffers(w, h, format, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003719 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003720 *handle = layer->getHandle();
3721 *gbp = layer->getProducer();
3722 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003723 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003724
David Sodman0c69cad2017-08-21 12:12:51 -07003725 ALOGE_IF(err, "createBufferLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727}
3728
chaviw13fdc492017-06-27 12:40:18 -07003729status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003730 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003731 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732{
chaviw13fdc492017-06-27 12:40:18 -07003733 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003734 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003736}
3737
Robert Carrd6f70352018-08-13 13:05:17 -07003738status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3739 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3740 sp<IBinder>* handle, sp<Layer>* outLayer)
3741{
3742 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3743 *handle = (*outLayer)->getHandle();
3744 return NO_ERROR;
3745}
3746
3747
Mathias Agopianac9fa422013-02-11 16:40:36 -08003748status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003749{
Robert Carr9524cb32017-02-13 11:32:32 -08003750 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003751 status_t err = NO_ERROR;
3752 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003753 if (l != nullptr) {
Lloyd Pique4d234852018-01-22 17:21:36 -08003754 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003755 err = removeLayer(l);
3756 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3757 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003758 }
3759 return err;
3760}
3761
Mathias Agopian13127d82013-03-05 17:47:11 -08003762status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003763{
Mathias Agopian67106042013-03-14 19:18:13 -07003764 // called by ~LayerCleaner() when all references to the IBinder (handle)
3765 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003766 sp<Layer> l = layer.promote();
3767 if (l == nullptr) {
3768 // The layer has already been removed, carry on
3769 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003770 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003771 // If we have a parent, then we can continue to live as long as it does.
3772 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773}
3774
Mathias Agopianb60314a2012-04-10 22:09:54 -07003775// ---------------------------------------------------------------------------
3776
Andy McFadden13a082e2012-08-24 10:16:42 -07003777void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08003778 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003779 Vector<ComposerState> state;
3780 Vector<DisplayState> displays;
3781 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003782 d.what = DisplayState::eDisplayProjectionChanged |
3783 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08003784 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08003785 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003786 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003787 d.frame.makeInvalid();
3788 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003789 d.width = 0;
3790 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003791 displays.add(d);
3792 setTransactionState(state, displays, 0);
Steven Thomasb02664d2017-07-26 18:48:28 -07003793 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3794 /*stateLockHeld*/ false);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003795
David Sodman105b7dc2017-11-04 20:28:14 -07003796 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003797 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003798 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003799
Brian Andersond0010582017-03-07 13:20:31 -08003800 // Use phase of 0 since phase is not known.
3801 // Use latency of 0, which will snap to the ideal latency.
3802 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003803}
3804
3805void SurfaceFlinger::initializeDisplays() {
3806 class MessageScreenInitialized : public MessageBase {
3807 SurfaceFlinger* flinger;
3808 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003809 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07003810 virtual bool handler() {
3811 flinger->onInitializeDisplays();
3812 return true;
3813 }
3814 };
3815 sp<MessageBase> msg = new MessageScreenInitialized(this);
3816 postMessageAsync(msg); // we may be called from main thread, use async message
3817}
3818
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003819void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
Steven Thomasb02664d2017-07-26 18:48:28 -07003820 int mode, bool stateLockHeld) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003821 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3822 this);
3823 int32_t type = hw->getDisplayType();
3824 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07003825
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003826 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003827 return;
3828 }
3829
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003830 hw->setPowerMode(mode);
3831 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3832 ALOGW("Trying to set power mode for virtual display");
3833 return;
3834 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003835
Lloyd Pique4d234852018-01-22 17:21:36 -08003836 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003837 ConditionalLock lock(mStateLock, !stateLockHeld);
Irvelffc9efc2016-07-27 15:16:37 -07003838 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3839 if (idx < 0) {
3840 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3841 return;
3842 }
Lloyd Pique4d234852018-01-22 17:21:36 -08003843 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003844 }
3845
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003847 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003848 getHwComposer().setPowerMode(type, mode);
Matthew Bouyack38d49612017-05-12 12:49:32 -07003849 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3850 mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003851 // FIXME: eventthread only knows about the main display right now
3852 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003853 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003854 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003856 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003857 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003858 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003859
3860 struct sched_param param = {0};
3861 param.sched_priority = 1;
3862 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3863 ALOGW("Couldn't set SCHED_FIFO on display on");
3864 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003865 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003866 // Turn off the display
3867 struct sched_param param = {0};
3868 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3869 ALOGW("Couldn't set SCHED_OTHER on display off");
3870 }
3871
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003872 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3873 currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003874 disableHardwareVsync(true); // also cancels any in-progress resync
3875
Mathias Agopiancde87a32012-09-13 14:09:01 -07003876 // FIXME: eventthread only knows about the main display right now
3877 mEventThread->onScreenReleased();
3878 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003879
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003880 getHwComposer().setPowerMode(type, mode);
3881 mVisibleRegionsDirty = true;
3882 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003883 } else if (mode == HWC_POWER_MODE_DOZE ||
3884 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003885 // Update display while dozing
3886 getHwComposer().setPowerMode(type, mode);
Matthew Bouyackcd9b55c2017-06-01 14:37:29 -07003887 if (type == DisplayDevice::DISPLAY_PRIMARY &&
3888 currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003889 // FIXME: eventthread only knows about the main display right now
3890 mEventThread->onScreenAcquired();
3891 resyncToHardwareVsync(true);
3892 }
3893 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3894 // Leave display going to doze
3895 if (type == DisplayDevice::DISPLAY_PRIMARY) {
3896 disableHardwareVsync(true); // also cancels any in-progress resync
3897 // FIXME: eventthread only knows about the main display right now
3898 mEventThread->onScreenReleased();
3899 }
3900 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003901 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003902 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003903 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003904 }
Alice Sheng05ee4c92018-03-27 15:03:10 -07003905 ALOGD("Finished set power mode=%d, type=%d", mode, hw->getDisplayType());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003906}
3907
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003908void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3909 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003910 SurfaceFlinger& mFlinger;
3911 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003912 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003913 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003914 MessageSetPowerMode(SurfaceFlinger& flinger,
3915 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3916 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003917 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003918 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003919 if (hw == nullptr) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003920 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07003921 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07003922 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003923 ALOGW("Attempt to set power mode = %d for virtual display",
3924 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003925 } else {
Steven Thomasb02664d2017-07-26 18:48:28 -07003926 mFlinger.setPowerModeInternal(
3927 hw, mMode, /*stateLockHeld*/ false);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003928 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003929 return true;
3930 }
3931 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003932 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003933 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07003934}
3935
3936// ---------------------------------------------------------------------------
3937
Lloyd Pique755e3192018-01-31 16:46:15 -08003938status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3939 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003940 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003941
Mathias Agopianbd115332013-04-18 16:41:04 -07003942 IPCThreadState* ipc = IPCThreadState::self();
3943 const int pid = ipc->getCallingPid();
3944 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003945
Mathias Agopianbd115332013-04-18 16:41:04 -07003946 if ((uid != AID_SHELL) &&
3947 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003948 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003949 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003950 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003951 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003952 // (this would indicate SF is stuck, but we want to be able to
3953 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003954 status_t err = mStateLock.timedLock(s2ns(1));
3955 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003956 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003957 result.appendFormat(
3958 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3959 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003960 }
3961
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003962 bool dumpAll = true;
3963 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003965
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003966 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003967 if ((index < numArgs) &&
3968 (args[index] == String16("--list"))) {
3969 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003970 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003971 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003972 }
3973
3974 if ((index < numArgs) &&
3975 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003976 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003977 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003978 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003979 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003980
3981 if ((index < numArgs) &&
3982 (args[index] == String16("--latency-clear"))) {
3983 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003984 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003985 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003986 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003987
3988 if ((index < numArgs) &&
3989 (args[index] == String16("--dispsync"))) {
3990 index++;
3991 mPrimaryDispSync.dump(result);
3992 dumpAll = false;
3993 }
Dan Stozab90cf072015-03-05 11:05:59 -08003994
3995 if ((index < numArgs) &&
3996 (args[index] == String16("--static-screen"))) {
3997 index++;
3998 dumpStaticScreenStats(result);
3999 dumpAll = false;
4000 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004001
4002 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004003 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004004 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004005 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004006 dumpAll = false;
4007 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004008
4009 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4010 index++;
4011 dumpWideColorInfo(result);
4012 dumpAll = false;
4013 }
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004014
4015 if ((index < numArgs) &&
4016 (args[index] == String16("--enable-layer-stats"))) {
4017 index++;
4018 mLayerStats.enable();
4019 dumpAll = false;
4020 }
4021
4022 if ((index < numArgs) &&
4023 (args[index] == String16("--disable-layer-stats"))) {
4024 index++;
4025 mLayerStats.disable();
4026 dumpAll = false;
4027 }
4028
4029 if ((index < numArgs) &&
4030 (args[index] == String16("--clear-layer-stats"))) {
4031 index++;
4032 mLayerStats.clear();
4033 dumpAll = false;
4034 }
4035
4036 if ((index < numArgs) &&
4037 (args[index] == String16("--dump-layer-stats"))) {
4038 index++;
4039 mLayerStats.dump(result);
4040 dumpAll = false;
4041 }
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004042
4043 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4044 index++;
4045 mTimeStats.parseArgs(asProto, args, index, result);
4046 dumpAll = false;
4047 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004048 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004049
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004050 if (dumpAll) {
Yiwei Zhang0102ad22018-05-02 17:37:17 -07004051 if (asProto) {
4052 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4053 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4054 } else {
4055 dumpAllLocked(args, index, result);
4056 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004057 }
4058
Mathias Agopian9795c422009-08-26 16:36:26 -07004059 if (locked) {
4060 mStateLock.unlock();
4061 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004062 }
4063 write(fd, result.string(), result.size());
4064 return NO_ERROR;
4065}
4066
Dan Stozac7014012014-02-14 15:03:43 -08004067void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4068 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004069{
Robert Carr2047fae2016-11-28 14:09:09 -08004070 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004071 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004072 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004073}
4074
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004075void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004076 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004077{
4078 String8 name;
4079 if (index < args.size()) {
4080 name = String8(args[index]);
4081 index++;
4082 }
4083
David Sodman105b7dc2017-11-04 20:28:14 -07004084 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004085 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08004086 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004087
4088 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004089 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004090 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004091 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004092 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004093 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004094 }
Robert Carr2047fae2016-11-28 14:09:09 -08004095 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004096 }
4097}
4098
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004099void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004100 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004101{
4102 String8 name;
4103 if (index < args.size()) {
4104 name = String8(args[index]);
4105 index++;
4106 }
4107
Robert Carr2047fae2016-11-28 14:09:09 -08004108 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004109 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004110 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004111 }
Robert Carr2047fae2016-11-28 14:09:09 -08004112 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004113
Svetoslavd85084b2014-03-20 10:28:31 -07004114 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004115}
4116
Jamie Gennis6547ff42013-07-16 20:12:42 -07004117// This should only be called from the main thread. Otherwise it would need
4118// the lock and should use mCurrentState rather than mDrawingState.
4119void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004120 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004121 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004122 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004123
4124 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4125}
4126
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004127void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004128{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004129 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004130
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004131 if (isLayerTripleBufferingDisabled())
4132 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004133
4134 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004135 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004136 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004137 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004138 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4139 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004140 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004141}
4142
Dan Stozab90cf072015-03-05 11:05:59 -08004143void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4144{
4145 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004146 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4147 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004148 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004149 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004150 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4151 b + 1, bucketTimeSec, percent);
4152 }
David Sodman4a36e932017-11-07 14:29:47 -08004153 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004154 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004155 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004156 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004157 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004158}
4159
Dan Stozae77c7662016-05-13 11:37:28 -07004160void SurfaceFlinger::recordBufferingStats(const char* layerName,
4161 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004162 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4163 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004164 for (const auto& segment : history) {
4165 if (!segment.usedThirdBuffer) {
4166 stats.twoBufferTime += segment.totalTime;
4167 }
4168 if (segment.occupancyAverage < 1.0f) {
4169 stats.doubleBufferedTime += segment.totalTime;
4170 } else if (segment.occupancyAverage < 2.0f) {
4171 stats.tripleBufferedTime += segment.totalTime;
4172 }
4173 ++stats.numSegments;
4174 stats.totalTime += segment.totalTime;
4175 }
4176}
4177
Brian Andersond6927fb2016-07-23 23:37:30 -07004178void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4179 result.appendFormat("Layer frame timestamps:\n");
4180
4181 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4182 const size_t count = currentLayers.size();
4183 for (size_t i=0 ; i<count ; i++) {
4184 currentLayers[i]->dumpFrameEvents(result);
4185 }
4186}
4187
Dan Stozae77c7662016-05-13 11:37:28 -07004188void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4189 result.append("Buffering stats:\n");
4190 result.append(" [Layer name] <Active time> <Two buffer> "
4191 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004192 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004193 typedef std::tuple<std::string, float, float, float> BufferTuple;
4194 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004195 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004196 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004197 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004198 if (stats.numSegments == 0) {
4199 continue;
4200 }
4201 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4202 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4203 stats.totalTime;
4204 float doubleBufferRatio = static_cast<float>(
4205 stats.doubleBufferedTime) / stats.totalTime;
4206 float tripleBufferRatio = static_cast<float>(
4207 stats.tripleBufferedTime) / stats.totalTime;
4208 sorted.insert({activeTime, {name, twoBufferRatio,
4209 doubleBufferRatio, tripleBufferRatio}});
4210 }
4211 for (const auto& sortedPair : sorted) {
4212 float activeTime = sortedPair.first;
4213 const BufferTuple& values = sortedPair.second;
4214 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4215 std::get<0>(values).c_str(), activeTime,
4216 std::get<1>(values), std::get<2>(values),
4217 std::get<3>(values));
4218 }
4219 result.append("\n");
4220}
4221
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004222void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4223 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004224 result.appendFormat("DisplayColorSetting: %s\n",
4225 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004226
4227 // TODO: print out if wide-color mode is active or not
4228
4229 for (size_t d = 0; d < mDisplays.size(); d++) {
4230 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4231 int32_t hwcId = displayDevice->getHwcDisplayId();
4232 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4233 continue;
4234 }
4235
4236 result.appendFormat("Display %d color modes:\n", hwcId);
Peiyong Lina52f0292018-03-14 17:26:31 -07004237 std::vector<ColorMode> modes = getHwComposer().getColorModes(hwcId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004238 for (auto&& mode : modes) {
4239 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4240 }
4241
Peiyong Lina52f0292018-03-14 17:26:31 -07004242 ColorMode currentMode = displayDevice->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004243 result.appendFormat(" Current color mode: %s (%d)\n",
4244 decodeColorMode(currentMode).c_str(), currentMode);
4245 }
4246 result.append("\n");
4247}
4248
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004249LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004250 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004251 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4252 const State& state = useDrawing ? mDrawingState : mCurrentState;
4253 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004254 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004255 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004256 });
4257
4258 return layersProto;
4259}
4260
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004261LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(int32_t hwcId) const {
4262 LayersProto layersProto;
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004263 const sp<DisplayDevice>& displayDevice(mDisplays[hwcId]);
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004264
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004265 SizeProto* resolution = layersProto.mutable_resolution();
4266 resolution->set_w(displayDevice->getWidth());
4267 resolution->set_h(displayDevice->getHeight());
4268
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004269 layersProto.set_color_mode(decodeColorMode(displayDevice->getActiveColorMode()));
4270 layersProto.set_color_transform(decodeColorTransform(displayDevice->getColorTransform()));
4271 layersProto.set_global_transform(
4272 static_cast<int32_t>(displayDevice->getOrientationTransform()));
4273
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004274 mDrawingState.traverseInZOrder([&](Layer* layer) {
Yiwei Zhang7c64f172018-03-07 14:52:28 -08004275 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(hwcId)) {
Yiwei Zhang068e31b2018-02-21 13:02:45 -08004276 LayerProto* layerProto = layersProto.add_layers();
4277 layer->writeToProto(layerProto, hwcId);
4278 }
4279 });
4280
4281 return layersProto;
4282}
4283
Mathias Agopian74d211a2013-04-22 16:55:35 +02004284void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4285 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004286{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004287 bool colorize = false;
4288 if (index < args.size()
4289 && (args[index] == String16("--color"))) {
4290 colorize = true;
4291 index++;
4292 }
4293
4294 Colorizer colorizer(colorize);
4295
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004296 // figure out if we're stuck somewhere
4297 const nsecs_t now = systemTime();
4298 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4299 const nsecs_t inTransaction(mDebugInTransaction);
4300 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4301 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4302
4303 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004304 * Dump library configuration.
4305 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004306
4307 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004308 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004309 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004310 appendSfConfigString(result);
4311 appendUiConfigString(result);
4312 appendGuiConfigString(result);
4313 result.append("\n");
4314
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004315 result.append("\nWide-Color information:\n");
4316 dumpWideColorInfo(result);
4317
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004318 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004319 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004320 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004321 result.append(SyncFeatures::getInstance().toString());
4322 result.append("\n");
4323
David Sodman105b7dc2017-11-04 20:28:14 -07004324 const auto& activeConfig = getBE().mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
Dan Stoza9e56aa02015-11-02 13:00:03 -08004325
Andy McFadden41d67d72014-04-25 16:58:34 -07004326 colorizer.bold(result);
4327 result.append("DispSync configuration: ");
4328 colorizer.reset(result);
Jorim Jaggie203e042018-06-19 15:57:08 +02004329 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4330 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
4331 result.appendFormat(
4332 "app phase %" PRId64 " ns, "
4333 "sf phase %" PRId64 " ns, "
4334 "early app phase %" PRId64 " ns, "
4335 "early sf phase %" PRId64 " ns, "
4336 "early app gl phase %" PRId64 " ns, "
4337 "early sf gl phase %" PRId64 " ns, "
4338 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4339 vsyncPhaseOffsetNs,
4340 sfVsyncPhaseOffsetNs,
4341 appEarlyOffset,
4342 sfEarlyOffset,
4343 appEarlyGlOffset,
4344 sfEarlyOffset,
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004345 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07004346 result.append("\n");
4347
Dan Stozab90cf072015-03-05 11:05:59 -08004348 // Dump static screen stats
4349 result.append("\n");
4350 dumpStaticScreenStats(result);
4351 result.append("\n");
4352
Dan Stozae77c7662016-05-13 11:37:28 -07004353 dumpBufferingStats(result);
4354
Andy McFadden4803b742012-09-24 19:07:20 -07004355 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004356 * Dump the visible layer list
4357 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004358 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004359 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004360 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4361 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004363
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004364 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004365 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7794ec12018-03-14 13:28:39 -07004366 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004367 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368
4369 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004370 * Dump Display state
4371 */
4372
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004373 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004374 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004375 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004376 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
4377 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004378 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004379 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004380 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004381
4382 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004383 * Dump SurfaceFlinger global state
4384 */
4385
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004386 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004387 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004388 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004389
Mathias Agopian888c8222012-08-04 21:10:38 -07004390 HWComposer& hwc(getHwComposer());
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004391 sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
Mathias Agopianca088332013-03-28 17:44:13 -07004392
David Sodmanbc815282017-11-05 18:57:52 -08004393 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004394
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004395 if (hw) {
4396 hw->undefinedRegion.dump(result, "undefinedRegion");
4397 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
4398 hw->getOrientation(), hw->isDisplayOn());
4399 }
Mathias Agopian74d211a2013-04-22 16:55:35 +02004400 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004401 " last eglSwapBuffers() time: %f us\n"
4402 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004403 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004404 " refresh-rate : %f fps\n"
4405 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004406 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07004407 " gpu_to_cpu_unsupported : %d\n"
4408 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004409 mLastSwapBufferTime/1000.0,
4410 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08004411 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08004412 1e9 / activeConfig->getVsyncPeriod(),
4413 activeConfig->getDpiX(),
4414 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07004415 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004416
Mathias Agopian74d211a2013-04-22 16:55:35 +02004417 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419
Mathias Agopian74d211a2013-04-22 16:55:35 +02004420 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004421 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004422
4423 /*
4424 * VSYNC state
4425 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004426 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004427 result.append("\n");
4428
4429 /*
Yichi Chen738966b2018-09-15 14:51:18 +08004430 * Tracing state
4431 */
4432 mTracing.dump(result);
4433 result.append("\n");
4434
4435 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004436 * HWC layer minidump
4437 */
4438 for (size_t d = 0; d < mDisplays.size(); d++) {
4439 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
4440 int32_t hwcId = displayDevice->getHwcDisplayId();
4441 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
4442 continue;
4443 }
4444
4445 result.appendFormat("Display %d HWC layers:\n", hwcId);
4446 Layer::miniDumpHeader(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004447 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dan Stozae22aec72016-08-01 13:20:59 -07004448 layer->miniDump(result, hwcId);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004449 });
Dan Stozae22aec72016-08-01 13:20:59 -07004450 result.append("\n");
4451 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004452
4453 /*
4454 * Dump HWComposer state
4455 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004456 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004457 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004458 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004459 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004460 result.appendFormat(" h/w composer %s\n",
4461 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004462 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004463
4464 /*
4465 * Dump gralloc state
4466 */
4467 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4468 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004469
4470 /*
4471 * Dump VrFlinger state if in use.
4472 */
4473 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4474 result.append("VrFlinger state:\n");
4475 result.append(mVrFlinger->Dump().c_str());
4476 result.append("\n");
4477 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004478}
4479
Mathias Agopian13127d82013-03-05 17:47:11 -08004480const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07004481SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004482 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07004483 wp<IBinder> dpy;
4484 for (size_t i=0 ; i<mDisplays.size() ; i++) {
4485 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
4486 dpy = mDisplays.keyAt(i);
4487 break;
4488 }
4489 }
Peiyong Lin566a3b42018-01-09 18:22:43 -08004490 if (dpy == nullptr) {
Jesse Hall48bc05b2013-03-21 14:06:52 -07004491 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
4492 // Just use the primary display so we have something to return
4493 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
4494 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07004495 return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07004496}
4497
Chia-I Wu28f320b2018-05-03 11:02:56 -07004498void SurfaceFlinger::updateColorMatrixLocked() {
4499 mat4 colorMatrix;
4500 if (mGlobalSaturationFactor != 1.0f) {
4501 // Rec.709 luma coefficients
4502 float3 luminance{0.213f, 0.715f, 0.072f};
4503 luminance *= 1.0f - mGlobalSaturationFactor;
4504 mat4 saturationMatrix = mat4(
4505 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4506 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4507 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4508 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4509 );
4510 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4511 } else {
4512 colorMatrix = mClientColorMatrix * mDaltonizer();
4513 }
4514
4515 if (mCurrentState.colorMatrix != colorMatrix) {
4516 mCurrentState.colorMatrix = colorMatrix;
4517 mCurrentState.colorMatrixChanged = true;
4518 setTransactionFlags(eTransactionNeeded);
4519 }
4520}
4521
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004522status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 switch (code) {
4524 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07004525 case CREATE_DISPLAY:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004527 case CLEAR_ANIMATION_FRAME_STATS:
4528 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004529 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07004530 case GET_HDR_CAPABILITIES:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004531 case ENABLE_VSYNC_INJECTIONS:
4532 case INJECT_VSYNC:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 {
4534 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004535 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4536 IPCThreadState* ipc = IPCThreadState::self();
4537 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4538 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004539 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004541 break;
4542 }
Robert Carr1db73f62016-12-21 12:58:51 -08004543 /*
4544 * Calling setTransactionState is safe, because you need to have been
4545 * granted a reference to Client* and Handle* to do anything with it.
4546 *
4547 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4548 */
4549 case SET_TRANSACTION_STATE:
4550 case CREATE_SCOPED_CONNECTION:
4551 {
4552 return OK;
4553 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004554 case CAPTURE_SCREEN:
4555 {
4556 // codes that require permission check
4557 IPCThreadState* ipc = IPCThreadState::self();
4558 const int pid = ipc->getCallingPid();
4559 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07004560 if ((uid != AID_GRAPHICS) &&
4561 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004562 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004563 return PERMISSION_DENIED;
4564 }
4565 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004566 }
chaviwa76b2712017-09-20 12:02:26 -07004567 case CAPTURE_LAYERS: {
4568 IPCThreadState* ipc = IPCThreadState::self();
4569 const int pid = ipc->getCallingPid();
4570 const int uid = ipc->getCallingUid();
4571 if ((uid != AID_GRAPHICS) &&
4572 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4573 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4574 return PERMISSION_DENIED;
4575 }
4576 break;
4577 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004578 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004579 return OK;
4580}
4581
4582status_t SurfaceFlinger::onTransact(
4583 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4584{
4585 status_t credentialCheck = CheckTransactCodeCredentials(code);
4586 if (credentialCheck != OK) {
4587 return credentialCheck;
4588 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004589
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004590 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4591 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004592 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004593 IPCThreadState* ipc = IPCThreadState::self();
4594 const int uid = ipc->getCallingUid();
4595 if (CC_UNLIKELY(uid != AID_SYSTEM
4596 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004597 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004598 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004599 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004600 return PERMISSION_DENIED;
4601 }
4602 int n;
4603 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004604 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004605 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 return NO_ERROR;
4607 case 1002: // SHOW_UPDATES
4608 n = data.readInt32();
4609 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004610 invalidateHwcGeometry();
4611 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004613 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004614 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004615 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004616 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004617 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004618 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004619 setTransactionFlags(
4620 eTransactionNeeded|
4621 eDisplayTransactionNeeded|
4622 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004623 return NO_ERROR;
4624 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004625 case 1006:{ // send empty update
4626 signalRefresh();
4627 return NO_ERROR;
4628 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004629 case 1008: // toggle use of hw composer
4630 n = data.readInt32();
4631 mDebugDisableHWC = n ? 1 : 0;
4632 invalidateHwcGeometry();
4633 repaintEverything();
4634 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004635 case 1009: // toggle use of transform hint
4636 n = data.readInt32();
4637 mDebugDisableTransformHint = n ? 1 : 0;
4638 invalidateHwcGeometry();
4639 repaintEverything();
4640 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004641 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004642 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004643 reply->writeInt32(0);
4644 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004645 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004646 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004647 return NO_ERROR;
4648 case 1013: {
Tomasz Wasilczyk8722a312017-04-13 19:14:30 +00004649 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopian42977342012-08-05 00:40:46 -07004650 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004651 return NO_ERROR;
4652 }
4653 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004655 // daltonize
4656 n = data.readInt32();
4657 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004658 case 1:
4659 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4660 break;
4661 case 2:
4662 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4663 break;
4664 case 3:
4665 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4666 break;
4667 default:
4668 mDaltonizer.setType(ColorBlindnessType::None);
4669 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004670 }
4671 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004672 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004673 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004674 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004675 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004676
4677 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004678 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004680 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004681 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004682 // apply a color matrix
4683 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004684 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004685 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004686 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004687 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004688 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004689 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004690 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004691 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004692 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004693 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004694
4695 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4696 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004697 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004698 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4699 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4700 }
4701
Chia-I Wu28f320b2018-05-03 11:02:56 -07004702 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004703 return NO_ERROR;
4704 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004705 // This is an experimental interface
4706 // Needs to be shifted to proper binder interface when we productize
4707 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004708 n = data.readInt32();
4709 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004710 return NO_ERROR;
4711 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004712 case 1017: {
4713 n = data.readInt32();
4714 mForceFullDamage = static_cast<bool>(n);
4715 return NO_ERROR;
4716 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004717 case 1018: { // Modify Choreographer's phase offset
4718 n = data.readInt32();
4719 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4720 return NO_ERROR;
4721 }
4722 case 1019: { // Modify SurfaceFlinger's phase offset
4723 n = data.readInt32();
4724 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4725 return NO_ERROR;
4726 }
Irvel468051e2016-06-13 16:44:44 -07004727 case 1020: { // Layer updates interceptor
4728 n = data.readInt32();
4729 if (n) {
4730 ALOGV("Interceptor enabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004731 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004732 }
4733 else{
4734 ALOGV("Interceptor disabled");
Lloyd Pique4d234852018-01-22 17:21:36 -08004735 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004736 }
4737 return NO_ERROR;
4738 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004739 case 1021: { // Disable HWC virtual displays
4740 n = data.readInt32();
4741 mUseHwcVirtualDisplays = !n;
4742 return NO_ERROR;
4743 }
Romain Guy0147a172017-06-01 13:53:56 -07004744 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004745 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004746 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004747
Chia-I Wu28f320b2018-05-03 11:02:56 -07004748 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004749 return NO_ERROR;
4750 }
Romain Guy54f154a2017-10-24 21:40:32 +01004751 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004752 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004753 invalidateHwcGeometry();
4754 repaintEverything();
4755 return NO_ERROR;
4756 }
4757 case 1024: { // Is wide color gamut rendering/color management supported?
4758 reply->writeBool(hasWideColorDisplay);
4759 return NO_ERROR;
4760 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004761 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004762 n = data.readInt32();
4763 if (n) {
Yichi Chen738966b2018-09-15 14:51:18 +08004764 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004765 mTracing.enable();
4766 doTracing("tracing.enable");
4767 reply->writeInt32(NO_ERROR);
4768 } else {
Yichi Chen738966b2018-09-15 14:51:18 +08004769 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01004770 status_t err = mTracing.disable();
4771 reply->writeInt32(err);
4772 }
4773 return NO_ERROR;
4774 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004775 case 1026: { // Get layer tracing status
4776 reply->writeBool(mTracing.isEnabled());
4777 return NO_ERROR;
4778 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004779 // Is a DisplayColorSetting supported?
4780 case 1027: {
Chia-I Wu0d711262018-05-21 15:19:35 -07004781 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
4782 if (!hw) {
4783 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004784 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004785
4786 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4787 switch (setting) {
4788 case DisplayColorSetting::MANAGED:
4789 reply->writeBool(hasWideColorDisplay);
4790 break;
4791 case DisplayColorSetting::UNMANAGED:
4792 reply->writeBool(true);
4793 break;
4794 case DisplayColorSetting::ENHANCED:
4795 reply->writeBool(hw->hasRenderIntent(RenderIntent::ENHANCE));
4796 break;
4797 default: // vendor display color setting
4798 reply->writeBool(hw->hasRenderIntent(static_cast<RenderIntent>(setting)));
4799 break;
4800 }
4801 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004802 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004803 }
4804 }
4805 return err;
4806}
4807
Steven Thomas6d8110b2017-08-31 18:24:21 -07004808void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004809 android_atomic_or(1, &mRepaintEverything);
4810 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004811}
4812
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004813// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4814class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004815public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004816 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4817 ~WindowDisconnector() {
4818 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004819 }
4820
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004821private:
4822 ANativeWindow* mWindow;
4823 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004824};
4825
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004826status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
4827 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4828 int32_t minLayerZ, int32_t maxLayerZ,
4829 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004830 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004831 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004832
chaviwa76b2712017-09-20 12:02:26 -07004833 if (CC_UNLIKELY(display == 0)) return BAD_VALUE;
4834
4835 const sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004836 if (CC_UNLIKELY(device == 0)) return BAD_VALUE;
4837
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004838 const Rect& dispScissor = device->getScissor();
4839 if (!dispScissor.isEmpty()) {
4840 sourceCrop.set(dispScissor);
4841 // adb shell screencap will default reqWidth and reqHeight to zeros.
4842 if (reqWidth == 0 || reqHeight == 0) {
Yiwei Zhang9ad73bc2018-08-21 22:11:37 -07004843 reqWidth = uint32_t(device->getViewport().width());
4844 reqHeight = uint32_t(device->getViewport().height());
Yiwei Zhangf4e02872018-08-20 16:42:23 -07004845 }
4846 }
4847
Chia-I Wu07f190f2018-08-23 13:44:43 -07004848 DisplayRenderArea renderArea(device, sourceCrop, reqWidth, reqHeight, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004849
4850 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
4851 device, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004852 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004853}
4854
4855status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004856 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004857 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004858 ATRACE_CALL();
4859
4860 class LayerRenderArea : public RenderArea {
4861 public:
Robert Carr578038f2018-03-09 12:25:24 -08004862 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4863 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu07f190f2018-08-23 13:44:43 -07004864 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004865 mLayer(layer),
4866 mCrop(crop),
4867 mFlinger(flinger),
4868 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004869 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004870 Rect getBounds() const override {
4871 const Layer::State& layerState(mLayer->getDrawingState());
4872 return Rect(layerState.active.w, layerState.active.h);
4873 }
4874 int getHeight() const override { return mLayer->getDrawingState().active.h; }
4875 int getWidth() const override { return mLayer->getDrawingState().active.w; }
4876 bool isSecure() const override { return false; }
4877 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004878 Rect getSourceCrop() const override {
4879 if (mCrop.isEmpty()) {
4880 return getBounds();
4881 } else {
4882 return mCrop;
4883 }
4884 }
Robert Carr578038f2018-03-09 12:25:24 -08004885 class ReparentForDrawing {
4886 public:
4887 const sp<Layer>& oldParent;
4888 const sp<Layer>& newParent;
4889
4890 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4891 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004892 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004893 }
Robert Carr15eae092018-03-23 13:43:53 -07004894 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004895 };
4896
4897 void render(std::function<void()> drawLayers) override {
4898 if (!mChildrenOnly) {
4899 mTransform = mLayer->getTransform().inverse();
4900 drawLayers();
4901 } else {
4902 Rect bounds = getBounds();
4903 screenshotParentLayer =
4904 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4905 bounds.getWidth(), bounds.getHeight(), 0);
4906
4907 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4908 drawLayers();
4909 }
4910 }
chaviwa76b2712017-09-20 12:02:26 -07004911
chaviwa76b2712017-09-20 12:02:26 -07004912 private:
chaviw7206d492017-11-10 16:16:12 -08004913 const sp<Layer> mLayer;
4914 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004915
4916 // In the "childrenOnly" case we reparent the children to a screenshot
4917 // layer which has no properties set and which does not draw.
4918 sp<ContainerLayer> screenshotParentLayer;
4919 Transform mTransform;
4920
4921 SurfaceFlinger* mFlinger;
4922 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004923 };
4924
4925 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
4926 auto parent = layerHandle->owner.promote();
4927
chaviw7206d492017-11-10 16:16:12 -08004928 if (parent == nullptr || parent->isPendingRemoval()) {
4929 ALOGE("captureLayers called with a removed parent");
4930 return NAME_NOT_FOUND;
4931 }
4932
Robert Carr578038f2018-03-09 12:25:24 -08004933 const int uid = IPCThreadState::self()->getCallingUid();
4934 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4935 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
4936 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
4937 return PERMISSION_DENIED;
4938 }
4939
chaviw7206d492017-11-10 16:16:12 -08004940 Rect crop(sourceCrop);
4941 if (sourceCrop.width() <= 0) {
4942 crop.left = 0;
4943 crop.right = parent->getCurrentState().active.w;
4944 }
4945
4946 if (sourceCrop.height() <= 0) {
4947 crop.top = 0;
4948 crop.bottom = parent->getCurrentState().active.h;
4949 }
4950
4951 int32_t reqWidth = crop.width() * frameScale;
4952 int32_t reqHeight = crop.height() * frameScale;
4953
Robert Carr578038f2018-03-09 12:25:24 -08004954 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08004955
Robert Carr578038f2018-03-09 12:25:24 -08004956 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07004957 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4958 if (!layer->isVisible()) {
4959 return;
Robert Carr578038f2018-03-09 12:25:24 -08004960 } else if (childrenOnly && layer == parent.get()) {
4961 return;
chaviwa76b2712017-09-20 12:02:26 -07004962 }
4963 visitor(layer);
4964 });
4965 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004966 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07004967}
4968
4969status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
4970 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004971 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07004972 bool useIdentityTransform) {
4973 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004974
Iris Chang7501ed62018-04-30 14:45:42 +08004975 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07004976
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004977 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4978 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4979 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
4980 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004981
4982 // This mutex protects syncFd and captureResult for communication of the return values from the
4983 // main thread back to this Binder thread
4984 std::mutex captureMutex;
4985 std::condition_variable captureCondition;
4986 std::unique_lock<std::mutex> captureLock(captureMutex);
4987 int syncFd = -1;
4988 std::optional<status_t> captureResult;
4989
Robert Carr03480e22018-01-04 16:02:06 -08004990 const int uid = IPCThreadState::self()->getCallingUid();
4991 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
4992
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004993 sp<LambdaMessage> message = new LambdaMessage([&]() {
4994 // If there is a refresh pending, bug out early and tell the binder thread to try again
4995 // after the refresh.
4996 if (mRefreshPending) {
4997 ATRACE_NAME("Skipping screenshot for now");
4998 std::unique_lock<std::mutex> captureLock(captureMutex);
4999 captureResult = std::make_optional<status_t>(EAGAIN);
5000 captureCondition.notify_one();
5001 return;
5002 }
5003
5004 status_t result = NO_ERROR;
5005 int fd = -1;
5006 {
5007 Mutex::Autolock _l(mStateLock);
Robert Carr578038f2018-03-09 12:25:24 -08005008 renderArea.render([&]() {
5009 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5010 useIdentityTransform, forSystem, &fd);
5011 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005012 }
5013
5014 {
5015 std::unique_lock<std::mutex> captureLock(captureMutex);
5016 syncFd = fd;
5017 captureResult = std::make_optional<status_t>(result);
5018 captureCondition.notify_one();
5019 }
5020 });
5021
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005022 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005023 if (result == NO_ERROR) {
5024 captureCondition.wait(captureLock, [&]() { return captureResult; });
5025 while (*captureResult == EAGAIN) {
5026 captureResult.reset();
5027 result = postMessageAsync(message);
5028 if (result != NO_ERROR) {
5029 return result;
5030 }
5031 captureCondition.wait(captureLock, [&]() { return captureResult; });
5032 }
5033 result = *captureResult;
5034 }
5035
5036 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005037 sync_wait(syncFd, -1);
5038 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005039 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005040
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005041 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005042}
5043
chaviwa76b2712017-09-20 12:02:26 -07005044void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5045 TraverseLayersFunction traverseLayers, bool yswap,
5046 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005047 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005048
Lloyd Pique144e1162017-12-20 16:44:52 -08005049 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005050
5051 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005052 const auto raWidth = renderArea.getWidth();
5053 const auto raHeight = renderArea.getHeight();
5054
5055 const auto reqWidth = renderArea.getReqWidth();
5056 const auto reqHeight = renderArea.getReqHeight();
5057 Rect sourceCrop = renderArea.getSourceCrop();
5058
Iris Chang7501ed62018-04-30 14:45:42 +08005059 bool filtering = false;
5060 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5061 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5062 static_cast<int32_t>(reqHeight) != raWidth;
5063 } else {
5064 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5065 static_cast<int32_t>(reqHeight) != raHeight;
5066 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005067
Dan Stozac1879002014-05-22 15:59:05 -07005068 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005069 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005070 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005071 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005072 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5073 Transform tr;
5074 uint32_t flags = 0x00;
5075 switch (mPrimaryDisplayOrientation) {
5076 case DisplayState::eOrientation90:
5077 flags = Transform::ROT_90;
5078 break;
5079 case DisplayState::eOrientation180:
5080 flags = Transform::ROT_180;
5081 break;
5082 case DisplayState::eOrientation270:
5083 flags = Transform::ROT_270;
5084 break;
5085 }
5086 tr.set(flags, raWidth, raHeight);
5087 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005088 }
5089
5090 // ensure that sourceCrop is inside screen
5091 if (sourceCrop.left < 0) {
5092 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5093 }
chaviwa76b2712017-09-20 12:02:26 -07005094 if (sourceCrop.right > raWidth) {
5095 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005096 }
5097 if (sourceCrop.top < 0) {
5098 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5099 }
chaviwa76b2712017-09-20 12:02:26 -07005100 if (sourceCrop.bottom > raHeight) {
5101 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005102 }
5103
Chia-I Wu36574d92018-05-16 10:54:36 -07005104 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5105 engine.setOutputDataSpace(Dataspace::SRGB);
5106 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005107
Mathias Agopian180f10d2013-04-10 22:55:41 -07005108 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005109 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005110
Iris Chang7501ed62018-04-30 14:45:42 +08005111 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5112 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5113 // convert hw orientation into flag presentation
5114 // here inverse transform needed
5115 uint8_t hw_rot_90 = 0x00;
5116 uint8_t hw_flip_hv = 0x00;
5117 switch (mPrimaryDisplayOrientation) {
5118 case DisplayState::eOrientation90:
5119 hw_rot_90 = Transform::ROT_90;
5120 hw_flip_hv = Transform::ROT_180;
5121 break;
5122 case DisplayState::eOrientation180:
5123 hw_flip_hv = Transform::ROT_180;
5124 break;
5125 case DisplayState::eOrientation270:
5126 hw_rot_90 = Transform::ROT_90;
5127 break;
5128 }
5129
5130 // transform flags operation
5131 // 1) flip H V if both have ROT_90 flag
5132 // 2) XOR these flags
5133 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5134 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5135 if (rotation_rot_90 & hw_rot_90) {
5136 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5137 }
5138 rotation = static_cast<Transform::orientation_flags>
5139 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5140 }
5141
Mathias Agopian180f10d2013-04-10 22:55:41 -07005142 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005143 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005144 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005145 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005146
chaviw50da5042018-04-09 13:49:37 -07005147 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005148 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005149 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005150
chaviwa76b2712017-09-20 12:02:26 -07005151 traverseLayers([&](Layer* layer) {
5152 if (filtering) layer->setFiltering(true);
5153 layer->draw(renderArea, useIdentityTransform);
5154 if (filtering) layer->setFiltering(false);
5155 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005156}
5157
chaviwa76b2712017-09-20 12:02:26 -07005158status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5159 TraverseLayersFunction traverseLayers,
5160 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005161 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005162 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005163 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005164 ATRACE_CALL();
5165
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005166 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005167
5168 traverseLayers([&](Layer* layer) {
5169 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5170 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005171
Robert Carr03480e22018-01-04 16:02:06 -08005172 // We allow the system server to take screenshots of secure layers for
5173 // use in situations like the Screen-rotation animation and place
5174 // the impetus on WindowManager to not persist them.
5175 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005176 ALOGW("FB is protected: PERMISSION_DENIED");
5177 return PERMISSION_DENIED;
5178 }
5179
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005180 // this binds the given EGLImage as a framebuffer for the
5181 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005182 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005183 if (bufferBond.getStatus() != NO_ERROR) {
5184 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005185 return INVALID_OPERATION;
5186 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005187
Dan Stozaabcda352017-06-01 14:37:39 -07005188 // this will in fact render into our dequeued buffer
5189 // via an FBO, which means we didn't have to create
5190 // an EGLSurface and therefore we're not
5191 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005192 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005193
Dan Stozaabcda352017-06-01 14:37:39 -07005194 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005195 getRenderEngine().finish();
5196 *outSyncFd = -1;
5197
chaviwa76b2712017-09-20 12:02:26 -07005198 const auto reqWidth = renderArea.getReqWidth();
5199 const auto reqHeight = renderArea.getReqHeight();
5200
Dan Stozaabcda352017-06-01 14:37:39 -07005201 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5202 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005203 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005204 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005205 } else {
5206 base::unique_fd syncFd = getRenderEngine().flush();
5207 if (syncFd < 0) {
5208 getRenderEngine().finish();
5209 }
5210 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005211 }
5212
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005213 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005214}
5215
Mathias Agopiand5556842013-09-19 17:08:37 -07005216void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005217 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005218 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005219 for (size_t y = 0; y < h; y++) {
5220 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5221 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005222 if (p[x] != 0xFF000000) return;
5223 }
5224 }
chaviwa76b2712017-09-20 12:02:26 -07005225 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005226
Robert Carr2047fae2016-11-28 14:09:09 -08005227 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005228 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005229 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005230 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5231 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5232 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5233 static_cast<float>(state.color.a));
5234 i++;
5235 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005236 }
5237}
5238
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005239// ---------------------------------------------------------------------------
5240
Dan Stoza412903f2017-04-27 13:42:17 -07005241void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5242 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005243}
5244
Dan Stoza412903f2017-04-27 13:42:17 -07005245void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5246 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005247}
5248
chaviwa76b2712017-09-20 12:02:26 -07005249void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& hw, int32_t minLayerZ,
5250 int32_t maxLayerZ,
5251 const LayerVector::Visitor& visitor) {
5252 // We loop through the first level of layers without traversing,
5253 // as we need to interpret min/max layer Z in the top level Z space.
5254 for (const auto& layer : mDrawingState.layersSortedByZ) {
5255 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5256 continue;
5257 }
5258 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005259 // relative layers are traversed in Layer::traverseInZOrder
5260 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005261 continue;
5262 }
5263 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005264 if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
5265 return;
5266 }
chaviwa76b2712017-09-20 12:02:26 -07005267 if (!layer->isVisible()) {
5268 return;
5269 }
5270 visitor(layer);
5271 });
5272 }
5273}
5274
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005275}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005276
5277
5278#if defined(__gl_h_)
5279#error "don't include gl/gl.h in this file"
5280#endif
5281
5282#if defined(__gl2_h_)
5283#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005284#endif