blob: c03329001822bbf3c8fbfe0711ab6abbc3005f73 [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
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
52
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070054#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080055#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080056#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080057#include <gui/Surface.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000058#include <hidl/ServiceManagement.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070060#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <ui/ColorSpace.h>
62#include <ui/DebugUtils.h>
63#include <ui/DisplayInfo.h>
64#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070065#include <ui/GraphicBufferAllocator.h>
66#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070067#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/String16.h>
70#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070071#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080072#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070073#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopian921e6ac2012-07-23 23:11:29 -070075#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070076#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Robert Carr578038f2018-03-09 12:25:24 -080078#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070079#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070080#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020083#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080084#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070087#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080088#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070089#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070090#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070091#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094
Steven Thomasb02664d2017-07-26 18:48:28 -070095#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070096#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070097#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070098#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070099#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700100#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700101#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700103#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104#include "Scheduler/EventControlThread.h"
105#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700106#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700107#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700108#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700109#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800110#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700111
Mathias Agopianff2ed702013-09-01 21:36:12 -0700112#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700113
David Sodman7e4ae112018-02-09 15:02:28 -0800114#include "android-base/stringprintf.h"
115
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800117#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
118#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700119#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900120#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121
chaviw1d044282017-09-27 12:19:28 -0700122#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700166bool isHdrColorMode(const ColorMode colorMode) {
167 switch (colorMode) {
168 case ColorMode::BT2100_PQ:
169 case ColorMode::BT2100_HLG:
170 return true;
171 case ColorMode::DISPLAY_P3:
172 case ColorMode::ADOBE_RGB:
173 case ColorMode::DCI_P3:
174 case ColorMode::BT2020:
175 case ColorMode::DISPLAY_BT2020:
176 case ColorMode::NATIVE:
177 case ColorMode::STANDARD_BT601_625:
178 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
179 case ColorMode::STANDARD_BT601_525:
180 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
181 case ColorMode::STANDARD_BT709:
182 case ColorMode::SRGB:
183 return false;
184 }
185 return false;
186}
187
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700188ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
189 switch (rotation) {
190 case ISurfaceComposer::eRotateNone:
191 return ui::Transform::ROT_0;
192 case ISurfaceComposer::eRotate90:
193 return ui::Transform::ROT_90;
194 case ISurfaceComposer::eRotate180:
195 return ui::Transform::ROT_180;
196 case ISurfaceComposer::eRotate270:
197 return ui::Transform::ROT_270;
198 }
199 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
200 return ui::Transform::ROT_0;
201}
202
Peiyong Linfca547f2018-07-09 13:03:33 -0700203#pragma clang diagnostic pop
204
Steven Thomasb02664d2017-07-26 18:48:28 -0700205class ConditionalLock {
206public:
207 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
208 if (lock) {
209 mMutex.lock();
210 }
211 }
212 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
213private:
214 Mutex& mMutex;
215 bool mLocked;
216};
Peiyong Linfca547f2018-07-09 13:03:33 -0700217
Peiyong Lin9d846a52018-11-05 13:18:20 -0800218// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
219bool validateCompositionDataspace(Dataspace dataspace) {
220 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
221}
222
Steven Thomasb02664d2017-07-26 18:48:28 -0700223} // namespace anonymous
224
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800225// ---------------------------------------------------------------------------
226
Mathias Agopian99b49842011-06-27 16:05:52 -0700227const String16 sHardwareTest("android.permission.HARDWARE_TEST");
228const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
229const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
230const String16 sDump("android.permission.DUMP");
231
232// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700233int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700234bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800235uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800236bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800237bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800238int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600239bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700240int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700241bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700242bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700243Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
244ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
245Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
246ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700247
Kalle Raitaa099a242017-01-11 11:17:29 -0800248std::string getHwcServiceName() {
249 char value[PROPERTY_VALUE_MAX] = {};
250 property_get("debug.sf.hwc_service_name", value, "default");
251 ALOGI("Using HWComposer service: '%s'", value);
252 return std::string(value);
253}
254
255bool useTrebleTestingOverride() {
256 char value[PROPERTY_VALUE_MAX] = {};
257 property_get("debug.sf.treble_testing_override", value, "false");
258 ALOGI("Treble testing override: '%s'", value);
259 return std::string(value) == "true";
260}
261
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800262std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
263 switch(displayColorSetting) {
264 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700265 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800266 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700267 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800268 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700269 return std::string("Enhanced");
270 default:
271 return std::string("Unknown ") +
272 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800273 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800274}
275
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800277
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700278SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
279 : mFactory(factory),
280 mPhaseOffsets(mFactory.createPhaseOffsets()),
281 mInterceptor(mFactory.createSurfaceInterceptor(this)),
282 mTimeStats(mFactory.createTimeStats()),
283 mEventQueue(mFactory.createMessageQueue()),
284 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800285
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700286SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800287 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600305
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 mDefaultCompositionDataspace =
307 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700308 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
309 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 defaultCompositionDataspace = mDefaultCompositionDataspace;
311 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
312 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
313 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
314 wideColorGamutCompositionPixelFormat =
315 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700316
Yichi Chenda901bf2019-06-28 14:58:27 +0800317 mColorSpaceAgnosticDataspace =
318 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
319
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900320 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800321
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
323 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
324 switch (tmpPrimaryDisplayOrientation) {
325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
334 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800336 break;
337 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700338 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800339
Sundong Ahn85131bd2019-02-18 15:51:53 +0900340 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 // debugging stuff...
343 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianb4b17302013-03-20 18:36:41 -0700345 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700346 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700347
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800348 property_get("debug.sf.showupdates", value, "0");
349 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700351 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000352
353 // DDMS debugging deprecated (b/120782499)
354 property_get("debug.sf.ddms", value, "0");
355 int debugDdms = atoi(value);
356 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700357
358 property_get("debug.sf.disable_backpressure", value, "0");
359 mPropagateBackpressure = !atoi(value);
360 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700361
Ady Abrahamadb9a992019-09-19 21:21:55 +0000362 property_get("debug.sf.enable_gl_backpressure", value, "0");
363 mPropagateBackpressureClientComposition = atoi(value);
364 ALOGI_IF(mPropagateBackpressureClientComposition,
365 "Enabling backpressure propagation for Client Composition");
366
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800367 property_get("debug.sf.enable_hwc_vds", value, "0");
368 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800369 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800370
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800371 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800372 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800373 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700374
Yiwei Zhang243b3782018-05-15 17:40:04 -0700375 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
378
Ana Krulece5a06e02019-03-06 17:09:03 -0800379 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800380 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800381
382 int int_value = atoi(value);
383 if (int_value) {
384 mUseSmart90ForVideo = true;
385 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800386
Dan Stozaec460082018-12-17 15:35:09 -0800387 property_get("debug.sf.luma_sampling", value, "1");
388 mLumaSampling = atoi(value);
389
Ana Krulec757f63a2019-01-25 10:46:18 -0800390 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700391 mVsyncModulator.setPhaseOffsets(early, gl, late,
392 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700393
Romain Guy11d63f42017-07-20 12:47:14 -0700394 // We should be reading 'persist.sys.sf.color_saturation' here
395 // but since /data may be encrypted, we need to wait until after vold
396 // comes online to attempt to read the property. The property is
397 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800398
399 if (useTrebleTestingOverride()) {
400 // Without the override SurfaceFlinger cannot connect to HIDL
401 // services that are not listed in the manifests. Considered
402 // deriving the setting from the set service name, but it
403 // would be brittle if the name that's not 'default' is used
404 // for production purposes later on.
Steven Moreland7c8af942020-07-08 18:35:51 +0000405 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800406 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407}
408
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409void SurfaceFlinger::onFirstRef()
410{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800411 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412}
413
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700414SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800415
Dan Stozac7014012014-02-14 15:03:43 -0800416void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417{
418 // the window manager died on us. prepare its eulogy.
419
Andy McFadden13a082e2012-08-24 10:16:42 -0700420 // restore initial conditions (default device unblank, etc)
421 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
423 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700424 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
Robert Carr1db73f62016-12-21 12:58:51 -0800427static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700428 status_t err = client->initCheck();
429 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800430 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 }
Robert Carr1db73f62016-12-21 12:58:51 -0800432 return nullptr;
433}
434
435sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
436 return initClient(new Client(this));
437}
438
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700439sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
440 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441{
442 class DisplayToken : public BBinder {
443 sp<SurfaceFlinger> flinger;
444 virtual ~DisplayToken() {
445 // no more references, this display must be terminated
446 Mutex::Autolock _l(flinger->mStateLock);
447 flinger->mCurrentState.displays.removeItem(this);
448 flinger->setTransactionFlags(eDisplayTransactionNeeded);
449 }
450 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700451 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700452 : flinger(flinger) {
453 }
454 };
455
456 sp<BBinder> token = new DisplayToken(this);
457
458 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 // Display ID is assigned when virtual display is allocated by HWC.
460 DisplayDeviceState state;
461 state.isSecure = secure;
462 state.displayName = displayName;
463 mCurrentState.displays.add(token, state);
464 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 return token;
466}
467
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700468void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 Mutex::Autolock _l(mStateLock);
470
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
472 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700473 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 return;
475 }
476
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
478 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 ALOGE("destroyDisplay called for non-virtual display");
480 return;
481 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 mInterceptor->saveDisplayDeletion(state.sequenceId);
483 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 setTransactionFlags(eDisplayTransactionNeeded);
485}
486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
488 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490 const auto internalDisplayId = getInternalDisplayIdLocked();
491 if (!internalDisplayId) {
492 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 }
494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495 std::vector<PhysicalDisplayId> displayIds;
496 displayIds.reserve(mPhysicalDisplayTokens.size());
497 displayIds.push_back(internalDisplayId->value);
498
499 for (const auto& [id, token] : mPhysicalDisplayTokens) {
500 if (id != *internalDisplayId) {
501 displayIds.push_back(id.value);
502 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 return displayIds;
506}
507
508sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
509 Mutex::Autolock lock(mStateLock);
510 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511}
512
Ady Abraham37965d42018-11-01 13:43:32 -0700513status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
514 if (!outGetColorManagement) {
515 return BAD_VALUE;
516 }
517 *outGetColorManagement = useColorManagement;
518 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700519}
520
Lloyd Pique441d5042018-10-18 16:49:51 -0700521HWComposer& SurfaceFlinger::getHwComposer() const {
522 return mCompositionEngine->getHwComposer();
523}
524
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700525renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
526 return mCompositionEngine->getRenderEngine();
527}
528
Lloyd Pique70d91362018-10-18 16:02:55 -0700529compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
530 return *mCompositionEngine.get();
531}
532
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533void SurfaceFlinger::bootFinished()
534{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700535 if (mStartPropertySetThread->join() != NO_ERROR) {
536 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800537 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 const nsecs_t now = systemTime();
539 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000540 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
542 // wait patiently for the window manager death
543 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700544 mWindowManager = defaultServiceManager()->getService(name);
545 if (mWindowManager != 0) {
546 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547 }
Robert Carr720e5062018-07-30 17:45:14 -0700548 sp<IBinder> input(defaultServiceManager()->getService(
549 String16("inputflinger")));
550 if (input == nullptr) {
551 ALOGE("Failed to link to input service");
552 } else {
553 mInputFlinger = interface_cast<IInputFlinger>(input);
554 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555
Steven Thomas050b2c82017-03-06 11:45:16 -0800556 if (mVrFlinger) {
557 mVrFlinger->OnBootFinished();
558 }
559
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700561 // formerly we would just kill the process, but we now ask it to exit so it
562 // can choose where to stop the animation.
563 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700564
565 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
566 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
567 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700568
Ana Krulecbd6654b2019-02-15 15:18:15 -0800569 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800570 readPersistentProperties();
571 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800572
Steven Thomase9eb1832019-08-28 16:08:35 -0700573 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
574 // set the refresh rate according to the policy
575 const auto& performanceRefreshRate =
576 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800577
Steven Thomase9eb1832019-08-28 16:08:35 -0700578 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
579 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
580 } else {
581 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::Changed);
582 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800583 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800584 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800585}
586
Dan Stoza436ccf32018-06-21 12:10:12 -0700587uint32_t SurfaceFlinger::getNewTexture() {
588 {
589 std::lock_guard lock(mTexturePoolMutex);
590 if (!mTexturePool.empty()) {
591 uint32_t name = mTexturePool.back();
592 mTexturePool.pop_back();
593 ATRACE_INT("TexturePoolSize", mTexturePool.size());
594 return name;
595 }
596
597 // The pool was too small, so increase it for the future
598 ++mTexturePoolSize;
599 }
600
601 // The pool was empty, so we need to get a new texture name directly using a
602 // blocking call to the main thread
603 uint32_t name = 0;
604 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
605 return name;
606}
607
Mathias Agopian3f844832013-08-07 21:24:32 -0700608void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700609 std::lock_guard lock(mTexturePoolMutex);
610 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
611 // to actually delete this or not based on mTexturePoolSize
612 mTexturePool.push_back(texture);
613 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700614}
615
Wei Wangf9b05ee2017-07-19 20:59:39 -0700616// Do not call property_set on main thread which will be blocked by init
617// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700619 ALOGI( "SurfaceFlinger's main thread ready to run. "
620 "Initializing graphics H/W...");
621
Ana Krulec757f63a2019-01-25 10:46:18 -0800622 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700627 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700628 renderEngineFeature |= (useColorManagement ?
629 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700630 renderEngineFeature |= (useContextPriority ?
631 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700632 renderEngineFeature |=
633 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
634 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700635
636 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800637 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700638 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700639 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800640 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700641
642 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
643 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700644 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
645 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800646 // Process any initial hotplug and resulting display changes.
647 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 const auto display = getDefaultDisplayDeviceLocked();
649 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700650 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800652
Steven Thomas050b2c82017-03-06 11:45:16 -0800653 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700655 // This callback is called from the vr flinger dispatch thread. We
656 // need to call signalTransaction(), which requires holding
657 // mStateLock when we're not on the main thread. Acquiring
658 // mStateLock from the vr flinger dispatch thread might trigger a
659 // deadlock in surface flinger (see b/66916578), so post a message
660 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700662 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
663 mVrFlingerRequestsDisplay = requestDisplay;
664 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
668 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700669 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 .value_or(0),
671 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 if (!mVrFlinger) {
673 ALOGE("Failed to start vrflinger");
674 }
675 }
676
Mathias Agopian92a979a2012-08-02 18:32:23 -0700677 // initialize our drawing state
678 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700679
Andy McFadden13a082e2012-08-24 10:16:42 -0700680 // set initial conditions (e.g. unblank default device)
681 initializeDisplays();
682
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700683 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700684
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700686
687 const bool presentFenceReliable =
688 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
689 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690
691 if (mStartPropertySetThread->Start() != NO_ERROR) {
692 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800693 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800694
Dan Stoza9e56aa02015-11-02 13:00:03 -0800695 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700696}
697
Romain Guy11d63f42017-07-20 12:47:14 -0700698void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700699 Mutex::Autolock _l(mStateLock);
700
Romain Guy11d63f42017-07-20 12:47:14 -0700701 char value[PROPERTY_VALUE_MAX];
702
703 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800704 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700705 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800706 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100707
708 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700709 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800710
711 property_get("persist.sys.sf.color_mode", value, "0");
712 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700713}
714
Mathias Agopiana67e4182012-06-19 17:26:12 -0700715void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800716 // Start boot animation service by setting a property mailbox
717 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800719 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 if (mStartPropertySetThread->join() != NO_ERROR) {
721 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700723}
724
Mathias Agopian875d8e12013-06-07 15:35:48 -0700725size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700726 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700727}
728
Mathias Agopian875d8e12013-06-07 15:35:48 -0700729size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700730 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700731}
732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800734
Jamie Gennis582270d2011-08-17 18:19:00 -0700735bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800737 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800738 return authenticateSurfaceTextureLocked(bufferProducer);
739}
740
741bool SurfaceFlinger::authenticateSurfaceTextureLocked(
742 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800743 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800744 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800745}
746
Brian Anderson6b376712017-04-04 10:51:39 -0700747status_t SurfaceFlinger::getSupportedFrameTimestamps(
748 std::vector<FrameEvent>* outSupported) const {
749 *outSupported = {
750 FrameEvent::REQUESTED_PRESENT,
751 FrameEvent::ACQUIRE,
752 FrameEvent::LATCH,
753 FrameEvent::FIRST_REFRESH_START,
754 FrameEvent::LAST_REFRESH_START,
755 FrameEvent::GPU_COMPOSITION_DONE,
756 FrameEvent::DEQUEUE_READY,
757 FrameEvent::RELEASE,
758 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700759 ConditionalLock _l(mStateLock,
760 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700761 if (!getHwComposer().hasCapability(
762 HWC2::Capability::PresentFenceIsNotReliable)) {
763 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
764 }
765 return NO_ERROR;
766}
767
Dominik Laskowski22488f62019-03-28 09:53:04 -0700768status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
769 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700770 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700771 return BAD_VALUE;
772 }
773
Dominik Laskowski22488f62019-03-28 09:53:04 -0700774 Mutex::Autolock lock(mStateLock);
775
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800776 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700777 if (!displayId) {
778 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700779 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700780
Mathias Agopian8b736f12012-08-13 17:54:26 -0700781 // TODO: Not sure if display density should handled by SF any longer
782 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700783 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700784 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700785 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800786 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700787 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700788 }
789 return density;
790 }
791 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700792 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700793 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700794 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700795 return getDensityFromProperty("ro.sf.lcd_density"); }
796 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700797
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700799
Dominik Laskowski075d3172018-05-24 15:50:06 -0700800 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 DisplayInfo info = DisplayInfo();
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803 float xdpi = hwConfig->getDpiX();
804 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700806 info.w = hwConfig->getWidth();
807 info.h = hwConfig->getHeight();
808 // Default display viewport to display width and height
809 info.viewportW = info.w;
810 info.viewportH = info.h;
811
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800812 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 // The density of the device is provided by a build property
814 float density = Density::getBuildDensity() / 160.0f;
815 if (density == 0) {
816 // the build doesn't provide a density -- this is wrong!
817 // use xdpi instead
818 ALOGE("ro.sf.lcd_density must be defined as a build property");
819 density = xdpi / 160.0f;
820 }
821 if (Density::getEmuDensity()) {
822 // if "qemu.sf.lcd_density" is specified, it overrides everything
823 xdpi = ydpi = density = Density::getEmuDensity();
824 density /= 160.0f;
825 }
826 info.density = density;
827
828 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700829 const auto display = getDefaultDisplayDeviceLocked();
830 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700831
832 // This is for screenrecord
833 const Rect viewport = display->getViewport();
834 if (viewport.isValid()) {
835 info.viewportW = uint32_t(viewport.getWidth());
836 info.viewportH = uint32_t(viewport.getHeight());
837 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 } else {
839 // TODO: where should this value come from?
840 static const int TV_DENSITY = 213;
841 info.density = TV_DENSITY / 160.0f;
842 info.orientation = 0;
843 }
844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 info.xdpi = xdpi;
846 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800847 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomase9eb1832019-08-28 16:08:35 -0700848 const auto refreshRateType =
849 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700850 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
851 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852
Andy McFadden91b2ca82014-06-13 14:04:23 -0700853 // This is how far in advance a buffer must be queued for
854 // presentation at a given time. If you want a buffer to appear
855 // on the screen at time N, you must submit the buffer before
856 // (N - presentationDeadline).
857 //
858 // Normally it's one full refresh period (to give SF a chance to
859 // latch the buffer), but this can be reduced by configuring a
860 // DispSync offset. Any additional delays introduced by the hardware
861 // composer or panel must be accounted for here.
862 //
863 // We add an additional 1ms to allow for processing time and
864 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700865 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700866
867 // All non-virtual displays are currently considered secure.
868 info.secure = true;
869
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800870 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700871 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800872 std::swap(info.w, info.h);
873 }
874
Michael Wright28f24d02016-07-12 13:30:53 -0700875 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700876 }
877
Dan Stoza7f7da322014-05-02 15:26:25 -0700878 return NO_ERROR;
879}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700880
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700881status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
882 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700883 return BAD_VALUE;
884 }
885
Ana Krulecc2870422019-01-29 19:00:58 -0800886 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700887 return NO_ERROR;
888}
889
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
891 const auto display = getDisplayDevice(displayToken);
892 if (!display) {
893 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800894 return BAD_VALUE;
895 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700896
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700897 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700898}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700899
Ady Abraham03b02dd2019-03-21 15:40:11 -0700900void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800901 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800902
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800903 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800904 // config twice. However event generation config might have changed so we need to update it
905 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800906 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700907 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
908 mDesiredActiveConfig = info;
909 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800910
911 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800912 // This will trigger HWC refresh without resetting the idle timer.
913 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700914 // Start receiving vsync samples now, so that we can detect a period
915 // switch.
916 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700917 // As we called to set period, we will call to onRefreshRateChangeCompleted once
918 // DispSync model is locked.
919 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700920 mPhaseOffsets->setRefreshRateType(info.type);
921 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700922 mVsyncModulator.setPhaseOffsets(early, gl, late,
923 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800925 mDesiredActiveConfigChanged = true;
926 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700927
928 if (mRefreshRateOverlay) {
929 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
930 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931}
932
933status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
934 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800935
936 std::vector<int32_t> allowedConfig;
937 allowedConfig.push_back(mode);
938
939 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940}
941
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942void SurfaceFlinger::setActiveConfigInternal() {
943 ATRACE_CALL();
944
Dominik Laskowski22488f62019-03-28 09:53:04 -0700945 const auto display = getDefaultDisplayDeviceLocked();
946 if (!display) {
947 return;
948 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949
Dominik Laskowski22488f62019-03-28 09:53:04 -0700950 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomase9eb1832019-08-28 16:08:35 -0700951 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
952 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700953
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954 display->setActiveConfig(mUpcomingActiveConfig.configId);
955
Alec Mouri754c98a2019-03-18 18:53:42 -0700956 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800957 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700958 mVsyncModulator.setPhaseOffsets(early, gl, late,
959 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700961
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800962 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800963 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
964 mUpcomingActiveConfig.configId);
965 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966}
967
Ady Abraham53852a52019-05-28 18:07:44 -0700968void SurfaceFlinger::desiredActiveConfigChangeDone() {
969 std::lock_guard<std::mutex> lock(mActiveConfigLock);
970 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
971 mDesiredActiveConfigChanged = false;
972 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
973
974 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
975 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
976 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700977 mVsyncModulator.setPhaseOffsets(early, gl, late,
978 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -0700979}
980
Dominik Laskowski22488f62019-03-28 09:53:04 -0700981bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800982 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700984 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800985 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700986 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800987 return true;
988 }
989
990 // We received the present fence from the HWC, so we assume it successfully updated
991 // the config, hence we update SF.
992 mCheckPendingFence = false;
993 setActiveConfigInternal();
994 }
995
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996 // Store the local variable to release the lock.
997 ActiveConfigInfo desiredActiveConfig;
998 {
999 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000 if (!mDesiredActiveConfigChanged) {
1001 return false;
1002 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001003 desiredActiveConfig = mDesiredActiveConfig;
1004 }
1005
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1008 // display is not valid or we are already in the requested mode
1009 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001010 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013
Ady Abraham838de062019-02-04 10:24:03 -08001014 // Desired active config was set, it is different than the config currently in use, however
1015 // allowed configs might have change by the time we process the refresh.
1016 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001017 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001018 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001019 return false;
1020 }
Alec Mouri7f015182019-07-11 13:56:22 -07001021
Ady Abrahamb838aed2019-02-12 15:30:16 -08001022 mUpcomingActiveConfig = desiredActiveConfig;
1023 const auto displayId = display->getId();
1024 LOG_ALWAYS_FATAL_IF(!displayId);
1025
1026 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1027 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1028
1029 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001031 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001033}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1036 Vector<ColorMode>* outColorModes) {
1037 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001038 return BAD_VALUE;
1039 }
1040
Peiyong Lina52f0292018-03-14 17:26:31 -07001041 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001042 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001043 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001044 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1045
1046 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1047 if (!displayId) {
1048 return NAME_NOT_FOUND;
1049 }
1050
Dominik Laskowski075d3172018-05-24 15:50:06 -07001051 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001052 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001053 }
Michael Wright28f24d02016-07-12 13:30:53 -07001054 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001055
1056 // If it's built-in display and the configuration claims it's not wide color capable,
1057 // filter out all wide color modes. The typical reason why this happens is that the
1058 // hardware is not good enough to support GPU composition of wide color, and thus the
1059 // OEMs choose to disable this capability.
1060 if (isInternalDisplay && !hasWideColorDisplay) {
1061 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1062 isWideColorMode);
1063 } else {
1064 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1065 }
Michael Wright28f24d02016-07-12 13:30:53 -07001066
1067 return NO_ERROR;
1068}
1069
Daniel Solomon42d04562019-01-20 21:03:19 -08001070status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1071 ui::DisplayPrimaries &primaries) {
1072 if (!displayToken) {
1073 return BAD_VALUE;
1074 }
1075
1076 // Currently we only support this API for a single internal display.
1077 if (getInternalDisplayToken() != displayToken) {
1078 return BAD_VALUE;
1079 }
1080
1081 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1082 return NO_ERROR;
1083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1086 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001087 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001088 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001093 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 Vector<ColorMode> modes;
1095 getDisplayColorModes(displayToken, &modes);
1096 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1097 if (mode < ColorMode::NATIVE || !exists) {
1098 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1099 decodeColorMode(mode).c_str(), mode, displayToken.get());
1100 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const auto display = getDisplayDevice(displayToken);
1103 if (!display) {
1104 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1105 decodeColorMode(mode).c_str(), mode, displayToken.get());
1106 } else if (display->isVirtual()) {
1107 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1108 decodeColorMode(mode).c_str(), mode);
1109 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001110 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1111 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112 }
1113 }));
1114
Michael Wright28f24d02016-07-12 13:30:53 -07001115 return NO_ERROR;
1116}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001117
Svetoslavd85084b2014-03-20 10:28:31 -07001118status_t SurfaceFlinger::clearAnimationFrameStats() {
1119 Mutex::Autolock _l(mStateLock);
1120 mAnimFrameTracker.clearStats();
1121 return NO_ERROR;
1122}
1123
1124status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1125 Mutex::Autolock _l(mStateLock);
1126 mAnimFrameTracker.getStats(outStats);
1127 return NO_ERROR;
1128}
1129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1131 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001132 Mutex::Autolock _l(mStateLock);
1133
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001134 const auto display = getDisplayDeviceLocked(displayToken);
1135 if (!display) {
1136 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001137 return BAD_VALUE;
1138 }
1139
Peiyong Linfb069302018-04-25 14:34:31 -07001140 // At this point the DisplayDeivce should already be set up,
1141 // meaning the luminance information is already queried from
1142 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001143 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001144 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1145 capabilities.getDesiredMaxLuminance(),
1146 capabilities.getDesiredMaxAverageLuminance(),
1147 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001148
1149 return NO_ERROR;
1150}
1151
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001152status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1153 ui::PixelFormat* outFormat,
1154 ui::Dataspace* outDataspace,
1155 uint8_t* outComponentMask) const {
1156 if (!outFormat || !outDataspace || !outComponentMask) {
1157 return BAD_VALUE;
1158 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001159 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001160 if (!display || !display->getId()) {
1161 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1162 return BAD_VALUE;
1163 }
1164 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1165 outDataspace, outComponentMask);
1166}
1167
Kevin DuBois74e53772018-11-19 10:52:38 -08001168status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1169 bool enable, uint8_t componentMask,
1170 uint64_t maxFrames) const {
1171 const auto display = getDisplayDevice(displayToken);
1172 if (!display || !display->getId()) {
1173 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1174 return BAD_VALUE;
1175 }
1176
1177 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1178 componentMask, maxFrames);
1179}
1180
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001181status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1182 uint64_t maxFrames, uint64_t timestamp,
1183 DisplayedFrameStats* outStats) const {
1184 const auto display = getDisplayDevice(displayToken);
1185 if (!display || !display->getId()) {
1186 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1187 return BAD_VALUE;
1188 }
1189
1190 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1191 outStats);
1192}
1193
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001194status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1195 if (!outSupported) {
1196 return BAD_VALUE;
1197 }
1198 *outSupported = getRenderEngine().supportsProtectedContent();
1199 return NO_ERROR;
1200}
1201
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001202status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1203 bool* outIsWideColorDisplay) const {
1204 if (!displayToken || !outIsWideColorDisplay) {
1205 return BAD_VALUE;
1206 }
1207 Mutex::Autolock _l(mStateLock);
1208 const auto display = getDisplayDeviceLocked(displayToken);
1209 if (!display) {
1210 return BAD_VALUE;
1211 }
Peiyong Linff84a152019-05-17 18:36:19 -07001212
1213 // Use hasWideColorDisplay to override built-in display.
1214 const auto displayId = display->getId();
1215 if (displayId && displayId == getInternalDisplayIdLocked()) {
1216 *outIsWideColorDisplay = hasWideColorDisplay;
1217 return NO_ERROR;
1218 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001219 *outIsWideColorDisplay = display->hasWideColorGamut();
1220 return NO_ERROR;
1221}
1222
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001223status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001224 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001225 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226
Chia-I Wu90f669f2017-10-05 14:24:41 -07001227 if (mInjectVSyncs == enable) {
1228 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001229 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001230
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001231 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001232 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001233 if (enable) {
1234 ALOGV("VSync Injections enabled");
1235 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001236 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001237 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001238 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001239 impl::EventThread::InterceptVSyncsCallback(),
1240 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001241 }
Steven Thomase9eb1832019-08-28 16:08:35 -07001242 mEventQueue->setEventThread(mInjectorEventThread.get(), [&] { mScheduler->resync(); });
Chia-I Wu90f669f2017-10-05 14:24:41 -07001243 } else {
1244 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001245 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
Steven Thomase9eb1832019-08-28 16:08:35 -07001246 [&] { mScheduler->resync(); });
Chia-I Wu90f669f2017-10-05 14:24:41 -07001247 }
1248
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001249 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001250 }));
1251
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001252 return NO_ERROR;
1253}
1254
1255status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001256 Mutex::Autolock _l(mStateLock);
1257
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001258 if (!mInjectVSyncs) {
1259 ALOGE("VSync Injections not enabled");
1260 return BAD_VALUE;
1261 }
1262 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1263 ALOGV("Injecting VSync inside SurfaceFlinger");
1264 mVSyncInjector->onInjectSyncEvent(when);
1265 }
1266 return NO_ERROR;
1267}
1268
Lloyd Pique755e3192018-01-31 16:46:15 -08001269status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1270 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001271 // Try to acquire a lock for 1s, fail gracefully
1272 const status_t err = mStateLock.timedLock(s2ns(1));
1273 const bool locked = (err == NO_ERROR);
1274 if (!locked) {
1275 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1276 return TIMED_OUT;
1277 }
1278
1279 outLayers->clear();
1280 mCurrentState.traverseInZOrder([&](Layer* layer) {
1281 outLayers->push_back(layer->getLayerDebugInfo());
1282 });
1283
1284 mStateLock.unlock();
1285 return NO_ERROR;
1286}
1287
Peiyong Linc6780972018-10-28 15:24:08 -07001288status_t SurfaceFlinger::getCompositionPreference(
1289 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1290 Dataspace* outWideColorGamutDataspace,
1291 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001292 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001293 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001294 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001295 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001296 return NO_ERROR;
1297}
1298
Dan Stozaec460082018-12-17 15:35:09 -08001299status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1300 const sp<IBinder>& stopLayerHandle,
1301 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001302 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001303 return BAD_VALUE;
1304 }
1305 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001306 return NO_ERROR;
1307}
1308
Dan Stozaec460082018-12-17 15:35:09 -08001309status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001310 if (!listener) {
1311 return BAD_VALUE;
1312 }
Dan Stozaec460082018-12-17 15:35:09 -08001313 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001314 return NO_ERROR;
1315}
Dan Gittik57e63c52019-01-18 16:37:54 +00001316
1317status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1318 bool* outSupport) const {
1319 if (!displayToken || !outSupport) {
1320 return BAD_VALUE;
1321 }
1322 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1323 if (!displayId) {
1324 return NAME_NOT_FOUND;
1325 }
1326 *outSupport =
1327 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1328 return NO_ERROR;
1329}
1330
1331status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1332 float brightness) const {
1333 if (!displayToken) {
1334 return BAD_VALUE;
1335 }
1336 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1337 if (!displayId) {
1338 return NAME_NOT_FOUND;
1339 }
1340 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1341}
1342
Ady Abraham8532d012019-05-08 14:50:56 -07001343status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1344 PowerHint powerHint = static_cast<PowerHint>(hintId);
1345
1346 if (powerHint == PowerHint::INTERACTION) {
1347 mScheduler->notifyTouchEvent();
1348 }
1349
1350 return NO_ERROR;
1351}
1352
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001353// ----------------------------------------------------------------------------
1354
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001355sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001356 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001357 const auto& handle =
1358 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001359
Steven Thomase9eb1832019-08-28 16:08:35 -07001360 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001361}
1362
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001363// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001364
1365void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001366 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001367}
1368
1369void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001370 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001371 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001372}
1373
1374void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001375 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001376 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001377}
1378
1379void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001380 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001381 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001382}
1383
1384status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001385 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001386 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001387}
1388
1389status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001390 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001391 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001392 if (res == NO_ERROR) {
1393 msg->wait();
1394 }
1395 return res;
1396}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001398void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001399 do {
1400 waitForEvent();
1401 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001402}
1403
Dominik Laskowski83b88212018-12-11 13:34:06 -08001404nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001405 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001406 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1407 return 0;
1408 }
1409
1410 const auto config = getHwComposer().getActiveConfig(*displayId);
1411 return config ? config->getVsyncPeriod() : 0;
1412}
1413
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001414void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1415 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001416 ATRACE_NAME("SF onVsync");
1417
Steven Thomas3cfac282017-02-06 12:29:30 -08001418 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001419 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 return;
1422 }
1423
Dominik Laskowski075d3172018-05-24 15:50:06 -07001424 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001425 return;
1426 }
1427
Dominik Laskowski075d3172018-05-24 15:50:06 -07001428 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001429 // For now, we don't do anything with external display vsyncs.
1430 return;
1431 }
1432
Alec Mourif8e689c2019-05-20 18:32:22 -07001433 bool periodFlushed = false;
1434 mScheduler->addResyncSample(timestamp, &periodFlushed);
1435 if (periodFlushed) {
1436 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001437 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001438}
1439
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001440void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001441 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1442 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001443}
1444
Dominik Laskowski22488f62019-03-28 09:53:04 -07001445bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1446 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001447}
1448
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001449void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001450 const auto display = getDefaultDisplayDeviceLocked();
1451 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001452 return;
1453 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001454 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001455
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 // Don't do any updating if the current fps is the same as the new one.
Steven Thomase9eb1832019-08-28 16:08:35 -07001457 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1458 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001459
Dominik Laskowski22488f62019-03-28 09:53:04 -07001460 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001461 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1462 return;
1463 }
1464
Dominik Laskowski22488f62019-03-28 09:53:04 -07001465 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001466}
1467
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001468void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001469 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001471 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001472
Lloyd Piqueba04e622017-12-14 17:11:26 -08001473 // Ignore events that do not have the right sequenceId.
1474 if (sequenceId != getBE().mComposerSequenceId) {
1475 return;
1476 }
1477
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 // Only lock if we're not on the main thread. This function is normally
1479 // called on a hwbinder thread, but for the primary display it's called on
1480 // the main thread with the state lock already held, so don't attempt to
1481 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001482 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001483
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001484 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001485
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001486 if (std::this_thread::get_id() == mMainThreadId) {
1487 // Process all pending hot plug events immediately if we are on the main thread.
1488 processDisplayHotplugEventsLocked();
1489 }
1490
Lloyd Piqueba04e622017-12-14 17:11:26 -08001491 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001492}
1493
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001494void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001495 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001496 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001498 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001499 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001500}
1501
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001502void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001503 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001504
1505 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1506 // display power state.
1507 postMessageAsync(new LambdaMessage(
1508 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1509}
1510
1511void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1512 ATRACE_CALL();
1513
Ady Abraham27c70212019-06-11 10:52:26 -07001514 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1515
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001516 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001517 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1518 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001519 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001520 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001521 }
Mathias Agopian86303202012-07-24 22:46:10 -07001522}
1523
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001524// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001525void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001526 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527 // Clear the drawing state so that the logic inside of
1528 // handleTransactionLocked will fire. It will determine the delta between
1529 // mCurrentState and mDrawingState and re-apply all changes when we make the
1530 // transition.
1531 mDrawingState.displays.clear();
1532 mDisplays.clear();
1533}
1534
Steven Thomas050b2c82017-03-06 11:45:16 -08001535void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001536 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001537 if (!mVrFlinger)
1538 return;
1539 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001541 return;
1542 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001543
Lloyd Pique441d5042018-10-18 16:49:51 -07001544 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 ALOGE("Vr flinger is only supported for remote hardware composer"
1546 " service connections. Ignoring request to transition to vr"
1547 " flinger.");
1548 mVrFlingerRequestsDisplay = false;
1549 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001550 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001551
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001552 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553
Steven Thomas0123ac62018-07-12 11:32:34 -07001554 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001555 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001556
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001557 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001558
1559 // Clear out all the output layers from the composition engine for all
1560 // displays before destroying the hardware composer interface. This ensures
1561 // any HWC layers are destroyed through that interface before it becomes
1562 // invalid.
1563 for (const auto& [token, displayDevice] : mDisplays) {
1564 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1565 compositionengine::Output::OutputLayers());
1566 }
1567
Steven Thomas0123ac62018-07-12 11:32:34 -07001568 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1569 // called below. Clear the reference now so we don't accidentally use it
1570 // later.
1571 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001574 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001576
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001578 // Delete the current instance before creating the new one
1579 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1580 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1581 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1582 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001583
Lloyd Pique441d5042018-10-18 16:49:51 -07001584 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001585 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001586
1587 if (vrFlingerRequestsDisplay) {
1588 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001589 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590
1591 mVisibleRegionsDirty = true;
1592 invalidateHwcGeometry();
1593
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001594 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001595 display = getDefaultDisplayDeviceLocked();
1596 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001597 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001598
Steven Thomasb02664d2017-07-26 18:48:28 -07001599 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001600 const nsecs_t vsyncPeriod = getVsyncPeriod();
1601 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001602
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001603 // The present fences returned from vr_hwc are not an accurate
1604 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001605 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001606
Steven Thomasb02664d2017-07-26 18:48:28 -07001607 // Use phase of 0 since phase is not known.
1608 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001609 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001610 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001611
Ana Krulecc2870422019-01-29 19:00:58 -08001612 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001613
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001614 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001615 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001616}
1617
Ady Abrahamb40b0262019-09-19 11:32:43 -07001618bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1619 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001620 // We are storing the last 2 present fences. If sf's phase offset is to be
1621 // woken up before the actual vsync but targeting the next vsync, we need to check
1622 // fence N-2
1623 const sp<Fence>& fence =
1624 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1625 ? mPreviousPresentFences[0]
1626 : mPreviousPresentFences[1];
1627
Ady Abrahamb40b0262019-09-19 11:32:43 -07001628 if (fence == Fence::NO_FENCE) {
1629 return false;
1630 }
1631
1632 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1633 fence->wait(graceTimeMs);
1634 }
1635
1636 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001637}
1638
Ady Abraham7c03ce62019-07-19 10:59:45 -07001639void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
Alec Mouriaa614192019-06-06 13:28:34 -07001640 DisplayStatInfo stats;
1641 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001642 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001643 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham7c03ce62019-07-19 10:59:45 -07001644 mExpectedPresentTime =
Alec Mouriaa614192019-06-06 13:28:34 -07001645 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1646 ? presentTime
1647 : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001648}
1649
Dominik Laskowski22488f62019-03-28 09:53:04 -07001650void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001651 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001652 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001653 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001654 // calculate the expected present time once and use the cached
1655 // value throughout this frame to make sure all layers are
1656 // seeing this same value.
1657 populateExpectedPresentTime();
1658
Ady Abrahamb40b0262019-09-19 11:32:43 -07001659 // When Backpressure propagation is enabled we want to give a small grace period
1660 // for the present fence to fire instead of just giving up on this frame to handle cases
1661 // where present fence is just about to get signaled.
1662 const int graceTimeForPresentFenceMs =
1663 (mPropagateBackpressure &&
1664 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1665 ? 1
1666 : 0;
1667 bool frameMissed = previousFrameMissed(graceTimeForPresentFenceMs);
Alec Mouricc0fc602019-02-26 21:45:19 -08001668 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1669 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1670 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1671 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1672 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1673 if (frameMissed) {
1674 mFrameMissedCount++;
1675 mTimeStats->incrementMissedFrames();
1676 }
1677
Alec Mouri40189b02019-03-05 15:07:54 -08001678 if (hwcFrameMissed) {
1679 mHwcFrameMissedCount++;
1680 }
1681
1682 if (gpuFrameMissed) {
1683 mGpuFrameMissedCount++;
1684 }
1685
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001686 if (mUseSmart90ForVideo) {
1687 // This call is made each time SF wakes up and creates a new frame. It is part
1688 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001689 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001690 }
1691
Ady Abrahamb838aed2019-02-12 15:30:16 -08001692 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001693 break;
1694 }
1695
Ady Abrahamadb9a992019-09-19 21:21:55 +00001696 if (frameMissed && mPropagateBackpressure) {
1697 if ((hwcFrameMissed && !gpuFrameMissed) ||
1698 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001699 signalLayerUpdate();
1700 break;
1701 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001702 }
Dan Stoza50182882016-07-08 12:02:20 -07001703
Steven Thomas050b2c82017-03-06 11:45:16 -08001704 // Now that we're going to make it to the handleMessageTransaction()
1705 // call below it's safe to call updateVrFlinger(), which will
1706 // potentially trigger a display handoff.
1707 updateVrFlinger();
1708
Dan Stoza6b9454d2014-11-07 16:00:59 -08001709 bool refreshNeeded = handleMessageTransaction();
1710 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001711
1712 updateCursorAsync();
1713 updateInputFlinger();
1714
Dan Stoza58784442014-12-02 16:58:17 -08001715 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001716 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001717 // Signal a refresh if a transaction modified the window state,
1718 // a new buffer was latched, or if HWC has requested a full
1719 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001720 signalRefresh();
1721 }
1722 break;
1723 }
1724 case MessageQueue::REFRESH: {
1725 handleMessageRefresh();
1726 break;
1727 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001728 }
1729}
1730
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001732 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001733 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001734
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001735 bool flushedATransaction = flushTransactionQueues();
1736
1737 bool runHandleTransaction = transactionFlags &&
1738 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1739
1740 if (runHandleTransaction) {
1741 handleTransaction(eTransactionMask);
1742 } else {
1743 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001744 }
1745
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001746 if (transactionFlushNeeded()) {
1747 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001748 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001749
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001750 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001751}
1752
Mathias Agopian4fec8732012-06-29 14:12:52 -07001753void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001755
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001756 mRefreshPending = false;
1757
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001758 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001759 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001760 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001761 calculateWorkingSet();
Nataniel Borgesc4def152019-09-26 15:20:00 +02001762 long compositionTime = elapsedRealtimeNano();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001763 for (const auto& [token, display] : mDisplays) {
1764 beginFrame(display);
1765 prepareFrame(display);
1766 doDebugFlashRegions(display, repaintEverything);
1767 doComposition(display, repaintEverything);
1768 }
1769
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001770 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001771
1772 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001773 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001774
Dan Stozabfbffeb2016-07-21 14:49:33 -07001775 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001776 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001777 for (const auto& [token, displayDevice] : mDisplays) {
1778 auto display = displayDevice->getCompositionDisplay();
1779 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001780 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001781 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001782 mHadDeviceComposition =
1783 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001784 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001785
Jorim Jaggi90535212018-05-23 23:44:06 +02001786 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001787
David Sodman7e4ae112018-02-09 15:02:28 -08001788 mLayersWithQueuedFrames.clear();
Vishnu Nair6bfe2642019-06-07 14:53:14 -07001789 if (mVisibleRegionsDirty) {
1790 mVisibleRegionsDirty = false;
1791 if (mTracingEnabled) {
Nataniel Borgesc4def152019-09-26 15:20:00 +02001792 mTracing.notify(compositionTime, "visibleRegionsDirty");
Vishnu Nair6bfe2642019-06-07 14:53:14 -07001793 }
1794 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001795}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001796
David Sodmanfa9b2af2017-12-24 13:28:59 -08001797
1798bool SurfaceFlinger::handleMessageInvalidate() {
1799 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001800 bool refreshNeeded = handlePageFlip();
1801
Vishnu Nair4351ad52019-02-11 14:13:02 -08001802 if (mVisibleRegionsDirty) {
1803 computeLayerBounds();
1804 }
1805
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001806 for (auto& layer : mLayersPendingRefresh) {
1807 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001808 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001809 invalidateLayerStack(layer, visibleReg);
1810 }
1811 mLayersPendingRefresh.clear();
1812 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001813}
1814
David Sodman79bba0e2018-08-05 18:07:49 -07001815void SurfaceFlinger::calculateWorkingSet() {
1816 ATRACE_CALL();
1817 ALOGV(__FUNCTION__);
1818
David Sodman79bba0e2018-08-05 18:07:49 -07001819 // build the h/w work list
1820 if (CC_UNLIKELY(mGeometryInvalid)) {
1821 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001822 for (const auto& [token, displayDevice] : mDisplays) {
1823 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001824
Lloyd Piquea83776c2019-01-29 18:42:32 -08001825 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001826
Lloyd Piquea83776c2019-01-29 18:42:32 -08001827 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1828 auto& compositionState = layer->editState();
1829 compositionState.forceClientComposition = false;
1830 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1831 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001832 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001833
Lloyd Piquea83776c2019-01-29 18:42:32 -08001834 // The output Z order is set here based on a simple counter.
1835 compositionState.z = zOrder++;
1836
1837 // Update the display independent composition state. This goes
1838 // to the general composition layer state structure.
1839 // TODO: Do this once per compositionengine::CompositionLayer.
1840 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1841 true);
1842
1843 // Recalculate the geometry state of the output layer.
1844 layer->updateCompositionState(true);
1845
1846 // Write the updated geometry state to the HWC
1847 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001848 }
1849 }
1850 }
1851
1852 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001853 for (const auto& [token, displayDevice] : mDisplays) {
1854 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001855 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001856 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001857 continue;
1858 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001859 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001860
1861 if (mDrawingState.colorMatrixChanged) {
1862 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001863 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001864 Dataspace targetDataspace = Dataspace::UNKNOWN;
1865 if (useColorManagement) {
1866 ColorMode colorMode;
1867 RenderIntent renderIntent;
1868 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1869 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001870
1871 if (isHdrColorMode(colorMode)) {
1872 targetDataspace = Dataspace::UNKNOWN;
1873 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1874 targetDataspace = mColorSpaceAgnosticDataspace;
1875 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001876 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001877
Lloyd Pique32cbe282018-10-19 13:09:22 -07001878 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001879 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001880 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001881 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1882 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001883 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001884 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001885 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1886 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001887 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001888 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001889 }
1890
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001891 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001892 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001893 }
1894
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001895 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001896 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001897 layer->setCompositionType(displayDevice,
1898 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001899 continue;
1900 }
1901
Lloyd Pique32cbe282018-10-19 13:09:22 -07001902 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001903 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001904 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001905 }
1906 }
1907
1908 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001909
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001910 for (const auto& [token, displayDevice] : mDisplays) {
1911 auto display = displayDevice->getCompositionDisplay();
1912 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001913 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1914 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1915 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001916 }
1917 }
David Sodman79bba0e2018-08-05 18:07:49 -07001918}
1919
Lloyd Pique32cbe282018-10-19 13:09:22 -07001920void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1921 bool repaintEverything) {
1922 auto display = displayDevice->getCompositionDisplay();
1923 const auto& displayState = display->getState();
1924
Mathias Agopiancd60f992012-08-16 16:28:27 -07001925 // is debugging enabled
1926 if (CC_LIKELY(!mDebugRegion))
1927 return;
1928
Lloyd Pique32cbe282018-10-19 13:09:22 -07001929 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001930 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001931 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001932 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001933 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001934 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001935 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001936
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001937 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001938 }
1939 }
1940
Lloyd Pique32cbe282018-10-19 13:09:22 -07001941 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001942
1943 if (mDebugRegion > 1) {
1944 usleep(mDebugRegion * 1000);
1945 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001946
Lloyd Pique32cbe282018-10-19 13:09:22 -07001947 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948}
1949
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001950void SurfaceFlinger::logLayerStats() {
1951 ATRACE_CALL();
1952 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001953 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001954 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001955 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001956 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001957 }
1958 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001959
1960 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001961 }
1962}
1963
David Sodman2b406362017-12-15 13:33:47 -08001964void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001966 ATRACE_CALL();
1967 ALOGV("preComposition");
1968
David Sodman2b406362017-12-15 13:33:47 -08001969 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1970
Mathias Agopiancd60f992012-08-16 16:28:27 -07001971 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001972 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001973 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001974 needExtraInvalidate = true;
1975 }
Robert Carr2047fae2016-11-28 14:09:09 -08001976 });
1977
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978 if (needExtraInvalidate) {
1979 signalLayerUpdate();
1980 }
1981}
1982
Ana Krulece588e312018-09-18 12:32:24 -07001983void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1984 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985 // Update queue of past composite+present times and determine the
1986 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001987 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001988 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001989 while (!getBE().mCompositePresentTimes.empty()) {
1990 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991 // Cached values should have been updated before calling this method,
1992 // which helps avoid duplicate syscalls.
1993 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1994 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1995 break;
1996 }
1997 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001998 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001999 }
2000
2001 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002002 while (getBE().mCompositePresentTimes.size() > 16) {
2003 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002004 }
2005
Ana Krulece588e312018-09-18 12:32:24 -07002006 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002007}
2008
Ana Krulece588e312018-09-18 12:32:24 -07002009void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2010 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002011 // Integer division and modulo round toward 0 not -inf, so we need to
2012 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002013 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2014 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2015 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002016
Ana Krulec757f63a2019-01-25 10:46:18 -08002017 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002018 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002019 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002020 }
2021
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002022 // Snap the latency to a value that removes scheduling jitter from the
2023 // composition and present times, which often have >1ms of jitter.
2024 // Reducing jitter is important if an app attempts to extrapolate
2025 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002026 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002027 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002028 nsecs_t bias = stats.vsyncPeriod / 2;
2029 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2030 nsecs_t snappedCompositeToPresentLatency =
2031 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002032
David Sodman99974d22017-11-28 12:04:33 -08002033 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002034 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2035 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002036 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002037}
2038
David Sodman2b406362017-12-15 13:33:47 -08002039void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002040{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002041 ATRACE_CALL();
2042 ALOGV("postComposition");
2043
Brian Anderson3546a3f2016-07-14 11:51:14 -07002044 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002045 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002046 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002047 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002048 }
2049
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002050 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002051 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002052
David Sodman73beded2017-11-15 11:56:06 -08002053 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002054 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002055 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002056 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002057 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2058 ->getRenderSurface()
2059 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002060 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061 } else {
2062 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2063 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064
David Sodman73beded2017-11-15 11:56:06 -08002065 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002066 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2067 mPreviousPresentFences[0] = displayDevice
2068 ? getHwComposer().getPresentFence(*displayDevice->getId())
2069 : Fence::NO_FENCE;
2070 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002071 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002072
Ana Krulece588e312018-09-18 12:32:24 -07002073 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002074 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
David Sodman2b406362017-12-15 13:33:47 -08002076 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077 // when we started doing work for this frame, but that should be okay
2078 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002079 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002080 CompositorTiming compositorTiming;
2081 {
David Sodman99974d22017-11-28 12:04:33 -08002082 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2083 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002084 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002085
Robert Carr2047fae2016-11-28 14:09:09 -08002086 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 bool frameLatched =
2088 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2089 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002090 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002091 recordBufferingStats(layer->getName().string(),
2092 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002093 }
Robert Carr2047fae2016-11-28 14:09:09 -08002094 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002095
Valerie Hau7687b3c2020-04-15 18:09:40 -07002096 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2097
2098 // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2099 // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2100 // metrics.
2101 {
2102 Mutex::Autolock _l(mStateLock);
2103 mTransactionCompletedThread.sendCallbacks();
2104 }
2105
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002106 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002107 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002108 }
2109
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002110 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002111 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2112 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002113 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002114 }
2115 }
2116
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002117 if (mAnimCompositionPending) {
2118 mAnimCompositionPending = false;
2119
Brian Anderson4e606e32017-03-16 15:34:57 -07002120 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002121 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002122 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002123 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002124 // The HWC doesn't support present fences, so use the refresh
2125 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002126 const nsecs_t presentTime =
2127 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002128 mAnimFrameTracker.setActualPresentTime(presentTime);
2129 }
2130 mAnimFrameTracker.advanceFrame();
2131 }
Dan Stozab90cf072015-03-05 11:05:59 -08002132
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002133 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002134 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002135 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002136 }
2137
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002138 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002139
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2141 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002142 return;
2143 }
2144
2145 nsecs_t currentTime = systemTime();
2146 if (mHasPoweredOff) {
2147 mHasPoweredOff = false;
2148 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002149 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002150 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002151 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2152 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002153 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002154 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002155 }
David Sodman4a36e932017-11-07 14:29:47 -08002156 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002157 }
David Sodman4a36e932017-11-07 14:29:47 -08002158 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002159
2160 {
2161 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002162 if (mTexturePool.size() < mTexturePoolSize) {
2163 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002164 const size_t offset = mTexturePool.size();
2165 mTexturePool.resize(mTexturePoolSize);
2166 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2167 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002168 } else if (mTexturePool.size() > mTexturePoolSize) {
2169 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2170 const size_t offset = mTexturePoolSize;
2171 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2172 mTexturePool.resize(mTexturePoolSize);
2173 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002174 }
2175 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002176
Kevin DuBois413287f2019-02-25 08:46:47 -08002177 if (mLumaSampling && mRegionSamplingThread) {
2178 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002179 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002180
2181 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2182 // side-effect of getTotalSize(), so we check that again here
2183 if (ATRACE_ENABLED()) {
2184 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2185 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002186}
2187
Vishnu Nair4351ad52019-02-11 14:13:02 -08002188void SurfaceFlinger::computeLayerBounds() {
2189 for (const auto& pair : mDisplays) {
2190 const auto& displayDevice = pair.second;
2191 const auto display = displayDevice->getCompositionDisplay();
2192 for (const auto& layer : mDrawingState.layersSortedByZ) {
2193 // only consider the layers on the given layer stack
2194 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002195 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002196 }
2197
2198 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2199 }
2200 }
2201}
2202
Mathias Agopiancd60f992012-08-16 16:28:27 -07002203void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002204 ATRACE_CALL();
2205 ALOGV("rebuildLayerStacks");
2206
Mathias Agopiancd60f992012-08-16 16:28:27 -07002207 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002208 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002209 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002210 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002211
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002212 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002213 const auto& displayDevice = pair.second;
2214 auto display = displayDevice->getCompositionDisplay();
2215 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002216 Region opaqueRegion;
2217 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002218 compositionengine::Output::OutputLayers layersSortedByZ;
2219 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002220 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002221 const ui::Transform& tr = displayState.transform;
2222 const Rect bounds = displayState.bounds;
2223 if (displayState.isEnabled) {
2224 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002225
Jeff Sharkey76488112017-02-27 14:15:18 -07002226 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002227 auto compositionLayer = layer->getCompositionLayer();
2228 if (compositionLayer == nullptr) {
2229 return;
2230 }
2231
Lloyd Pique32cbe282018-10-19 13:09:22 -07002232 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002233 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2234 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2235
Lloyd Pique07e33212018-12-18 16:33:37 -08002236 bool needsOutputLayer = false;
2237
Lloyd Piqueef36b002019-01-23 17:52:04 -08002238 if (display->belongsInOutput(layer->getLayerStack(),
2239 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 Region drawRegion(tr.transform(
2241 layer->visibleNonTransparentRegion));
2242 drawRegion.andSelf(bounds);
2243 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002244 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002245 }
Chia-I Wu83806892017-11-16 10:50:20 -08002246 }
2247
Lloyd Pique07e33212018-12-18 16:33:37 -08002248 if (needsOutputLayer) {
2249 layersSortedByZ.emplace_back(
2250 display->getOrCreateOutputLayer(displayId, compositionLayer,
2251 layerFE));
2252 deprecated_layersSortedByZ.add(layer);
2253
2254 auto& outputLayerState = layersSortedByZ.back()->editState();
2255 outputLayerState.visibleRegion =
2256 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2257 } else if (displayId) {
2258 // For layers that are being removed from a HWC display,
2259 // and that have queued frames, add them to a a list of
2260 // released layers so we can properly set a fence.
2261 bool hasExistingOutputLayer =
2262 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2263 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2264 mLayersWithQueuedFrames.cend(),
2265 layer) != mLayersWithQueuedFrames.cend();
2266
2267 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002268 layersNeedingFences.add(layer);
2269 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002271 });
2272 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002273
2274 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2275
2276 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 displayDevice->setLayersNeedingFences(layersNeedingFences);
2278
2279 Region undefinedRegion{bounds};
2280 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2281
2282 display->editState().undefinedRegion = undefinedRegion;
2283 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002284 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002285 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002286}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002287
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002289// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002290// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002291// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002292// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002293// The returned HDR data space is one of
2294// - Dataspace::UNKNOWN
2295// - Dataspace::BT2020_HLG
2296// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002297Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2298 Dataspace* outHdrDataSpace,
2299 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002300 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002301 *outHdrDataSpace = Dataspace::UNKNOWN;
2302
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002304 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002305 case Dataspace::V0_SCRGB:
2306 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002307 case Dataspace::BT2020:
2308 case Dataspace::BT2020_ITU:
2309 case Dataspace::BT2020_LINEAR:
2310 case Dataspace::DISPLAY_BT2020:
2311 bestDataSpace = Dataspace::DISPLAY_BT2020;
2312 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002313 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002314 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002315 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 case Dataspace::BT2020_PQ:
2317 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002318 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002320 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002322 case Dataspace::BT2020_HLG:
2323 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002324 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325 // When there's mixed PQ content and HLG content, we set the HDR
2326 // data space to be BT2020_PQ and convert HLG to PQ.
2327 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2328 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002329 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330 break;
2331 default:
2332 break;
2333 }
Romain Guy54f154a2017-10-24 21:40:32 +01002334 }
2335
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002336 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002337}
2338
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002339// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002340void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2341 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002342 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2343 *outMode = ColorMode::NATIVE;
2344 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002345 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002347 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002348
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002349 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002350 bool isHdrClientComposition = false;
2351 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002352
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002353 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2354
Peiyong Lina3ea5592019-02-10 14:45:00 -08002355 switch (mForceColorMode) {
2356 case ColorMode::SRGB:
2357 bestDataSpace = Dataspace::V0_SRGB;
2358 break;
2359 case ColorMode::DISPLAY_P3:
2360 bestDataSpace = Dataspace::DISPLAY_P3;
2361 break;
2362 default:
2363 break;
2364 }
2365
Peiyong Lindfde5112018-06-05 10:58:41 -07002366 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002367 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2368 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002369 if (isHdr) {
2370 bestDataSpace = hdrDataSpace;
2371 }
2372
Chia-I Wu0d711262018-05-21 15:19:35 -07002373 RenderIntent intent;
2374 switch (mDisplayColorSetting) {
2375 case DisplayColorSetting::MANAGED:
2376 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002377 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002378 break;
2379 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002380 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002381 break;
2382 default: // vendor display color setting
2383 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2384 break;
2385 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002386
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002387 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002388}
2389
Lloyd Pique32cbe282018-10-19 13:09:22 -07002390void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2391 auto display = displayDevice->getCompositionDisplay();
2392 const auto& displayState = display->getState();
2393
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002394 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002395 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2396 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002397
David Sodmanfa9b2af2017-12-24 13:28:59 -08002398 // If nothing has changed (!dirty), don't recompose.
2399 // If something changed, but we don't currently have any visible layers,
2400 // and didn't when we last did a composition, then skip it this time.
2401 // The second rule does two things:
2402 // - When all layers are removed from a display, we'll emit one black
2403 // frame, then nothing more until we get new layers.
2404 // - When a display is created with a private layer stack, we won't
2405 // emit any black frames until a layer is added to the layer stack.
2406 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002407
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 const char flagPrefix[] = {'-', '+'};
2409 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002410 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2411 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2412 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2413 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002414
Lloyd Pique31cb2942018-10-19 17:23:03 -07002415 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002416
David Sodmanfa9b2af2017-12-24 13:28:59 -08002417 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002418 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002419 }
2420}
2421
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2423 auto display = displayDevice->getCompositionDisplay();
2424 const auto& displayState = display->getState();
2425
2426 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002427 return;
David Sodman2b406362017-12-15 13:33:47 -08002428 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002429
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002430 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002432 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002433}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002436 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002437 ALOGV("doComposition");
2438
Lloyd Pique32cbe282018-10-19 13:09:22 -07002439 auto display = displayDevice->getCompositionDisplay();
2440 const auto& displayState = display->getState();
2441
2442 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002444 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002445
David Sodmanfa9b2af2017-12-24 13:28:59 -08002446 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002447 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002450 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002451 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002453}
2454
David Sodmanfa9b2af2017-12-24 13:28:59 -08002455void SurfaceFlinger::postFrame()
2456{
2457 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 const auto display = getDefaultDisplayDeviceLocked();
2459 if (display && getHwComposer().isConnected(*display->getId())) {
2460 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002461 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2462 logFrameStats();
2463 }
2464 }
2465}
2466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002468 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 auto display = displayDevice->getCompositionDisplay();
2472 const auto& displayState = display->getState();
2473 const auto displayId = display->getId();
2474
Lloyd Pique32cbe282018-10-19 13:09:22 -07002475 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 if (displayId) {
2477 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002478 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002479 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002480 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002481 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002482 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002483
Chia-I Wu7b549592017-11-15 09:14:57 -08002484 // The layer buffer from the previous frame (if any) is released
2485 // by HWC only when the release fence from this frame (if any) is
2486 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002487 if (layer->getState().hwc) {
2488 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002489 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002490 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2491 usedClientComposition =
2492 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002493 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002494
2495 // If the layer was client composited in the previous frame, we
2496 // need to merge with the previous client target acquire fence.
2497 // Since we do not track that, always merge with the current
2498 // client target acquire fence when it is available, even though
2499 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002500 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002501 releaseFence =
2502 Fence::merge("LayerRelease", releaseFence,
2503 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002504 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002505
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002506 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002507 }
Chia-I Wu83806892017-11-16 10:50:20 -08002508
2509 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002511 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002512 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002513 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002514 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002515 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002516 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002517 }
2518 }
2519
Dominik Laskowski075d3172018-05-24 15:50:06 -07002520 if (displayId) {
2521 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002522 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524}
2525
Mathias Agopian87baae12012-07-31 12:38:26 -07002526void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002527{
Mathias Agopian841cde52012-03-01 15:44:37 -08002528 ATRACE_CALL();
2529
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002530 // here we keep a copy of the drawing state (that is the state that's
2531 // going to be overwritten by handleTransactionLocked()) outside of
2532 // mStateLock so that the side-effects of the State assignment
2533 // don't happen with mStateLock held (which can cause deadlocks).
2534 State drawingState(mDrawingState);
2535
Mathias Agopianca4d3602011-05-19 15:38:14 -07002536 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002537 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538
Mathias Agopianca4d3602011-05-19 15:38:14 -07002539 // Here we're guaranteed that some transaction flags are set
2540 // so we can call handleTransactionLocked() unconditionally.
2541 // We call getTransactionFlags(), which will also clear the flags,
2542 // with mStateLock held to guarantee that mCurrentState won't change
2543 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002544
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002545 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002546 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002547 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002548
Mathias Agopianca4d3602011-05-19 15:38:14 -07002549 mDebugInTransaction = 0;
2550 invalidateHwcGeometry();
2551 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002552}
2553
Lloyd Piqueba04e622017-12-14 17:11:26 -08002554void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2555 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002556 const std::optional<DisplayIdentificationInfo> info =
2557 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002558
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560 continue;
2561 }
2562
Lloyd Piqueba04e622017-12-14 17:11:26 -08002563 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002564 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002565 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomase9eb1832019-08-28 16:08:35 -07002566 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2567 initScheduler(info->id);
2568 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002569 mPhysicalDisplayTokens[info->id] = new BBinder();
2570 DisplayDeviceState state;
2571 state.displayId = info->id;
2572 state.isSecure = true; // All physical displays are currently considered secure.
2573 state.displayName = info->name;
2574 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2575 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002576 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002577 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002578 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002579
Dominik Laskowski075d3172018-05-24 15:50:06 -07002580 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2581 if (index >= 0) {
2582 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2583 mInterceptor->saveDisplayDeletion(state.sequenceId);
2584 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002585 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002587 }
2588
2589 processDisplayChangesLocked();
2590 }
2591
2592 mPendingHotplugEvents.clear();
2593}
2594
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002595void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002596 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2597 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002598}
2599
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002602 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 const sp<IGraphicBufferProducer>& producer) {
2604 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002605 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002606 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002607 creationArgs.isSecure = state.isSecure;
2608 creationArgs.displaySurface = dispSurface;
2609 creationArgs.hasWideColorGamut = false;
2610 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002611
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002612 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 creationArgs.isPrimary = isInternalDisplay;
2614
2615 if (useColorManagement && displayId) {
2616 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002618 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002619 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002621
Dominik Laskowski7e045462018-05-30 13:02:02 -07002622 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002623 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002624 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625 }
tangrobin6753a022018-08-10 10:58:54 +08002626 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 if (displayId) {
2629 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002630 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002632 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633
Lloyd Pique90c115d2018-09-18 21:39:42 -07002634 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002636 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638 // Make sure that composition can never be stalled by a virtual display
2639 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002640 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002641 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2643 }
2644
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645 creationArgs.displayInstallOrientation =
2646 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002647
Lloyd Pique99d3da52018-01-22 17:48:03 -08002648 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002649 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002650
Lloyd Pique90c115d2018-09-18 21:39:42 -07002651 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652
2653 if (maxFrameBufferAcquiredBuffers >= 3) {
2654 nativeWindowSurface->preallocateBuffers();
2655 }
2656
2657 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002658 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002659 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002661 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002663 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2664 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002665 if (!state.isVirtual()) {
2666 LOG_ALWAYS_FATAL_IF(!displayId);
2667 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002668 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002670 display->setLayerStack(state.layerStack);
2671 display->setProjection(state.orientation, state.viewport, state.frame);
2672 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002674 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675}
2676
Lloyd Pique347200f2017-12-14 17:00:15 -08002677void SurfaceFlinger::processDisplayChangesLocked() {
2678 // here we take advantage of Vector's copy-on-write semantics to
2679 // improve performance by skipping the transaction entirely when
2680 // know that the lists are identical
2681 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2682 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2683 if (!curr.isIdenticalTo(draw)) {
2684 mVisibleRegionsDirty = true;
2685 const size_t cc = curr.size();
2686 size_t dc = draw.size();
2687
2688 // find the displays that were removed
2689 // (ie: in drawing state but not in current state)
2690 // also handle displays that changed
2691 // (ie: displays that are in both lists)
2692 for (size_t i = 0; i < dc;) {
2693 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2694 if (j < 0) {
2695 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002696 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002697 // Save display ID before disconnecting.
2698 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002699 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002700
2701 if (!display->isVirtual()) {
2702 LOG_ALWAYS_FATAL_IF(!displayId);
2703 dispatchDisplayHotplugEvent(displayId->value, false);
2704 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002706
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002708 } else {
2709 // this display is in both lists. see if something changed.
2710 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2713 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2714 if (state_binder != draw_binder) {
2715 // changing the surface is like destroying and
2716 // recreating the DisplayDevice, so we just remove it
2717 // from the drawing state, so that it get re-added
2718 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002719 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002720 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002722 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002723 mDrawingState.displays.removeItemsAt(i);
2724 dc--;
2725 // at this point we must loop to the next item
2726 continue;
2727 }
2728
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002729 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002730 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 }
2733 if ((state.orientation != draw[i].orientation) ||
2734 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002735 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002736 }
2737 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002738 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 }
2740 }
2741 }
2742 ++i;
2743 }
2744
2745 // find displays that were added
2746 // (ie: in current state but not in drawing state)
2747 for (size_t i = 0; i < cc; i++) {
2748 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2749 const DisplayDeviceState& state(curr[i]);
2750
Lloyd Pique542307f2018-10-19 13:24:08 -07002751 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 sp<IGraphicBufferProducer> producer;
2753 sp<IGraphicBufferProducer> bqProducer;
2754 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002755 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002756
Dominik Laskowski075d3172018-05-24 15:50:06 -07002757 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002758 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 // Virtual displays without a surface are dormant:
2760 // they have external state (layer stack, projection,
2761 // etc.) but no internal state (i.e. a DisplayDevice).
2762 if (state.surface != nullptr) {
2763 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002764 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 int width = 0;
2766 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2767 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2768 int height = 0;
2769 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2770 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2771 int intFormat = 0;
2772 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2773 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002774 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775
Dominik Laskowski075d3172018-05-24 15:50:06 -07002776 displayId =
2777 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 }
2779
2780 // TODO: Plumb requested format back up to consumer
2781
2782 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002783 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002784 bqProducer, bqConsumer,
2785 state.displayName);
2786
2787 dispSurface = vds;
2788 producer = vds;
2789 }
2790 } else {
2791 ALOGE_IF(state.surface != nullptr,
2792 "adding a supported display, but rendering "
2793 "surface is provided (%p), ignoring it",
2794 state.surface.get());
2795
Dominik Laskowski075d3172018-05-24 15:50:06 -07002796 displayId = state.displayId;
2797 LOG_ALWAYS_FATAL_IF(!displayId);
2798 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002799 producer = bqProducer;
2800 }
2801
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002802 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002803 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002804 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002805 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002807 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002808 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002809 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002810 }
2811 }
2812 }
2813 }
2814 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002815
2816 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002817}
2818
Mathias Agopian87baae12012-07-31 12:38:26 -07002819void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002820{
Dan Stoza7dde5992015-05-22 09:51:44 -07002821 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002822 mCurrentState.traverseInZOrder([](Layer* layer) {
2823 layer->notifyAvailableFrames();
2824 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002825
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002826 /*
2827 * Traversal of the children
2828 * (perform the transaction for each of them if needed)
2829 */
2830
Marissa Wall06255332019-03-27 13:48:27 -07002831 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002834 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835
2836 const uint32_t flags = layer->doTransaction(0);
2837 if (flags & Layer::eVisibleRegion)
2838 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002839
2840 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002841 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002842 }
Robert Carr2047fae2016-11-28 14:09:09 -08002843 });
Marissa Wall06255332019-03-27 13:48:27 -07002844 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 }
2846
2847 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002848 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 */
2850
Mathias Agopiane57f2922012-08-09 16:29:12 -07002851 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002852 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002853 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002854 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002856 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002857 // The transform hint might have changed for some layers
2858 // (either because a display has changed, or because a layer
2859 // as changed).
2860 //
2861 // Walk through all the layers in currentLayers,
2862 // and update their transform hint.
2863 //
2864 // If a layer is visible only on a single display, then that
2865 // display is used to calculate the hint, otherwise we use the
2866 // default display.
2867 //
2868 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2869 // the hint is set before we acquire a buffer from the surface texture.
2870 //
2871 // NOTE: layer transactions have taken place already, so we use their
2872 // drawing state. However, SurfaceFlinger's own transaction has not
2873 // happened yet, so we must use the current state layer list
2874 // (soon to become the drawing state list).
2875 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002877 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002878 bool first = true;
2879 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002880 // NOTE: we rely on the fact that layers are sorted by
2881 // layerStack first (so we don't have to traverse the list
2882 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002883 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002884 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002885 currentlayerStack = layerStack;
2886 // figure out if this layerstack is mirrored
2887 // (more than one display) if so, pick the default display,
2888 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 hintDisplay = nullptr;
2890 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002891 if (display->getCompositionDisplay()
2892 ->belongsInOutput(layer->getLayerStack(),
2893 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002894 if (hintDisplay) {
2895 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002896 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002897 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002898 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002899 }
2900 }
2901 }
2902 }
Chet Haase91d25932013-04-11 15:24:55 -07002903
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002904 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002905 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2906 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002907
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002908 // could be null when this layer is using a layerStack
2909 // that is not visible on any display. Also can occur at
2910 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002911 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002912 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002913
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002915 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002916 if (hintDisplay) {
2917 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002918 }
Robert Carr2047fae2016-11-28 14:09:09 -08002919
2920 first = false;
2921 });
Mathias Agopian84300952012-11-21 16:02:13 -08002922 }
2923
2924
Mathias Agopian3559b072012-08-15 13:46:03 -07002925 /*
2926 * Perform our own transaction if needed
2927 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002928
2929 if (mLayersAdded) {
2930 mLayersAdded = false;
2931 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002932 mVisibleRegionsDirty = true;
2933 }
2934
2935 // some layers might have been removed, so
2936 // we need to update the regions they're exposing.
2937 if (mLayersRemoved) {
2938 mLayersRemoved = false;
2939 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002940 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002941 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002942 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002943 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002944 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002945 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002946 }
Robert Carr2047fae2016-11-28 14:09:09 -08002947 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 }
2949
Vishnu Nairec0ab382019-02-13 15:32:56 -08002950 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002951 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002952}
2953
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002954void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002955 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002956 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002957 return;
2958 }
2959
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002960 if (mVisibleRegionsDirty || mInputInfoChanged) {
2961 mInputInfoChanged = false;
2962 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002963 } else if (mInputWindowCommands.syncInputWindows) {
2964 // If the caller requested to sync input windows, but there are no
2965 // changes to input windows, notify immediately.
2966 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002967 }
2968
Arthur Hung5845eaf2019-09-05 16:38:18 +08002969 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002970}
2971
2972void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002973 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002974
2975 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2976 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002977 // When calculating the screen bounds we ignore the transparent region since it may
2978 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002979 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002980 }
2981 });
chaviw291d88a2019-02-14 10:33:58 -08002982
2983 mInputFlinger->setInputWindows(inputHandles,
2984 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2985 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002986}
2987
Vishnu Nairec0ab382019-02-13 15:32:56 -08002988void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002989 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002990 mPendingInputWindowCommands.clear();
2991}
2992
Riley Andrews03414a12014-07-01 14:22:59 -07002993void SurfaceFlinger::updateCursorAsync()
2994{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002995 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002996 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002997 continue;
2998 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002999
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003000 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3001 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003002 }
3003 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003004}
3005
chaviw61626f22018-11-15 16:26:27 -08003006void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3007 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003008 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003009 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003010 }
3011 layer->releasePendingBuffer(systemTime());
3012}
3013
Steven Thomase9eb1832019-08-28 16:08:35 -07003014void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
3015 if (mScheduler) {
3016 // In practice it's not allowed to hotplug in/out the primary display once it's been
3017 // connected during startup, but some tests do it, so just warn and return.
3018 ALOGW("Can't re-init scheduler");
3019 return;
3020 }
3021
3022 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
3023 mRefreshRateConfigs =
3024 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
3025 getHwComposer().getConfigs(
3026 primaryDisplayId),
3027 currentConfig);
3028 mRefreshRateStats =
3029 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
3030 currentConfig, HWC_POWER_MODE_OFF);
3031 mRefreshRateStats->setConfigMode(currentConfig);
3032
3033 // start the EventThread
3034 mScheduler =
3035 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
3036 *mRefreshRateConfigs);
3037 mAppConnectionHandle =
3038 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
3039 mPhaseOffsets->getOffsetThresholdForNextVsync(),
3040 impl::EventThread::InterceptVSyncsCallback());
3041 mSfConnectionHandle =
3042 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
3043 mPhaseOffsets->getOffsetThresholdForNextVsync(),
3044 [this](nsecs_t timestamp) {
3045 mInterceptor->saveVSyncEvent(timestamp);
3046 });
3047
3048 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
3049 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
3050 mSfConnectionHandle.get());
3051
3052 mRegionSamplingThread =
3053 new RegionSamplingThread(*this, *mScheduler,
3054 RegionSamplingThread::EnvironmentTimingTunables());
3055
3056 mScheduler->setChangeRefreshRateCallback(
3057 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
3058 Mutex::Autolock lock(mStateLock);
3059 setRefreshRateTo(type, event);
3060 });
3061}
3062
Mathias Agopian4fec8732012-06-29 14:12:52 -07003063void SurfaceFlinger::commitTransaction()
3064{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003065 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003066 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 for (const auto& l : mLayersPendingRemoval) {
3068 recordBufferingStats(l->getName().string(),
3069 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003070
Lloyd Pique07e33212018-12-18 16:33:37 -08003071 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003072 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003073 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003074 }
chaviw74d90ad2019-04-26 14:45:26 -07003075
3076 // If the layer has been removed and has no parent, then it will not be reachable
3077 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3078 // ensure we can copy its current to drawing state.
3079 if (!l->getParent()) {
3080 mOffscreenLayers.emplace(l.get());
3081 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003082 }
3083 mLayersPendingRemoval.clear();
3084 }
3085
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003086 // If this transaction is part of a window animation then the next frame
3087 // we composite should be considered an animation as well.
3088 mAnimCompositionPending = mAnimTransactionPending;
3089
Nataniel Borges2b796da2019-02-15 13:32:18 -08003090 withTracingLock([&]() {
3091 mDrawingState = mCurrentState;
3092 // clear the "changed" flags in current state
3093 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003094
chaviw74d90ad2019-04-26 14:45:26 -07003095 mDrawingState.traverseInZOrder([&](Layer* layer) {
3096 layer->commitChildList();
3097
3098 // If the layer can be reached when traversing mDrawingState, then the layer is no
3099 // longer offscreen. Remove the layer from the offscreenLayer set.
3100 if (mOffscreenLayers.count(layer)) {
3101 mOffscreenLayers.erase(layer);
3102 }
3103 });
3104
3105 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003107
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003108 mTransactionPending = false;
3109 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003110 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111}
3112
Nataniel Borges2b796da2019-02-15 13:32:18 -08003113void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3114 if (mTracingEnabledChanged) {
3115 mTracingEnabled = mTracing.isEnabled();
3116 mTracingEnabledChanged = false;
3117 }
3118
3119 // Synchronize with Tracing thread
3120 std::unique_lock<std::mutex> lock;
3121 if (mTracingEnabled) {
3122 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3123 }
3124
3125 lockedOperation();
3126
3127 // Synchronize with Tracing thread
3128 if (mTracingEnabled) {
3129 lock.unlock();
3130 }
3131}
3132
chaviw74d90ad2019-04-26 14:45:26 -07003133void SurfaceFlinger::commitOffscreenLayers() {
3134 for (Layer* offscreenLayer : mOffscreenLayers) {
3135 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3136 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3137 if (!trFlags) return;
3138
3139 layer->doTransaction(0);
3140 layer->commitChildList();
3141 });
3142 }
3143}
3144
Lloyd Pique32cbe282018-10-19 13:09:22 -07003145void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003146 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003147 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003149
Lloyd Pique32cbe282018-10-19 13:09:22 -07003150 auto display = displayDevice->getCompositionDisplay();
3151
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 Region aboveOpaqueLayers;
3153 Region aboveCoveredLayers;
3154 Region dirty;
3155
Mathias Agopian87baae12012-07-31 12:38:26 -07003156 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157
Robert Carr2047fae2016-11-28 14:09:09 -08003158 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003159 // start with the whole surface at its current location
3160 const Layer::State& s(layer->getDrawingState());
3161
Jesse Hall01e29052013-02-19 16:13:35 -08003162 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003163 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003164 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003165 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003166
Mathias Agopianab028732010-03-16 16:41:46 -07003167 /*
3168 * opaqueRegion: area of a surface that is fully opaque.
3169 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003171
3172 /*
3173 * visibleRegion: area of a surface that is visible on screen
3174 * and not fully transparent. This is essentially the layer's
3175 * footprint minus the opaque regions above it.
3176 * Areas covered by a translucent surface are considered visible.
3177 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003179
3180 /*
3181 * coveredRegion: area of a surface that is covered by all
3182 * visible regions above it (which includes the translucent areas).
3183 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003185
Jesse Halla8026d22012-09-25 13:25:04 -07003186 /*
3187 * transparentRegion: area of a surface that is hinted to be completely
3188 * transparent. This is only used to tell when the layer has no visible
3189 * non-transparent regions and can be removed from the layer list. It
3190 * does not affect the visibleRegion of this layer or any layers
3191 * beneath it. The hint may not be correct if apps don't respect the
3192 * SurfaceView restrictions (which, sadly, some don't).
3193 */
3194 Region transparentRegion;
3195
Mathias Agopianab028732010-03-16 16:41:46 -07003196
3197 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003198 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003199 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003200 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003203 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003204 if (!visibleRegion.isEmpty()) {
3205 // Remove the transparent area from the visible region
3206 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003207 if (tr.preserveRects()) {
3208 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003209 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003210 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003211 // transformation too complex, can't do the
3212 // transparent region optimization.
3213 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003214 }
Mathias Agopianab028732010-03-16 16:41:46 -07003215 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216
Mathias Agopianab028732010-03-16 16:41:46 -07003217 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003219 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003220 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003221 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003222 // the opaque region is the layer's footprint
3223 opaqueRegion = visibleRegion;
3224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 }
3226 }
3227
Robert Carre5f4f692018-01-12 13:12:28 -08003228 if (visibleRegion.isEmpty()) {
3229 layer->clearVisibilityRegions();
3230 return;
3231 }
3232
Mathias Agopianab028732010-03-16 16:41:46 -07003233 // Clip the covered region to the visible region
3234 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3235
3236 // Update aboveCoveredLayers for next (lower) layer
3237 aboveCoveredLayers.orSelf(visibleRegion);
3238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 // subtract the opaque region covered by the layers above us
3240 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241
3242 // compute this layer's dirty region
3243 if (layer->contentDirty) {
3244 // we need to invalidate the whole region
3245 dirty = visibleRegion;
3246 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003247 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 layer->contentDirty = false;
3249 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003250 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003251 * the exposed region consists of two components:
3252 * 1) what's VISIBLE now and was COVERED before
3253 * 2) what's EXPOSED now less what was EXPOSED before
3254 *
3255 * note that (1) is conservative, we start with the whole
3256 * visible region but only keep what used to be covered by
3257 * something -- which mean it may have been exposed.
3258 *
3259 * (2) handles areas that were not covered by anything but got
3260 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003261 */
Mathias Agopianab028732010-03-16 16:41:46 -07003262 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003263 const Region oldVisibleRegion = layer->visibleRegion;
3264 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003265 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3266 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268 dirty.subtractSelf(aboveOpaqueLayers);
3269
3270 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003271 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272
Mathias Agopianab028732010-03-16 16:41:46 -07003273 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003275
Jesse Halla8026d22012-09-25 13:25:04 -07003276 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 layer->setVisibleRegion(visibleRegion);
3278 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003279 layer->setVisibleNonTransparentRegion(
3280 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003281 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282
Mathias Agopian87baae12012-07-31 12:38:26 -07003283 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284}
3285
Chia-I Wuab0c3192017-08-01 11:29:00 -07003286void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003287 for (const auto& [token, displayDevice] : mDisplays) {
3288 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003289 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003290 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003291 }
3292 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003293}
3294
Dan Stoza6b9454d2014-11-07 16:00:59 -08003295bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296{
Ady Abraham09bd3922019-04-08 10:44:56 -07003297 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 ALOGV("handlePageFlip");
3299
Brian Andersond6927fb2016-07-23 23:37:30 -07003300 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301
Mathias Agopian4fec8732012-06-29 14:12:52 -07003302 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003303 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003304 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003305
3306 // Store the set of layers that need updates. This set must not change as
3307 // buffers are being latched, as this could result in a deadlock.
3308 // Example: Two producers share the same command stream and:
3309 // 1.) Layer 0 is latched
3310 // 2.) Layer 0 gets a new frame
3311 // 2.) Layer 1 gets a new frame
3312 // 3.) Layer 1 is latched.
3313 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3314 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003315 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003316 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003318 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003319 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003320 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003321 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003322 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003323 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003324 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003325 } else {
3326 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003327 }
Robert Carr2047fae2016-11-28 14:09:09 -08003328 });
3329
Lloyd Piquef2c79392018-12-20 16:23:33 -08003330 if (!mLayersWithQueuedFrames.empty()) {
3331 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3332 // writes to Layer current state. See also b/119481871
3333 Mutex::Autolock lock(mStateLock);
3334
3335 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003336 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003337 mLayersPendingRefresh.push_back(layer);
3338 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003339 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003340 if (layer->isBufferLatched()) {
3341 newDataLatched = true;
3342 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003343 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003344 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003345
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003346 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003347
3348 // If we will need to wake up at some time in the future to deal with a
3349 // queued frame that shouldn't be displayed during this vsync period, wake
3350 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003351 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003352 signalLayerUpdate();
3353 }
3354
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003355 // enter boot animation on first buffer latch
3356 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3357 ALOGI("Enter boot animation");
3358 mBootStage = BootStage::BOOTANIMATION;
3359 }
3360
Dan Stoza6b9454d2014-11-07 16:00:59 -08003361 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003362 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363}
3364
Mathias Agopianad456f92011-01-13 17:53:01 -08003365void SurfaceFlinger::invalidateHwcGeometry()
3366{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003368}
3369
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003371 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003373 // We only need to actually compose the display if:
3374 // 1) It is being handled by hardware composer, which may need this to
3375 // keep its virtual display state machine in sync, or
3376 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003377 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003378 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003379 return;
3380 }
3381
Dan Stoza9e56aa02015-11-02 13:00:03 -08003382 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 base::unique_fd readyFence;
3384 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003385
3386 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003387 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003388}
3389
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003390bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3391 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003392 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003393 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003394
Lloyd Pique32cbe282018-10-19 13:09:22 -07003395 auto display = displayDevice->getCompositionDisplay();
3396 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003397 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003398 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003399 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003400
3401 const Region bounds(displayState.bounds);
3402 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003403 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Baldev Sahu0560e0e2018-09-27 15:02:33 +05303404 const bool hasFlipClientTargetRequest = getHwComposer().hasFlipClientTargetRequest(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003405 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003406
Chia-I Wu8e50e692018-05-04 10:12:37 -07003407 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003408
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003409 renderengine::DisplaySettings clientCompositionDisplay;
3410 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3411 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003412 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003413
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 if (hasClientComposition) {
3415 ALOGV("hasClientComposition");
3416
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003417 if (displayDevice->isPrimary() && supportProtectedContent) {
3418 bool needsProtected = false;
3419 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3420 // If the layer is a protected layer, mark protected context is needed.
3421 if (layer->isProtected()) {
3422 needsProtected = true;
3423 break;
3424 }
3425 }
Peiyong Lin52010312019-05-02 14:22:16 -07003426 if (needsProtected != renderEngine.isProtected()) {
3427 renderEngine.useProtectedContext(needsProtected);
3428 }
3429 if (needsProtected != display->getRenderSurface()->isProtected() &&
3430 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003431 display->getRenderSurface()->setProtected(needsProtected);
3432 }
3433 }
3434
Alec Mouri6338c9d2019-02-07 16:57:51 -08003435 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003436
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003437 if (buf == nullptr) {
3438 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3439 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003440 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003441 return false;
3442 }
3443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003444 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3445 clientCompositionDisplay.clip = displayState.scissor;
3446 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003447 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003448 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003449
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003450 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003451 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003452 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003453 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003454 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003455 clientCompositionDisplay.outputDataspace = outputDataspace;
3456 clientCompositionDisplay.maxLuminance =
3457 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003458
Lloyd Pique441d5042018-10-18 16:49:51 -07003459 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003460 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003461 getHwComposer()
3462 .hasDisplayCapability(displayId,
3463 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003464
Peiyong Lind3788632018-09-18 16:01:31 -07003465 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003466 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3467 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003468 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003469 }
Baldev Sahu0560e0e2018-09-27 15:02:33 +05303470 } else if (hasFlipClientTargetRequest) {
3471 buf = display->getRenderSurface()->dequeueBuffer(&fd);
3472
3473 if (buf == nullptr) {
3474 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3475 "client composition for this frame",
3476 displayDevice->getDisplayName().c_str());
3477 return false;
3478 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003479 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003480
Mathias Agopian85d751c2012-08-29 16:59:24 -07003481 /*
3482 * and then, render the layers targeted at the framebuffer
3483 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003484
Dan Stoza9e56aa02015-11-02 13:00:03 -08003485 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003486 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003487 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003488 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003489 const Region viewportRegion(displayState.viewport);
3490 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003491 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003492 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003493 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003494 switch (layer->getCompositionType(displayDevice)) {
3495 case Hwc2::IComposerClient::Composition::CURSOR:
3496 case Hwc2::IComposerClient::Composition::DEVICE:
3497 case Hwc2::IComposerClient::Composition::SIDEBAND:
3498 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003499 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003500 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003501 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003502 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003503 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003504 // never clear the very first layer since we're
3505 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003506 renderengine::LayerSettings layerSettings;
3507 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003508 bool prepared =
3509 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3510 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003511
3512 if (prepared) {
3513 layerSettings.source.buffer.buffer = nullptr;
3514 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3515 layerSettings.alpha = half(0.0);
3516 layerSettings.disableBlending = true;
3517 clientCompositionLayers.push_back(layerSettings);
3518 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003519 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003520 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003521 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003522 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003523 renderengine::LayerSettings layerSettings;
3524 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003525 layer->prepareClientLayer(renderArea, clip, clearRegion,
3526 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003527 if (prepared) {
3528 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003529 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003530 break;
3531 }
3532 default:
3533 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003534 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003535 } else {
3536 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003537 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003538 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003539 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003540
Alec Mouri820c7402019-01-23 13:02:39 -08003541 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003542 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003543 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003544
3545 // We boost GPU frequency here because there will be color spaces conversion
3546 // and it's expensive. We boost the GPU frequency so that GPU composition can
3547 // finish in time. We must reset GPU frequency afterwards, because high frequency
3548 // consumes extra battery.
3549 const bool expensiveRenderingExpected =
3550 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3551 if (expensiveRenderingExpected && displayId) {
3552 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3553 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003554 if (!debugRegion.isEmpty()) {
3555 Region::const_iterator it = debugRegion.begin();
3556 Region::const_iterator end = debugRegion.end();
3557 while (it != end) {
3558 const Rect& rect = *it++;
3559 renderengine::LayerSettings layerSettings;
3560 layerSettings.source.buffer.buffer = nullptr;
3561 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3562 layerSettings.geometry.boundaries = rect.toFloatRect();
3563 layerSettings.alpha = half(1.0);
3564 clientCompositionLayers.push_back(layerSettings);
3565 }
3566 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003567 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003568 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3569 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003570 } else if (displayId) {
3571 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003572 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003573 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574}
3575
Chia-I Wu28e3a252018-09-07 12:05:02 -07003576void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003577 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003578 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003579}
3580
Robert Carrc0df3122019-04-11 13:18:21 -07003581status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3582 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3583 const sp<IBinder>& parentHandle,
3584 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003585 // add this layer to the current state list
3586 {
3587 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003588 sp<Layer> parent;
3589 if (parentHandle != nullptr) {
3590 parent = fromHandle(parentHandle);
3591 if (parent == nullptr) {
3592 return NAME_NOT_FOUND;
3593 }
3594 } else {
3595 parent = parentLayer;
3596 }
3597
Robert Carr1f0a16a2016-10-24 16:27:39 -07003598 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003599 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3600 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003601 return NO_MEMORY;
3602 }
Robert Carrc0df3122019-04-11 13:18:21 -07003603
3604 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3605
Robert Carrb89ea9d2018-12-10 13:01:14 -08003606 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003607 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003608 } else if (parent == nullptr) {
3609 lbc->onRemovedFromCurrentState();
3610 } else if (parent->isRemovedFromCurrentState()) {
3611 parent->addChild(lbc);
3612 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003613 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003614 parent->addChild(lbc);
3615 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003616
Yiwei Zhang243b3782018-05-15 17:40:04 -07003617 if (gbc != nullptr) {
3618 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3619 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3620 mMaxGraphicBufferProducerListSize,
3621 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3622 mGraphicBufferProducerList.size(),
3623 mMaxGraphicBufferProducerListSize, mNumLayers);
3624 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003625 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003626 }
3627
Mathias Agopian96f08192010-06-02 23:28:45 -07003628 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003629 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003630
Dan Stoza7d89d062015-04-30 13:29:25 -07003631 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003632}
3633
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003634uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003635 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003636}
3637
Mathias Agopian3f844832013-08-07 21:24:32 -07003638uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003639 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003640}
3641
Mathias Agopian3f844832013-08-07 21:24:32 -07003642uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003643 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003644}
3645
3646uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003647 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003648 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003649 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003650 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003651 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003652 }
3653 return old;
3654}
3655
Marissa Wall713b63f2018-10-17 15:42:43 -07003656bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003657 // to prevent onHandleDestroyed from being called while the lock is held,
3658 // we must keep a copy of the transactions (specifically the composer
3659 // states) around outside the scope of the lock
3660 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003661 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003662 {
3663 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003664
Valerie Haufce31b82019-04-30 16:41:14 -07003665 auto it = mTransactionQueues.begin();
3666 while (it != mTransactionQueues.end()) {
3667 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003668
Valerie Haufce31b82019-04-30 16:41:14 -07003669 while (!transactionQueue.empty()) {
3670 const auto& transaction = transactionQueue.front();
3671 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3672 transaction.states)) {
3673 setTransactionFlags(eTransactionFlushNeeded);
3674 break;
3675 }
3676 transactions.push_back(transaction);
3677 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3678 mPendingInputWindowCommands, transaction.desiredPresentTime,
3679 transaction.buffer, transaction.callback,
3680 transaction.postTime, transaction.privileged,
3681 /*isMainThread*/ true);
3682 transactionQueue.pop();
3683 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003684 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003685
Valerie Haufce31b82019-04-30 16:41:14 -07003686 if (transactionQueue.empty()) {
3687 it = mTransactionQueues.erase(it);
3688 mTransactionCV.broadcast();
3689 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003690 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003691 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003692 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003693 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003694 return flushedATransaction;
3695}
3696
3697bool SurfaceFlinger::transactionFlushNeeded() {
3698 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003699}
3700
chaviwca27f252018-02-06 16:46:39 -08003701bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3702 for (const ComposerState& state : states) {
3703 // Here we need to check that the interface we're given is indeed
3704 // one of our own. A malicious client could give us a nullptr
3705 // IInterface, or one of its own or even one of our own but a
3706 // different type. All these situations would cause us to crash.
3707 if (state.client == nullptr) {
3708 return true;
3709 }
3710
3711 sp<IBinder> binder = IInterface::asBinder(state.client);
3712 if (binder == nullptr) {
3713 return true;
3714 }
3715
3716 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3717 return true;
3718 }
3719 }
3720 return false;
3721}
3722
Marissa Wall17b4e452018-12-26 16:32:34 -08003723bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3724 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003725 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003726 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3727 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3728 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3729 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3730 return false;
3731 }
3732
Marissa Wall713b63f2018-10-17 15:42:43 -07003733 for (const ComposerState& state : states) {
3734 const layer_state_t& s = state.state;
3735 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3736 continue;
3737 }
3738 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003739 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003740 }
3741 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003742 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003743}
3744
3745void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3746 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003747 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003748 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003749 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003750 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003751 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003752 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003753
Valerie Haubc6ddb12019-03-08 11:10:15 -08003754 const int64_t postTime = systemTime();
3755
Robert Carr14167e02019-02-13 13:50:55 -08003756 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3757
Mathias Agopian698c0872011-06-28 19:09:31 -07003758 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003759
chaviwca27f252018-02-06 16:46:39 -08003760 if (containsAnyInvalidClientState(states)) {
3761 return;
3762 }
3763
Marissa Wall713b63f2018-10-17 15:42:43 -07003764 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003765 auto itr = mTransactionQueues.find(applyToken);
3766 // if this is an animation frame, wait until prior animation frame has
3767 // been applied by SF
3768 if (flags & eAnimation) {
3769 while (itr != mTransactionQueues.end()) {
3770 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3771 if (CC_UNLIKELY(err != NO_ERROR)) {
3772 ALOGW_IF(err == TIMED_OUT,
3773 "setTransactionState timed out "
3774 "waiting for animation frame to apply");
3775 break;
3776 }
3777 itr = mTransactionQueues.find(applyToken);
3778 }
3779 }
3780 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003781 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003782 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003783 uncacheBuffer, listenerCallbacks, postTime,
3784 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003785 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003786 return;
3787 }
3788
Valerie Haubc6ddb12019-03-08 11:10:15 -08003789 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003790 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003791}
3792
3793void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003794 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003795 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003796 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003797 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003798 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003799 const int64_t postTime, bool privileged,
3800 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003801 uint32_t transactionFlags = 0;
3802
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003803 if (flags & eAnimation) {
3804 // For window updates that are part of an animation we must wait for
3805 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003806 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003807 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003808 if (CC_UNLIKELY(err != NO_ERROR)) {
3809 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003810 // caller after a few seconds.
3811 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3812 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003813 mAnimTransactionPending = false;
3814 break;
3815 }
3816 }
3817 }
3818
chaviwca27f252018-02-06 16:46:39 -08003819 for (const DisplayState& display : displays) {
3820 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003821 }
3822
Marissa Walld600d572019-03-26 15:38:50 -07003823 // In case the client has sent a Transaction that should receive callbacks but without any
3824 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3825 // to the callback thread so it can send an empty callback
3826 if (!listenerCallbacks.empty()) {
3827 mTransactionCompletedThread.run();
3828 }
3829 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3830 mTransactionCompletedThread.addCallback(listener, callbackIds);
3831 }
3832
Marissa Walle2ffb422018-10-12 11:33:52 -07003833 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003834 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003835 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3836 postTime, privileged);
3837 }
3838
Marissa Walle2ffb422018-10-12 11:33:52 -07003839 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003840 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003841 mTransactionCompletedThread.sendCallbacks();
3842 }
3843 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003844
chaviw273171b2018-12-26 11:46:30 -08003845 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3846
Marissa Wall947d34e2019-03-29 14:03:53 -07003847 if (uncacheBuffer.isValid()) {
3848 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003849 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003850 }
3851
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003852 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3853 // anyway. This can be used as a flush mechanism for previous async transactions.
3854 // Empty animation transaction can be used to simulate back-pressure, so also force a
3855 // transaction for empty animation transactions.
3856 if (transactionFlags == 0 &&
3857 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003858 transactionFlags = eTransactionNeeded;
3859 }
3860
Marissa Wall06255332019-03-27 13:48:27 -07003861 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3862 // so we don't have to wake up again next frame to preform an uneeded traversal.
3863 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3864 transactionFlags = transactionFlags & (~eTraversalNeeded);
3865 mTraversalNeededMainThread = true;
3866 }
3867
Mathias Agopian386aa982011-11-07 21:58:03 -08003868 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003869 if (mInterceptor->isEnabled()) {
3870 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003871 }
Irvel468051e2016-06-13 16:44:44 -07003872
Mathias Agopian386aa982011-11-07 21:58:03 -08003873 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003874 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3875 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003876 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003877
3878 // if this is a synchronous transaction, wait for it to take effect
3879 // before returning.
3880 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003881 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003882 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003883 if (flags & eAnimation) {
3884 mAnimTransactionPending = true;
3885 }
chaviw4fe36852019-04-15 16:25:49 -07003886 if (mPendingInputWindowCommands.syncInputWindows) {
3887 mPendingSyncInputWindows = true;
3888 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003889
3890 // applyTransactionState can be called by either the main SF thread or by
3891 // another process through setTransactionState. While a given process may wish
3892 // to wait on synchronous transactions, the main SF thread should never
3893 // be blocked. Therefore, we only wait if isMainThread is false.
3894 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003895 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3896 if (CC_UNLIKELY(err != NO_ERROR)) {
3897 // just in case something goes wrong in SF, return to the
3898 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003899 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3900 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003901 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003902 break;
3903 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003904 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003905 }
3906}
3907
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003908uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3909 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3910 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003911
Mathias Agopiane57f2922012-08-09 16:29:12 -07003912 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003913 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3914
3915 const uint32_t what = s.what;
3916 if (what & DisplayState::eSurfaceChanged) {
3917 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3918 state.surface = s.surface;
3919 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003920 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003921 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003922 if (what & DisplayState::eLayerStackChanged) {
3923 if (state.layerStack != s.layerStack) {
3924 state.layerStack = s.layerStack;
3925 flags |= eDisplayTransactionNeeded;
3926 }
3927 }
3928 if (what & DisplayState::eDisplayProjectionChanged) {
3929 if (state.orientation != s.orientation) {
3930 state.orientation = s.orientation;
3931 flags |= eDisplayTransactionNeeded;
3932 }
3933 if (state.frame != s.frame) {
3934 state.frame = s.frame;
3935 flags |= eDisplayTransactionNeeded;
3936 }
3937 if (state.viewport != s.viewport) {
3938 state.viewport = s.viewport;
3939 flags |= eDisplayTransactionNeeded;
3940 }
3941 }
3942 if (what & DisplayState::eDisplaySizeChanged) {
3943 if (state.width != s.width) {
3944 state.width = s.width;
3945 flags |= eDisplayTransactionNeeded;
3946 }
3947 if (state.height != s.height) {
3948 state.height = s.height;
3949 flags |= eDisplayTransactionNeeded;
3950 }
3951 }
3952
Mathias Agopiane57f2922012-08-09 16:29:12 -07003953 return flags;
3954}
3955
Robert Carr14167e02019-02-13 13:50:55 -08003956bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003957 IPCThreadState* ipc = IPCThreadState::self();
3958 const int pid = ipc->getCallingPid();
3959 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003960 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003961 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003962 return false;
3963 }
3964 return true;
3965}
3966
Marissa Wall3dad52d2019-03-22 14:03:19 -07003967uint32_t SurfaceFlinger::setClientStateLocked(
3968 const ComposerState& composerState, int64_t desiredPresentTime,
3969 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3970 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003971 const layer_state_t& s = composerState.state;
3972 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3973
Mathias Agopian13127d82013-03-05 17:47:11 -08003974 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003975 if (layer == nullptr) {
3976 return 0;
3977 }
3978
chaviw8b3871a2017-11-01 17:41:01 -07003979 uint32_t flags = 0;
3980
Garfield Tan8a3083e2018-12-03 13:21:07 -08003981 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003982 bool geometryAppliesWithResize =
3983 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003984
3985 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3986 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003987 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003988 layer->pushPendingState();
3989 }
3990
chaviw8b3871a2017-11-01 17:41:01 -07003991 if (what & layer_state_t::ePositionChanged) {
3992 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3993 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003994 }
chaviw8b3871a2017-11-01 17:41:01 -07003995 }
3996 if (what & layer_state_t::eLayerChanged) {
3997 // NOTE: index needs to be calculated before we update the state
3998 const auto& p = layer->getParent();
3999 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004000 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004001 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004002 mCurrentState.layersSortedByZ.removeAt(idx);
4003 mCurrentState.layersSortedByZ.add(layer);
4004 // we need traversal (state changed)
4005 // AND transaction (list changed)
4006 flags |= eTransactionNeeded|eTraversalNeeded;
4007 }
chaviw8b3871a2017-11-01 17:41:01 -07004008 } else {
4009 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004010 flags |= eTransactionNeeded|eTraversalNeeded;
4011 }
4012 }
chaviw8b3871a2017-11-01 17:41:01 -07004013 }
4014 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004015 // NOTE: index needs to be calculated before we update the state
4016 const auto& p = layer->getParent();
4017 if (p == nullptr) {
4018 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4019 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4020 mCurrentState.layersSortedByZ.removeAt(idx);
4021 mCurrentState.layersSortedByZ.add(layer);
4022 // we need traversal (state changed)
4023 // AND transaction (list changed)
4024 flags |= eTransactionNeeded|eTraversalNeeded;
4025 }
4026 } else {
4027 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4028 flags |= eTransactionNeeded|eTraversalNeeded;
4029 }
chaviw8b3871a2017-11-01 17:41:01 -07004030 }
4031 }
4032 if (what & layer_state_t::eSizeChanged) {
4033 if (layer->setSize(s.w, s.h)) {
4034 flags |= eTraversalNeeded;
4035 }
4036 }
4037 if (what & layer_state_t::eAlphaChanged) {
4038 if (layer->setAlpha(s.alpha))
4039 flags |= eTraversalNeeded;
4040 }
4041 if (what & layer_state_t::eColorChanged) {
4042 if (layer->setColor(s.color))
4043 flags |= eTraversalNeeded;
4044 }
Peiyong Lind3788632018-09-18 16:01:31 -07004045 if (what & layer_state_t::eColorTransformChanged) {
4046 if (layer->setColorTransform(s.colorTransform)) {
4047 flags |= eTraversalNeeded;
4048 }
4049 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004050 if (what & layer_state_t::eBackgroundColorChanged) {
4051 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4052 flags |= eTraversalNeeded;
4053 }
4054 }
chaviw8b3871a2017-11-01 17:41:01 -07004055 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004056 // TODO: b/109894387
4057 //
4058 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4059 // rotation. To see the problem observe that if we have a square parent, and a child
4060 // of the same size, then we rotate the child 45 degrees around it's center, the child
4061 // must now be cropped to a non rectangular 8 sided region.
4062 //
4063 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4064 // private API, and the WindowManager only uses rotation in one case, which is on a top
4065 // level layer in which cropping is not an issue.
4066 //
4067 // However given that abuse of rotation matrices could lead to surfaces extending outside
4068 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4069 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4070 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004071 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004072 flags |= eTraversalNeeded;
4073 }
4074 if (what & layer_state_t::eTransparentRegionChanged) {
4075 if (layer->setTransparentRegionHint(s.transparentRegion))
4076 flags |= eTraversalNeeded;
4077 }
4078 if (what & layer_state_t::eFlagsChanged) {
4079 if (layer->setFlags(s.flags, s.mask))
4080 flags |= eTraversalNeeded;
4081 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004082 if (what & layer_state_t::eCropChanged_legacy) {
4083 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004084 flags |= eTraversalNeeded;
4085 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004086 if (what & layer_state_t::eCornerRadiusChanged) {
4087 if (layer->setCornerRadius(s.cornerRadius))
4088 flags |= eTraversalNeeded;
4089 }
chaviw8b3871a2017-11-01 17:41:01 -07004090 if (what & layer_state_t::eLayerStackChanged) {
4091 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4092 // We only allow setting layer stacks for top level layers,
4093 // everything else inherits layer stack from its parent.
4094 if (layer->hasParent()) {
4095 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4096 layer->getName().string());
4097 } else if (idx < 0) {
4098 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4099 "that also does not appear in the top level layer list. Something"
4100 " has gone wrong.", layer->getName().string());
4101 } else if (layer->setLayerStack(s.layerStack)) {
4102 mCurrentState.layersSortedByZ.removeAt(idx);
4103 mCurrentState.layersSortedByZ.add(layer);
4104 // we need traversal (state changed)
4105 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004106 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004107 }
4108 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004109 if (what & layer_state_t::eDeferTransaction_legacy) {
4110 if (s.barrierHandle_legacy != nullptr) {
4111 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4112 } else if (s.barrierGbp_legacy != nullptr) {
4113 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004114 if (authenticateSurfaceTextureLocked(gbp)) {
4115 const auto& otherLayer =
4116 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004117 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004118 } else {
4119 ALOGE("Attempt to defer transaction to to an"
4120 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004121 }
4122 }
chaviw8b3871a2017-11-01 17:41:01 -07004123 // We don't trigger a traversal here because if no other state is
4124 // changed, we don't want this to cause any more work
4125 }
4126 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004127 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004128 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004129 if (!hadParent) {
4130 mCurrentState.layersSortedByZ.remove(layer);
4131 }
chaviw8b3871a2017-11-01 17:41:01 -07004132 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004133 }
chaviw8b3871a2017-11-01 17:41:01 -07004134 }
4135 if (what & layer_state_t::eReparentChildren) {
4136 if (layer->reparentChildren(s.reparentHandle)) {
4137 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004138 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004139 }
chaviw8b3871a2017-11-01 17:41:01 -07004140 if (what & layer_state_t::eDetachChildren) {
4141 layer->detachChildren();
4142 }
4143 if (what & layer_state_t::eOverrideScalingModeChanged) {
4144 layer->setOverrideScalingMode(s.overrideScalingMode);
4145 // We don't trigger a traversal here because if no other state is
4146 // changed, we don't want this to cause any more work
4147 }
Marissa Wall61c58622018-07-18 10:12:20 -07004148 if (what & layer_state_t::eTransformChanged) {
4149 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4150 }
4151 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4152 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4153 flags |= eTraversalNeeded;
4154 }
4155 if (what & layer_state_t::eCropChanged) {
4156 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4157 }
Marissa Wall861616d2018-10-22 12:52:23 -07004158 if (what & layer_state_t::eFrameChanged) {
4159 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4160 }
Marissa Wall61c58622018-07-18 10:12:20 -07004161 if (what & layer_state_t::eAcquireFenceChanged) {
4162 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4163 }
4164 if (what & layer_state_t::eDataspaceChanged) {
4165 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4166 }
4167 if (what & layer_state_t::eHdrMetadataChanged) {
4168 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4169 }
4170 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4171 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4172 }
4173 if (what & layer_state_t::eApiChanged) {
4174 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4175 }
4176 if (what & layer_state_t::eSidebandStreamChanged) {
4177 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4178 }
Robert Carr720e5062018-07-30 17:45:14 -07004179 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004180 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004181 layer->setInputInfo(s.inputInfo);
4182 flags |= eTraversalNeeded;
4183 } else {
4184 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4185 }
Robert Carr720e5062018-07-30 17:45:14 -07004186 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004187 if (what & layer_state_t::eMetadataChanged) {
4188 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4189 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004190 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4191 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4192 flags |= eTraversalNeeded;
4193 }
4194 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004195 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004196 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004197 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004198 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4199 }
4200 }
Marissa Wall78b72202019-03-15 14:58:34 -07004201 bool bufferChanged = what & layer_state_t::eBufferChanged;
4202 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4203 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004204 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07004205 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004206 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
4207 if (success) {
4208 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
4209 success = ClientCache::getInstance()
4210 .registerErasedRecipient(s.cachedBuffer,
4211 wp<ClientCache::ErasedRecipient>(this));
4212 if (!success) {
4213 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
4214 }
4215 }
Marissa Wall78b72202019-03-15 14:58:34 -07004216 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004217 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004218 } else if (bufferChanged) {
4219 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004220 }
Marissa Wall78b72202019-03-15 14:58:34 -07004221 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004222 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004223 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004224 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004225 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004226 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4227 // Do not put anything that updates layer state or modifies flags after
4228 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004229 return flags;
4230}
4231
chaviw273171b2018-12-26 11:46:30 -08004232uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4233 uint32_t flags = 0;
4234 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4235 flags |= eTraversalNeeded;
4236 }
4237
chaviwa911b102019-02-14 10:18:33 -08004238 if (inputWindowCommands.syncInputWindows) {
4239 flags |= eTraversalNeeded;
4240 }
4241
Vishnu Nairec0ab382019-02-13 15:32:56 -08004242 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004243 return flags;
4244}
4245
Marissa Wall2d814fb2019-04-09 18:52:57 +00004246status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4247 uint32_t h, PixelFormat format, uint32_t flags,
4248 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004249 sp<IGraphicBufferProducer>* gbp,
4250 const sp<IBinder>& parentHandle,
4251 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004252 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004253 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004254 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004255 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004256 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004257
Robert Carrc0df3122019-04-11 13:18:21 -07004258 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4259 "Expected only one of parentLayer or parentHandle to be non-null. "
4260 "Programmer error?");
4261
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004262 status_t result = NO_ERROR;
4263
4264 sp<Layer> layer;
4265
Cody Northropbc755282017-03-31 12:00:08 -06004266 String8 uniqueName = getUniqueLayerName(name);
4267
Evan Roskya1f1e152019-01-24 16:17:46 -08004268 bool primaryDisplayOnly = false;
4269
4270 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4271 // TODO b/64227542
4272 if (metadata.has(METADATA_WINDOW_TYPE)) {
4273 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4274 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004275 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004276 primaryDisplayOnly = true;
4277 }
4278 }
4279
Mathias Agopian3165cc22012-08-08 19:42:09 -07004280 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004281 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004282 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4283 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004284
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004286 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004287 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4288 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004289 break;
chaviw13fdc492017-06-27 12:40:18 -07004290 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004291 // check if buffer size is set for color layer.
4292 if (w > 0 || h > 0) {
4293 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4294 int(w), int(h));
4295 return BAD_VALUE;
4296 }
4297
Evan Roskya1f1e152019-01-24 16:17:46 -08004298 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4299 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004300 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004301 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004302 // check if buffer size is set for container layer.
4303 if (w > 0 || h > 0) {
4304 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4305 int(w), int(h));
4306 return BAD_VALUE;
4307 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004308 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4309 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004310 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004311 default:
4312 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004313 break;
4314 }
4315
Dan Stoza7d89d062015-04-30 13:29:25 -07004316 if (result != NO_ERROR) {
4317 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004318 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004319
Evan Roskya1f1e152019-01-24 16:17:46 -08004320 if (primaryDisplayOnly) {
4321 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004322 }
4323
Robert Carrb89ea9d2018-12-10 13:01:14 -08004324 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004325 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4326 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004327 if (result != NO_ERROR) {
4328 return result;
4329 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004330 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004331
4332 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004333 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004334}
4335
Cody Northropbc755282017-03-31 12:00:08 -06004336String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4337{
4338 bool matchFound = true;
4339 uint32_t dupeCounter = 0;
4340
4341 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4342 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4343
Dan Stoza436ccf32018-06-21 12:10:12 -07004344 // Grab the state lock since we're accessing mCurrentState
4345 Mutex::Autolock lock(mStateLock);
4346
Cody Northropbc755282017-03-31 12:00:08 -06004347 // Loop over layers until we're sure there is no matching name
4348 while (matchFound) {
4349 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004350 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004351 if (layer->getName() == uniqueName) {
4352 matchFound = true;
4353 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4354 }
4355 });
4356 }
4357
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004358 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4359 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004360
4361 return uniqueName;
4362}
4363
Marissa Wallfd668622018-05-10 10:21:13 -07004364status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4365 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004366 LayerMetadata metadata, PixelFormat& format,
4367 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004368 sp<IGraphicBufferProducer>* gbp,
4369 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004370 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004371 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004372 case PIXEL_FORMAT_TRANSPARENT:
4373 case PIXEL_FORMAT_TRANSLUCENT:
4374 format = PIXEL_FORMAT_RGBA_8888;
4375 break;
4376 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004377 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 break;
4379 }
4380
Evan Roskya1f1e152019-01-24 16:17:46 -08004381 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4382 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004383 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004384 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004385 *handle = layer->getHandle();
4386 *gbp = layer->getProducer();
4387 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004388 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004389
Marissa Wallfd668622018-05-10 10:21:13 -07004390 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004391 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392}
4393
Marissa Wall61c58622018-07-18 10:12:20 -07004394status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4395 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004396 LayerMetadata metadata, sp<IBinder>* handle,
4397 sp<Layer>* outLayer) {
4398 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4399 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004400 *handle = layer->getHandle();
4401 *outLayer = layer;
4402
4403 return NO_ERROR;
4404}
4405
Evan Roskya1f1e152019-01-24 16:17:46 -08004406status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4407 uint32_t h, uint32_t flags, LayerMetadata metadata,
4408 sp<IBinder>* handle, sp<Layer>* outLayer) {
4409 *outLayer = getFactory().createColorLayer(
4410 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004411 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004412 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004413}
4414
Evan Roskya1f1e152019-01-24 16:17:46 -08004415status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4416 uint32_t w, uint32_t h, uint32_t flags,
4417 LayerMetadata metadata, sp<IBinder>* handle,
4418 sp<Layer>* outLayer) {
4419 *outLayer = getFactory().createContainerLayer(
4420 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004421 *handle = (*outLayer)->getHandle();
4422 return NO_ERROR;
4423}
4424
4425
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004426void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004427 mLayersPendingRemoval.add(layer);
4428 mLayersRemoved = true;
4429 setTransactionFlags(eTransactionNeeded);
4430}
4431
Robert Carr695d5282018-12-18 15:27:58 -08004432void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004433{
Robert Carr2e102c92018-10-23 12:11:15 -07004434 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004435 // If a layer has a parent, we allow it to out-live it's handle
4436 // with the idea that the parent holds a reference and will eventually
4437 // be cleaned up. However no one cleans up the top-level so we do so
4438 // here.
4439 if (layer->getParent() == nullptr) {
4440 mCurrentState.layersSortedByZ.remove(layer);
4441 }
4442 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004443
4444 auto it = mLayersByLocalBinderToken.begin();
4445 while (it != mLayersByLocalBinderToken.end()) {
4446 if (it->second == layer) {
4447 it = mLayersByLocalBinderToken.erase(it);
4448 } else {
4449 it++;
4450 }
4451 }
4452
Robert Carr695d5282018-12-18 15:27:58 -08004453 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004454}
4455
Mathias Agopianb60314a2012-04-10 22:09:54 -07004456// ---------------------------------------------------------------------------
4457
Andy McFadden13a082e2012-08-24 10:16:42 -07004458void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004459 const auto display = getDefaultDisplayDeviceLocked();
4460 if (!display) return;
4461
4462 const sp<IBinder> token = display->getDisplayToken().promote();
4463 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004464
Jesse Hall01e29052013-02-19 16:13:35 -08004465 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004466 Vector<ComposerState> state;
4467 Vector<DisplayState> displays;
4468 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004469 d.what = DisplayState::eDisplayProjectionChanged |
4470 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004471 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004472 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004473 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004474 d.frame.makeInvalid();
4475 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004476 d.width = 0;
4477 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004478 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004479 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004480
Dominik Laskowskie9774092018-12-11 10:04:24 -08004481 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004482
Dominik Laskowski83b88212018-12-11 13:34:06 -08004483 const nsecs_t vsyncPeriod = getVsyncPeriod();
4484 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004485
Brian Andersond0010582017-03-07 13:20:31 -08004486 // Use phase of 0 since phase is not known.
4487 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004488 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004489 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004490}
4491
4492void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004493 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004494 postMessageAsync(
4495 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004496}
4497
Ady Abraham27c70212019-06-11 10:52:26 -07004498void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4499 if (mHWCVsyncState != enabled) {
4500 getHwComposer().setVsyncEnabled(displayId, enabled);
4501 mHWCVsyncState = enabled;
4502 }
4503}
4504
Dominik Laskowskie9774092018-12-11 10:04:24 -08004505void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004506 if (display->isVirtual()) {
4507 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004508 return;
4509 }
4510
Dominik Laskowski075d3172018-05-24 15:50:06 -07004511 const auto displayId = display->getId();
4512 LOG_ALWAYS_FATAL_IF(!displayId);
4513
Dominik Laskowski34157762018-10-31 13:07:19 -07004514 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004515
4516 int currentMode = display->getPowerMode();
4517 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004518 return;
4519 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004520
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004521 display->setPowerMode(mode);
4522
Lloyd Pique4dccc412018-01-22 17:21:36 -08004523 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004524 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004525 }
4526
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004527 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004528 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004529 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004530 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004531 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004532 mScheduler->onScreenAcquired(mAppConnectionHandle);
4533 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004534 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004536 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004537 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004538 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004539
4540 struct sched_param param = {0};
4541 param.sched_priority = 1;
4542 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4543 ALOGW("Couldn't set SCHED_FIFO on display on");
4544 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004545 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004546 // Turn off the display
4547 struct sched_param param = {0};
4548 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4549 ALOGW("Couldn't set SCHED_OTHER on display off");
4550 }
4551
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004552 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004553 mScheduler->disableHardwareVsync(true);
4554 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004555 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004556
Ady Abraham27c70212019-06-11 10:52:26 -07004557 // Make sure HWVsync is disabled before turning off the display
4558 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4559
Dominik Laskowski075d3172018-05-24 15:50:06 -07004560 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004561 mVisibleRegionsDirty = true;
4562 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004563 } else if (mode == HWC_POWER_MODE_DOZE ||
4564 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004565 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004566 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004567 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004568 mScheduler->onScreenAcquired(mAppConnectionHandle);
4569 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004570 }
4571 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4572 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004573 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004574 mScheduler->disableHardwareVsync(true);
4575 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004576 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004577 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004578 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004579 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004580 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004581 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004582
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004583 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004584 mTimeStats->setPowerMode(mode);
Steven Thomase9eb1832019-08-28 16:08:35 -07004585 mRefreshRateStats->setPowerMode(mode);
Ady Abraham24363172019-07-12 12:37:57 -07004586 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004587 }
4588
Dominik Laskowski34157762018-10-31 13:07:19 -07004589 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004590}
4591
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004592void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004593 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004594 const auto display = getDisplayDevice(displayToken);
4595 if (!display) {
4596 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4597 displayToken.get());
4598 } else if (display->isVirtual()) {
4599 ALOGW("Attempt to set power mode %d for virtual display", mode);
4600 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004601 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004602 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004603 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004604}
4605
4606// ---------------------------------------------------------------------------
4607
Dominik Laskowskic2867142019-01-21 11:33:38 -08004608status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4609 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004611
Mathias Agopianbd115332013-04-18 16:41:04 -07004612 IPCThreadState* ipc = IPCThreadState::self();
4613 const int pid = ipc->getCallingPid();
4614 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004615
Mathias Agopianbd115332013-04-18 16:41:04 -07004616 if ((uid != AID_SHELL) &&
4617 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4619 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004620 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004621 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004622 // (this would indicate SF is stuck, but we want to be able to
4623 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004624 status_t err = mStateLock.timedLock(s2ns(1));
4625 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004626 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004627 StringAppendF(&result,
4628 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4629 "(no locks held)\n",
4630 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004631 }
4632
Dominik Laskowskic2867142019-01-21 11:33:38 -08004633 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004634
Dominik Laskowskic2867142019-01-21 11:33:38 -08004635 static const std::unordered_map<std::string, Dumper> dumpers = {
4636 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4637 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4638 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004639 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004640 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004641 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004642 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4643 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004644 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4645 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4646 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4647 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4648 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4649 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004650 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004651 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4652 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004653
Dominik Laskowskic2867142019-01-21 11:33:38 -08004654 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004655
Dominik Laskowskic2867142019-01-21 11:33:38 -08004656 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4657 (it->second)(args, asProto, result);
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004658 } else if (!asProto) {
4659 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004660 }
4661
Mathias Agopian9795c422009-08-26 16:36:26 -07004662 if (locked) {
4663 mStateLock.unlock();
4664 }
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004665
4666 LayersProto layersProto = dumpProtoFromMainThread();
4667 if (asProto) {
4668 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4669 } else {
4670 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4671 result.append(LayerProtoParser::layerTreeToString(layerTree));
4672 result.append("\n");
4673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004674 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004676 return NO_ERROR;
4677}
4678
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004679status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4680 if (asProto && mTracing.isEnabled()) {
4681 mTracing.writeToFileAsync();
4682 }
4683
4684 return doDump(fd, DumpArgs(), asProto);
4685}
4686
Dominik Laskowskic2867142019-01-21 11:33:38 -08004687void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688 mCurrentState.traverseInZOrder(
4689 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004690}
4691
Dominik Laskowskic2867142019-01-21 11:33:38 -08004692void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004693 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004694
Dominik Laskowskic2867142019-01-21 11:33:38 -08004695 if (args.size() > 1) {
4696 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004697 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004698 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004699 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004700 }
Robert Carr2047fae2016-11-28 14:09:09 -08004701 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004702 } else {
4703 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004704 }
4705}
4706
Dominik Laskowskic2867142019-01-21 11:33:38 -08004707void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004708 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004709 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004710 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004711 }
Robert Carr2047fae2016-11-28 14:09:09 -08004712 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004713
Svetoslavd85084b2014-03-20 10:28:31 -07004714 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004715}
4716
Dominik Laskowskic2867142019-01-21 11:33:38 -08004717void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4718 mTimeStats->parseArgs(asProto, args, result);
4719}
4720
Jamie Gennis6547ff42013-07-16 20:12:42 -07004721// This should only be called from the main thread. Otherwise it would need
4722// the lock and should use mCurrentState rather than mDrawingState.
4723void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004724 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004725 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004726 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004727
4728 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4729}
4730
Yiwei Zhang5434a782018-12-05 18:06:32 -08004731void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004732 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004733
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004734 if (isLayerTripleBufferingDisabled())
4735 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004736
Yiwei Zhang5434a782018-12-05 18:06:32 -08004737 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4738 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4739 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4740 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4741 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4742 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004743 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004744}
4745
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004746void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004747 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004748 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004749 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004750 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004751
Ady Abraham97d04232019-03-05 19:48:12 -08004752 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004753 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4754 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004755 StringAppendF(&result, "Allowed Display Configs: ");
4756 for (int32_t configId : mAllowedDisplayConfigs) {
Steven Thomase9eb1832019-08-28 16:08:35 -07004757 StringAppendF(&result, "%" PRIu32 " Hz, ",
4758 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004759 }
4760 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4761 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004762 mScheduler->dump(mAppConnectionHandle, result);
Steven Thomase9eb1832019-08-28 16:08:35 -07004763 StringAppendF(&result, "+ Refresh rate switching: %s\n",
4764 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004765}
4766
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4768 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004769 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4770 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004771 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004772 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004774 }
David Sodman4a36e932017-11-07 14:29:47 -08004775 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004776 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004777 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4779 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004780}
4781
Dan Stozae77c7662016-05-13 11:37:28 -07004782void SurfaceFlinger::recordBufferingStats(const char* layerName,
4783 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004784 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4785 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004786 for (const auto& segment : history) {
4787 if (!segment.usedThirdBuffer) {
4788 stats.twoBufferTime += segment.totalTime;
4789 }
4790 if (segment.occupancyAverage < 1.0f) {
4791 stats.doubleBufferedTime += segment.totalTime;
4792 } else if (segment.occupancyAverage < 2.0f) {
4793 stats.tripleBufferedTime += segment.totalTime;
4794 }
4795 ++stats.numSegments;
4796 stats.totalTime += segment.totalTime;
4797 }
4798}
4799
Yiwei Zhang5434a782018-12-05 18:06:32 -08004800void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4801 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004802
4803 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4804 const size_t count = currentLayers.size();
4805 for (size_t i=0 ; i<count ; i++) {
4806 currentLayers[i]->dumpFrameEvents(result);
4807 }
4808}
4809
Yiwei Zhang5434a782018-12-05 18:06:32 -08004810void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004811 result.append("Buffering stats:\n");
4812 result.append(" [Layer name] <Active time> <Two buffer> "
4813 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004814 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004815 typedef std::tuple<std::string, float, float, float> BufferTuple;
4816 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004817 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004818 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004819 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004820 if (stats.numSegments == 0) {
4821 continue;
4822 }
4823 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4824 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4825 stats.totalTime;
4826 float doubleBufferRatio = static_cast<float>(
4827 stats.doubleBufferedTime) / stats.totalTime;
4828 float tripleBufferRatio = static_cast<float>(
4829 stats.tripleBufferedTime) / stats.totalTime;
4830 sorted.insert({activeTime, {name, twoBufferRatio,
4831 doubleBufferRatio, tripleBufferRatio}});
4832 }
4833 for (const auto& sortedPair : sorted) {
4834 float activeTime = sortedPair.first;
4835 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4837 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004838 }
4839 result.append("\n");
4840}
4841
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004843 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004844 const auto displayId = display->getId();
4845 if (!displayId) {
4846 continue;
4847 }
4848 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004849 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004850 continue;
4851 }
4852
Yiwei Zhang5434a782018-12-05 18:06:32 -08004853 StringAppendF(&result,
4854 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4855 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004856 uint8_t port;
4857 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004858 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004859 result.append("no identification data\n");
4860 continue;
4861 }
4862
4863 if (!isEdid(data)) {
4864 result.append("unknown identification data: ");
4865 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004866 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004867 }
4868 result.append("\n");
4869 continue;
4870 }
4871
4872 const auto edid = parseEdid(data);
4873 if (!edid) {
4874 result.append("invalid EDID: ");
4875 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004877 }
4878 result.append("\n");
4879 continue;
4880 }
4881
Yiwei Zhang5434a782018-12-05 18:06:32 -08004882 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004883 result.append(edid->displayName.data(), edid->displayName.length());
4884 result.append("\"\n");
4885 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004886}
4887
Yiwei Zhang5434a782018-12-05 18:06:32 -08004888void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004889 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004890 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4891 StringAppendF(&result, "DisplayColorSetting: %s\n",
4892 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004893
4894 // TODO: print out if wide-color mode is active or not
4895
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004896 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004897 const auto displayId = display->getId();
4898 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004899 continue;
4900 }
4901
Yiwei Zhang5434a782018-12-05 18:06:32 -08004902 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004903 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004904 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004905 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004906 }
4907
Lloyd Pique32cbe282018-10-19 13:09:22 -07004908 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 StringAppendF(&result, " Current color mode: %s (%d)\n",
4910 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004911 }
4912 result.append("\n");
4913}
4914
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004915LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004916 LayersProto layersProto;
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004917 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004918 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004919 layer->writeToProtoDrawingState(layerProto, traceFlags);
4920 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004921 });
4922
4923 return layersProto;
4924}
4925
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004926LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4927 LayersProto layersProto;
4928 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4929 return layersProto;
4930}
4931
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004932LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4933 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004934 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004935
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004936 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004937 resolution->set_w(displayDevice->getWidth());
4938 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004939
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004940 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004941 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004942
Lloyd Pique32cbe282018-10-19 13:09:22 -07004943 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4944 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4945 layersProto.set_global_transform(displayState.orientation);
4946
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004947 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004948 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004949 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004950 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004951 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004952 layer->writeToProtoCompositionState(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004953 }
4954 });
4955
4956 return layersProto;
4957}
4958
Dominik Laskowskic2867142019-01-21 11:33:38 -08004959void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4960 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004961 Colorizer colorizer(colorize);
4962
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004963 // figure out if we're stuck somewhere
4964 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004965 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004966 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4967
4968 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004969 * Dump library configuration.
4970 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004971
4972 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004973 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004974 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004975 appendSfConfigString(result);
4976 appendUiConfigString(result);
4977 appendGuiConfigString(result);
4978 result.append("\n");
4979
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004980 result.append("\nDisplay identification data:\n");
4981 dumpDisplayIdentificationData(result);
4982
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004983 result.append("\nWide-Color information:\n");
4984 dumpWideColorInfo(result);
4985
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004986 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004987 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004988 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004989 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004990 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004991
Andy McFadden41d67d72014-04-25 16:58:34 -07004992 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004993 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004994 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004995 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004996 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004997
Dan Stozab90cf072015-03-05 11:05:59 -08004998 dumpStaticScreenStats(result);
4999 result.append("\n");
5000
Alec Mouri40189b02019-03-05 15:07:54 -08005001 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5002 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5003 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005004
Dan Stozae77c7662016-05-13 11:37:28 -07005005 dumpBufferingStats(result);
5006
Andy McFadden4803b742012-09-24 19:07:20 -07005007 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005008 * Dump the visible layer list
5009 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005010 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005011 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
5012 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
5013 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005014 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005015
Chia-I Wu2f884132018-09-13 15:17:58 -07005016 {
Lloyd Pique207def92019-02-28 16:09:52 -08005017 StringAppendF(&result, "Composition layers\n");
5018 mDrawingState.traverseInZOrder([&](Layer* layer) {
5019 auto compositionLayer = layer->getCompositionLayer();
5020 if (compositionLayer) compositionLayer->dump(result);
5021 });
5022 }
5023
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005024 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005025 * Dump Display state
5026 */
5027
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005028 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005029 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005030 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005031 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005032 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005033 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005034 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005035
5036 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005037 * Dump SurfaceFlinger global state
5038 */
5039
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005040 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005041 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005042 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005043
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005044 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005045
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005046 DebugEGLImageTracker::getInstance()->dump(result);
5047
Dominik Laskowski075d3172018-05-24 15:50:06 -07005048 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005049 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5050 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005051 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5052 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005053 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005054 StringAppendF(&result,
5055 " transaction-flags : %08x\n"
5056 " gpu_to_cpu_unsupported : %d\n",
5057 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005058
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005059 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005060 displayId && getHwComposer().isConnected(*displayId)) {
5061 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005062 StringAppendF(&result,
5063 " refresh-rate : %f fps\n"
5064 " x-dpi : %f\n"
5065 " y-dpi : %f\n",
5066 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5067 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005068 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005069
Yiwei Zhang5434a782018-12-05 18:06:32 -08005070 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005071
Dan Stozae22aec72016-08-01 13:20:59 -07005072 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005073 * Tracing state
5074 */
5075 mTracing.dump(result);
5076 result.append("\n");
5077
5078 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005079 * HWC layer minidump
5080 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005081 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005082 const auto displayId = display->getId();
5083 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005084 continue;
5085 }
5086
Yiwei Zhang5434a782018-12-05 18:06:32 -08005087 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005088 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005089 const sp<DisplayDevice> displayDevice = display;
5090 mCurrentState.traverseInZOrder(
5091 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005092 result.append("\n");
5093 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005094
5095 /*
5096 * Dump HWComposer state
5097 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005098 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005099 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005100 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005101 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005102 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005103 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005104
5105 /*
5106 * Dump gralloc state
5107 */
5108 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5109 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005110
5111 /*
5112 * Dump VrFlinger state if in use.
5113 */
5114 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5115 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005116 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005117 result.append("\n");
5118 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005119
5120 /**
5121 * Scheduler dump state.
5122 */
Ana Krulecc2870422019-01-29 19:00:58 -08005123 result.append("\nScheduler state:\n");
5124 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005125 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Steven Thomase9eb1832019-08-28 16:08:35 -07005126 result.append(mRefreshRateStats->doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005127
5128 result.append(mTimeStats->miniDump());
5129 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005130}
5131
Dominik Laskowski075d3172018-05-24 15:50:06 -07005132const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005133 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005134 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005135 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005136 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005137 }
5138 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005139
Dominik Laskowski34157762018-10-31 13:07:19 -07005140 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005141 static const Vector<sp<Layer>> empty;
5142 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005143}
5144
Chia-I Wu28f320b2018-05-03 11:02:56 -07005145void SurfaceFlinger::updateColorMatrixLocked() {
5146 mat4 colorMatrix;
5147 if (mGlobalSaturationFactor != 1.0f) {
5148 // Rec.709 luma coefficients
5149 float3 luminance{0.213f, 0.715f, 0.072f};
5150 luminance *= 1.0f - mGlobalSaturationFactor;
5151 mat4 saturationMatrix = mat4(
5152 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5153 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5154 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5155 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5156 );
5157 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5158 } else {
5159 colorMatrix = mClientColorMatrix * mDaltonizer();
5160 }
5161
5162 if (mCurrentState.colorMatrix != colorMatrix) {
5163 mCurrentState.colorMatrix = colorMatrix;
5164 mCurrentState.colorMatrixChanged = true;
5165 setTransactionFlags(eTransactionNeeded);
5166 }
5167}
5168
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005169status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005170#pragma clang diagnostic push
5171#pragma clang diagnostic error "-Wswitch-enum"
5172 switch (static_cast<ISurfaceComposerTag>(code)) {
5173 // These methods should at minimum make sure that the client requested
5174 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005175 case BOOT_FINISHED:
5176 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005177 case CREATE_DISPLAY:
5178 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005179 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005180 case GET_ANIMATION_FRAME_STATS:
5181 case GET_HDR_CAPABILITIES:
5182 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005183 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005184 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005185 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005186 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005187 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005188 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005189 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005190 case GET_DISPLAYED_CONTENT_SAMPLE:
5191 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005192 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5193 IPCThreadState* ipc = IPCThreadState::self();
5194 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5195 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005196 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005197 }
Robert Carr1db73f62016-12-21 12:58:51 -08005198 return OK;
5199 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005200 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005201 IPCThreadState* ipc = IPCThreadState::self();
5202 const int pid = ipc->getCallingPid();
5203 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005204 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5205 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005206 return PERMISSION_DENIED;
5207 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005208 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005209 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005210 // Used by apps to hook Choreographer to SurfaceFlinger.
5211 case CREATE_DISPLAY_EVENT_CONNECTION:
5212 // The following calls are currently used by clients that do not
5213 // request necessary permissions. However, they do not expose any secret
5214 // information, so it is OK to pass them.
5215 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005216 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005217 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005218 case GET_PHYSICAL_DISPLAY_IDS:
5219 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005220 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005221 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005222 case GET_DISPLAY_CONFIGS:
5223 case GET_DISPLAY_STATS:
5224 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5225 // Calling setTransactionState is safe, because you need to have been
5226 // granted a reference to Client* and Handle* to do anything with it.
5227 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005228 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005229 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005230 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005231 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005232 case IS_WIDE_COLOR_DISPLAY:
5233 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5234 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005235 return OK;
5236 }
5237 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005238 case CAPTURE_SCREEN:
5239 case ADD_REGION_SAMPLING_LISTENER:
5240 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005241 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005242 IPCThreadState* ipc = IPCThreadState::self();
5243 const int pid = ipc->getCallingPid();
5244 const int uid = ipc->getCallingUid();
5245 if ((uid != AID_GRAPHICS) &&
5246 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5247 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5248 return PERMISSION_DENIED;
5249 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005250 return OK;
5251 }
5252 // The following codes are deprecated and should never be allowed to access SF.
5253 case CONNECT_DISPLAY_UNUSED:
5254 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5255 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5256 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005257 }
chaviw93df2ea2019-04-30 16:45:12 -07005258 case CAPTURE_SCREEN_BY_ID: {
5259 IPCThreadState* ipc = IPCThreadState::self();
5260 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005261 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005262 return OK;
5263 }
5264 return PERMISSION_DENIED;
5265 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005266 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005267
5268 // These codes are used for the IBinder protocol to either interrogate the recipient
5269 // side of the transaction for its canonical interface descriptor or to dump its state.
5270 // We let them pass by default.
5271 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5272 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5273 code == IBinder::SYSPROPS_TRANSACTION) {
5274 return OK;
5275 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005276 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005277 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005278 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005279 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5280 return OK;
5281 }
5282 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5283 return PERMISSION_DENIED;
5284#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005285}
5286
Ana Krulec13be8ad2018-08-21 02:43:56 +00005287status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5288 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005289 status_t credentialCheck = CheckTransactCodeCredentials(code);
5290 if (credentialCheck != OK) {
5291 return credentialCheck;
5292 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005293
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005294 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5295 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005296 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005297 IPCThreadState* ipc = IPCThreadState::self();
5298 const int uid = ipc->getCallingUid();
5299 if (CC_UNLIKELY(uid != AID_SYSTEM
5300 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005301 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005302 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005303 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005304 return PERMISSION_DENIED;
5305 }
5306 int n;
5307 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005308 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005309 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005310 return NO_ERROR;
5311 case 1002: // SHOW_UPDATES
5312 n = data.readInt32();
5313 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005314 invalidateHwcGeometry();
5315 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005316 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005317 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005318 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005319 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005320 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005321 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005322 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005323 setTransactionFlags(
5324 eTransactionNeeded|
5325 eDisplayTransactionNeeded|
5326 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005327 return NO_ERROR;
5328 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005329 case 1006:{ // send empty update
5330 signalRefresh();
5331 return NO_ERROR;
5332 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005333 case 1008: // toggle use of hw composer
5334 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005335 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005336 invalidateHwcGeometry();
5337 repaintEverything();
5338 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005339 case 1009: // toggle use of transform hint
5340 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005341 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005342 invalidateHwcGeometry();
5343 repaintEverything();
5344 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005345 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005346 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005347 reply->writeInt32(0);
5348 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005349 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005350 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005351 return NO_ERROR;
5352 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005353 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005354 if (!display) {
5355 return NAME_NOT_FOUND;
5356 }
5357
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005358 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005359 return NO_ERROR;
5360 }
5361 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005362 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005363 // daltonize
5364 n = data.readInt32();
5365 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005366 case 1:
5367 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5368 break;
5369 case 2:
5370 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5371 break;
5372 case 3:
5373 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5374 break;
5375 default:
5376 mDaltonizer.setType(ColorBlindnessType::None);
5377 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005378 }
5379 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005380 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005381 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005382 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005383 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005384
5385 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005386 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005387 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005388 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005389 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005390 // apply a color matrix
5391 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005392 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005393 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005394 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005395 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005396 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005397 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005398 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005399 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005400 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005401 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005402
5403 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5404 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005405 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005406 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5407 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5408 }
5409
Chia-I Wu28f320b2018-05-03 11:02:56 -07005410 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005411 return NO_ERROR;
5412 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005413 // This is an experimental interface
5414 // Needs to be shifted to proper binder interface when we productize
5415 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005416 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005417 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005418 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005419 return NO_ERROR;
5420 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005421 case 1017: {
5422 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005423 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005424 return NO_ERROR;
5425 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005426 case 1018: { // Modify Choreographer's phase offset
5427 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005428 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005429 return NO_ERROR;
5430 }
5431 case 1019: { // Modify SurfaceFlinger's phase offset
5432 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005433 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005434 return NO_ERROR;
5435 }
Irvel468051e2016-06-13 16:44:44 -07005436 case 1020: { // Layer updates interceptor
5437 n = data.readInt32();
5438 if (n) {
5439 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005440 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005441 }
5442 else{
5443 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005444 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005445 }
5446 return NO_ERROR;
5447 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005448 case 1021: { // Disable HWC virtual displays
5449 n = data.readInt32();
5450 mUseHwcVirtualDisplays = !n;
5451 return NO_ERROR;
5452 }
Romain Guy0147a172017-06-01 13:53:56 -07005453 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005454 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005455 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005456
Chia-I Wu28f320b2018-05-03 11:02:56 -07005457 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005458 return NO_ERROR;
5459 }
Romain Guy54f154a2017-10-24 21:40:32 +01005460 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005461 int32_t colorMode;
5462
Chia-I Wu0d711262018-05-21 15:19:35 -07005463 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005464 if (data.readInt32(&colorMode) == NO_ERROR) {
5465 mForceColorMode = static_cast<ColorMode>(colorMode);
5466 }
Romain Guy54f154a2017-10-24 21:40:32 +01005467 invalidateHwcGeometry();
5468 repaintEverything();
5469 return NO_ERROR;
5470 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005471 // Deprecate, use 1030 to check whether the device is color managed.
5472 case 1024: {
5473 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005474 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005475 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005476 n = data.readInt32();
5477 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005478 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005479 Mutex::Autolock lock(mStateLock);
5480 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005481 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005482 reply->writeInt32(NO_ERROR);
5483 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005484 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005485 bool writeFile = false;
5486 {
5487 Mutex::Autolock lock(mStateLock);
5488 mTracingEnabledChanged = true;
5489 writeFile = mTracing.disable();
5490 }
5491
5492 if (writeFile) {
5493 reply->writeInt32(mTracing.writeToFile());
5494 } else {
5495 reply->writeInt32(NO_ERROR);
5496 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005497 }
5498 return NO_ERROR;
5499 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005500 case 1026: { // Get layer tracing status
5501 reply->writeBool(mTracing.isEnabled());
5502 return NO_ERROR;
5503 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005504 // Is a DisplayColorSetting supported?
5505 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005506 const auto display = getDefaultDisplayDevice();
5507 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005508 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005509 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005510
5511 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5512 switch (setting) {
5513 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005514 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005515 break;
5516 case DisplayColorSetting::UNMANAGED:
5517 reply->writeBool(true);
5518 break;
5519 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005520 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005521 break;
5522 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005523 reply->writeBool(
5524 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005525 break;
5526 }
5527 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005528 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005529 // Is VrFlinger active?
5530 case 1028: {
5531 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005532 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005533 return NO_ERROR;
5534 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005535 // Set buffer size for SF tracing (value in KB)
5536 case 1029: {
5537 n = data.readInt32();
5538 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5539 ALOGW("Invalid buffer size: %d KB", n);
5540 reply->writeInt32(BAD_VALUE);
5541 return BAD_VALUE;
5542 }
5543
5544 ALOGD("Updating trace buffer to %d KB", n);
5545 mTracing.setBufferSize(n * 1024);
5546 reply->writeInt32(NO_ERROR);
5547 return NO_ERROR;
5548 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005549 // Is device color managed?
5550 case 1030: {
5551 reply->writeBool(useColorManagement);
5552 return NO_ERROR;
5553 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005554 // Override default composition data space
5555 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5556 // && adb shell stop zygote && adb shell start zygote
5557 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5558 // adb shell stop zygote && adb shell start zygote
5559 case 1031: {
5560 Mutex::Autolock _l(mStateLock);
5561 n = data.readInt32();
5562 if (n) {
5563 n = data.readInt32();
5564 if (n) {
5565 Dataspace dataspace = static_cast<Dataspace>(n);
5566 if (!validateCompositionDataspace(dataspace)) {
5567 return BAD_VALUE;
5568 }
5569 mDefaultCompositionDataspace = dataspace;
5570 }
5571 n = data.readInt32();
5572 if (n) {
5573 Dataspace dataspace = static_cast<Dataspace>(n);
5574 if (!validateCompositionDataspace(dataspace)) {
5575 return BAD_VALUE;
5576 }
5577 mWideColorGamutCompositionDataspace = dataspace;
5578 }
5579 } else {
5580 // restore composition data space.
5581 mDefaultCompositionDataspace = defaultCompositionDataspace;
5582 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5583 }
5584 return NO_ERROR;
5585 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005586 // Set trace flags
5587 case 1033: {
5588 n = data.readUint32();
5589 ALOGD("Updating trace flags to 0x%x", n);
5590 mTracing.setTraceFlags(n);
5591 reply->writeInt32(NO_ERROR);
5592 return NO_ERROR;
5593 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005594 case 1034: {
5595 // TODO(b/129297325): expose this via developer menu option
5596 n = data.readInt32();
Steven Thomase9eb1832019-08-28 16:08:35 -07005597 if (n && !mRefreshRateOverlay &&
5598 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005599 RefreshRateType type;
5600 {
5601 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5602 type = mDesiredActiveConfig.type;
5603 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005604 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005605 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005606 } else if (!n) {
5607 mRefreshRateOverlay.reset();
5608 }
5609 return NO_ERROR;
5610 }
Ady Abraham34392f72019-04-10 11:29:27 -07005611 case 1035: {
5612 n = data.readInt32();
5613 mDebugDisplayConfigSetByBackdoor = false;
5614 if (n >= 0) {
5615 const auto displayToken = getInternalDisplayToken();
5616 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5617 if (result != NO_ERROR) {
5618 return result;
5619 }
5620 mDebugDisplayConfigSetByBackdoor = true;
5621 }
5622 return NO_ERROR;
5623 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005624 }
5625 }
5626 return err;
5627}
5628
Steven Thomas6d8110b2017-08-31 18:24:21 -07005629void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005630 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005631 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005632}
5633
Ana Krulec7d1d6832018-12-27 11:10:09 -08005634void SurfaceFlinger::repaintEverythingForHWC() {
5635 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005636 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005637}
5638
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005639// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5640class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005641public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005642 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5643 ~WindowDisconnector() {
5644 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005645 }
5646
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005647private:
5648 ANativeWindow* mWindow;
5649 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005650};
5651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005652status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005653 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5654 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005655 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005656 uint32_t reqWidth, uint32_t reqHeight,
5657 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005658 ISurfaceComposer::Rotation rotation,
5659 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005660 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005661
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005662 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005663
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005664 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5665
Chia-I Wu20261cb2018-08-23 12:55:44 -07005666 sp<DisplayDevice> display;
5667 {
5668 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005669
Chia-I Wu20261cb2018-08-23 12:55:44 -07005670 display = getDisplayDeviceLocked(displayToken);
5671 if (!display) return BAD_VALUE;
5672
Chia-I Wucb023152018-08-28 12:57:23 -07005673 // set the requested width/height to the logical display viewport size
5674 // by default
5675 if (reqWidth == 0 || reqHeight == 0) {
5676 reqWidth = uint32_t(display->getViewport().width());
5677 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005678 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005679 }
5680
Peiyong Lin0e003c92018-09-17 11:09:51 -07005681 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005682 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005683
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005684 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5685 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005686 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005687 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005688}
5689
chaviw93df2ea2019-04-30 16:45:12 -07005690static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5691 switch (colorMode) {
5692 case ColorMode::DISPLAY_P3:
5693 case ColorMode::BT2100_PQ:
5694 case ColorMode::BT2100_HLG:
5695 case ColorMode::DISPLAY_BT2020:
5696 return Dataspace::DISPLAY_P3;
5697 default:
5698 return Dataspace::V0_SRGB;
5699 }
5700}
5701
5702const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5703 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5704 if (displayToken) {
5705 return getDisplayDeviceLocked(displayToken);
5706 }
5707 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5708 // may not have a displayId.
5709 for (const auto& [token, display] : mDisplays) {
5710 if (display->getLayerStack() == displayOrLayerStack) {
5711 return display;
5712 }
5713 }
5714 return nullptr;
5715}
5716
5717status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5718 sp<GraphicBuffer>* outBuffer) {
5719 sp<DisplayDevice> display;
5720 uint32_t width;
5721 uint32_t height;
5722 ui::Transform::orientation_flags captureOrientation;
5723 {
5724 Mutex::Autolock _l(mStateLock);
5725 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5726 if (!display) {
5727 return BAD_VALUE;
5728 }
5729
5730 width = uint32_t(display->getViewport().width());
5731 height = uint32_t(display->getViewport().height());
5732
5733 captureOrientation = fromSurfaceComposerRotation(
5734 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005735 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5736 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5737 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5738 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5739 }
chaviw93df2ea2019-04-30 16:45:12 -07005740 *outDataspace =
5741 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5742 }
5743
5744 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5745 false /* captureSecureLayers */);
5746
5747 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5748 std::placeholders::_1);
5749 bool ignored = false;
5750 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5751 false /* useIdentityTransform */,
5752 ignored /* outCapturedSecureLayers */);
5753}
5754
Robert Carr866455f2019-04-02 16:28:26 -07005755status_t SurfaceFlinger::captureLayers(
5756 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5757 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5758 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5759 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005760 ATRACE_CALL();
5761
5762 class LayerRenderArea : public RenderArea {
5763 public:
Robert Carr578038f2018-03-09 12:25:24 -08005764 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005765 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5766 bool childrenOnly)
5767 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005768 mLayer(layer),
5769 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005770 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005771 mFlinger(flinger),
5772 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005773 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005774 Rect getBounds() const override {
5775 const Layer::State& layerState(mLayer->getDrawingState());
5776 return mLayer->getBufferSize(layerState);
5777 }
Marissa Wall61c58622018-07-18 10:12:20 -07005778 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005779 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005780 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005781 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005782 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005783 }
chaviwa76b2712017-09-20 12:02:26 -07005784 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005785 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005786 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005787 Rect getSourceCrop() const override {
5788 if (mCrop.isEmpty()) {
5789 return getBounds();
5790 } else {
5791 return mCrop;
5792 }
5793 }
Robert Carr578038f2018-03-09 12:25:24 -08005794 class ReparentForDrawing {
5795 public:
5796 const sp<Layer>& oldParent;
5797 const sp<Layer>& newParent;
5798
Vishnu Nair4351ad52019-02-11 14:13:02 -08005799 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5800 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005801 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005802 // Compute and cache the bounds for the new parent layer.
5803 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005804 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005805 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005806 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005807 };
5808
5809 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005810 const Rect sourceCrop = getSourceCrop();
5811 // no need to check rotation because there is none
5812 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5813 sourceCrop.height() != getReqHeight();
5814
Robert Carr578038f2018-03-09 12:25:24 -08005815 if (!mChildrenOnly) {
5816 mTransform = mLayer->getTransform().inverse();
5817 drawLayers();
5818 } else {
5819 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005820 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005821 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005822 bounds.getWidth(), bounds.getHeight(), 0,
5823 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005824
Vishnu Nair4351ad52019-02-11 14:13:02 -08005825 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005826 drawLayers();
5827 }
5828 }
chaviwa76b2712017-09-20 12:02:26 -07005829
chaviwa76b2712017-09-20 12:02:26 -07005830 private:
chaviw7206d492017-11-10 16:16:12 -08005831 const sp<Layer> mLayer;
5832 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005833
5834 // In the "childrenOnly" case we reparent the children to a screenshot
5835 // layer which has no properties set and which does not draw.
5836 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005837 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005838 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005839
5840 SurfaceFlinger* mFlinger;
5841 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005842 };
5843
Robert Carrc0df3122019-04-11 13:18:21 -07005844 int reqWidth = 0;
5845 int reqHeight = 0;
5846 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005847 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005848 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005849
Robert Carrc0df3122019-04-11 13:18:21 -07005850 {
5851 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005852
Robert Carrc0df3122019-04-11 13:18:21 -07005853 parent = fromHandle(layerHandleBinder);
5854 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5855 ALOGE("captureLayers called with an invalid or removed parent");
5856 return NAME_NOT_FOUND;
5857 }
5858
5859 const int uid = IPCThreadState::self()->getCallingUid();
5860 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5861 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5862 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5863 return PERMISSION_DENIED;
5864 }
5865
5866 if (sourceCrop.width() <= 0) {
5867 crop.left = 0;
5868 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5869 }
5870
5871 if (sourceCrop.height() <= 0) {
5872 crop.top = 0;
5873 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5874 }
5875 reqWidth = crop.width() * frameScale;
5876 reqHeight = crop.height() * frameScale;
5877
5878 for (const auto& handle : excludeHandles) {
5879 sp<Layer> excludeLayer = fromHandle(handle);
5880 if (excludeLayer != nullptr) {
5881 excludeLayers.emplace(excludeLayer);
5882 } else {
5883 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5884 return NAME_NOT_FOUND;
5885 }
5886 }
5887 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005888
Chia-I Wu20261cb2018-08-23 12:55:44 -07005889 // really small crop or frameScale
5890 if (reqWidth <= 0) {
5891 reqWidth = 1;
5892 }
5893 if (reqHeight <= 0) {
5894 reqHeight = 1;
5895 }
5896
Robert Carr866455f2019-04-02 16:28:26 -07005897 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5898 auto traverseLayers = [parent, childrenOnly,
5899 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005900 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5901 if (!layer->isVisible()) {
5902 return;
Robert Carr578038f2018-03-09 12:25:24 -08005903 } else if (childrenOnly && layer == parent.get()) {
5904 return;
chaviwa76b2712017-09-20 12:02:26 -07005905 }
Robert Carr866455f2019-04-02 16:28:26 -07005906
5907 sp<Layer> p = layer;
5908 while (p != nullptr) {
5909 if (excludeLayers.count(p) != 0) {
5910 return;
5911 }
5912 p = p->getParent();
5913 }
5914
chaviwa76b2712017-09-20 12:02:26 -07005915 visitor(layer);
5916 });
5917 };
Robert Carr108b2c72019-04-02 16:32:58 -07005918
5919 bool outCapturedSecureLayers = false;
5920 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5921 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005922}
5923
5924status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5925 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005926 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005927 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005928 bool useIdentityTransform,
5929 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005930 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005931
Peiyong Lin0e003c92018-09-17 11:09:51 -07005932 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005933 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5934 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005935 *outBuffer =
5936 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5937 static_cast<android_pixel_format>(reqPixelFormat), 1,
5938 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005939
Robert Carr108b2c72019-04-02 16:32:58 -07005940 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5941 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005942}
5943
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005944status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5945 TraverseLayersFunction traverseLayers,
5946 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005947 bool useIdentityTransform,
5948 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005949 // This mutex protects syncFd and captureResult for communication of the return values from the
5950 // main thread back to this Binder thread
5951 std::mutex captureMutex;
5952 std::condition_variable captureCondition;
5953 std::unique_lock<std::mutex> captureLock(captureMutex);
5954 int syncFd = -1;
5955 std::optional<status_t> captureResult;
5956
Robert Carr03480e22018-01-04 16:02:06 -08005957 const int uid = IPCThreadState::self()->getCallingUid();
5958 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5959
Dominik Laskowski8c001672018-05-30 16:52:06 -07005960 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005961 // If there is a refresh pending, bug out early and tell the binder thread to try again
5962 // after the refresh.
5963 if (mRefreshPending) {
5964 ATRACE_NAME("Skipping screenshot for now");
5965 std::unique_lock<std::mutex> captureLock(captureMutex);
5966 captureResult = std::make_optional<status_t>(EAGAIN);
5967 captureCondition.notify_one();
5968 return;
5969 }
5970
5971 status_t result = NO_ERROR;
5972 int fd = -1;
5973 {
5974 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005975 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005976 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005977 useIdentityTransform, forSystem, &fd,
5978 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005979 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005980 }
5981
5982 {
5983 std::unique_lock<std::mutex> captureLock(captureMutex);
5984 syncFd = fd;
5985 captureResult = std::make_optional<status_t>(result);
5986 captureCondition.notify_one();
5987 }
5988 });
5989
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005990 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005991 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005992 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005993 while (*captureResult == EAGAIN) {
5994 captureResult.reset();
5995 result = postMessageAsync(message);
5996 if (result != NO_ERROR) {
5997 return result;
5998 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005999 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006000 }
6001 result = *captureResult;
6002 }
6003
6004 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006005 sync_wait(syncFd, -1);
6006 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006007 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006008
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006009 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006010}
6011
chaviwa76b2712017-09-20 12:02:26 -07006012void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006013 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006014 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6015 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006016 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006017
chaviwa76b2712017-09-20 12:02:26 -07006018 const auto reqWidth = renderArea.getReqWidth();
6019 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006020 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006021 const auto transform = renderArea.getTransform();
6022 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006023
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006024 renderengine::DisplaySettings clientCompositionDisplay;
6025 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006026
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006027 // assume that bounds are never offset, and that they are the same as the
6028 // buffer bounds.
6029 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006030 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006031 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006032
6033 // Now take into account the rotation flag. We append a transform that
6034 // rotates the layer stack about the origin, then translate by buffer
6035 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006036 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006037 int displacementX = 0;
6038 int displacementY = 0;
6039 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6040 switch (rotation) {
6041 case ui::Transform::ROT_90:
6042 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006043 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006044 break;
6045 case ui::Transform::ROT_180:
6046 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006047 displacementY = renderArea.getBounds().getWidth();
6048 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006049 break;
6050 case ui::Transform::ROT_270:
6051 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006052 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006053 break;
6054 default:
6055 break;
6056 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006057
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006058 // We need to transform the clipping window into the right spot.
6059 // First, rotate the clipping rectangle by the rotation hint to get the
6060 // right orientation
6061 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6062 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6063 const vec4 rotClipTL = rotMatrix * clipTL;
6064 const vec4 rotClipBR = rotMatrix * clipBR;
6065 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6066 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6067 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6068 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6069
6070 // Now reposition the clipping rectangle with the displacement vector
6071 // computed above.
6072 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006073 clientCompositionDisplay.clip =
6074 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6075 newClipRight + displacementX, newClipBottom + displacementY);
6076
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006077 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006078 clientCompositionDisplay.globalTransform =
6079 clipTransform * clientCompositionDisplay.globalTransform;
6080
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006081 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6082 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006083
chaviw50da5042018-04-09 13:49:37 -07006084 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006085
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006086 renderengine::LayerSettings fillLayer;
6087 fillLayer.source.buffer.buffer = nullptr;
6088 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6089 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6090 fillLayer.alpha = half(alpha);
6091 clientCompositionLayers.push_back(fillLayer);
6092
6093 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006094 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006095 renderengine::LayerSettings layerSettings;
6096 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006097 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006098 if (prepared) {
6099 clientCompositionLayers.push_back(layerSettings);
6100 }
chaviwa76b2712017-09-20 12:02:26 -07006101 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006102
6103 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006104 // Use an empty fence for the buffer fence, since we just created the buffer so
6105 // there is no need for synchronization with the GPU.
6106 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006107 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006108 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006109 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006110 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006111
6112 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006113}
6114
chaviwa76b2712017-09-20 12:02:26 -07006115status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6116 TraverseLayersFunction traverseLayers,
6117 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006118 bool useIdentityTransform, bool forSystem,
6119 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006120 ATRACE_CALL();
6121
chaviwa76b2712017-09-20 12:02:26 -07006122 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006123 outCapturedSecureLayers =
6124 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006125 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006126
Robert Carr03480e22018-01-04 16:02:06 -08006127 // We allow the system server to take screenshots of secure layers for
6128 // use in situations like the Screen-rotation animation and place
6129 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006130 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006131 ALOGW("FB is protected: PERMISSION_DENIED");
6132 return PERMISSION_DENIED;
6133 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006134 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006135 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006136}
6137
chaviw95ef3c42019-02-14 10:55:09 -08006138void SurfaceFlinger::setInputWindowsFinished() {
6139 Mutex::Autolock _l(mStateLock);
6140
6141 mPendingSyncInputWindows = false;
6142 mTransactionCV.broadcast();
6143}
chaviw5f21a5e2019-02-14 10:00:34 -08006144
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006145// ---------------------------------------------------------------------------
6146
Dan Stoza412903f2017-04-27 13:42:17 -07006147void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6148 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006149}
6150
Dan Stoza412903f2017-04-27 13:42:17 -07006151void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6152 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006153}
6154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006155void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006156 const LayerVector::Visitor& visitor) {
6157 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006158 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006159 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006160 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006161 continue;
6162 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006163 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006164 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006165 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006166 return;
6167 }
chaviwa76b2712017-09-20 12:02:26 -07006168 if (!layer->isVisible()) {
6169 return;
6170 }
6171 visitor(layer);
6172 });
6173 }
6174}
6175
Dominik Laskowski22488f62019-03-28 09:53:04 -07006176void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6177 const std::vector<int32_t>& allowedConfigs) {
6178 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006179 return;
6180 }
6181
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006182 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
6183 allowedConfigs.end());
6184 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
6185 return;
6186 }
6187
Ady Abraham838de062019-02-04 10:24:03 -08006188 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006189 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
6190
6191 // TODO(b/140204874): This hack triggers a notification that something has changed, so
6192 // that listeners that care about a change in allowed configs can get the notification.
6193 // Giving current ActiveConfig so that most other listeners would just drop the event
6194 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
6195 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08006196
Steven Thomase9eb1832019-08-28 16:08:35 -07006197 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
6198 // Set the highest allowed config by iterating backwards on available refresh rates
6199 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
6200 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
6201 if (isDisplayConfigAllowed(iter->second.configId)) {
6202 ALOGV("switching to allowed config %d", iter->second.configId);
6203 setDesiredActiveConfig(
6204 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
6205 break;
6206 }
Ady Abraham97d04232019-03-05 19:48:12 -08006207 }
Steven Thomase9eb1832019-08-28 16:08:35 -07006208 } else if (!isDisplayConfigAllowed(display->getActiveConfig())) {
6209 ALOGV("switching to config %d", allowedConfigs[0]);
6210 setDesiredActiveConfig(
6211 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
Ady Abraham97d04232019-03-05 19:48:12 -08006212 }
Ady Abraham838de062019-02-04 10:24:03 -08006213}
6214
Dominik Laskowski22488f62019-03-28 09:53:04 -07006215status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006216 const std::vector<int32_t>& allowedConfigs) {
6217 ATRACE_CALL();
6218
Dominik Laskowski22488f62019-03-28 09:53:04 -07006219 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006220 return BAD_VALUE;
6221 }
6222
Ady Abraham34392f72019-04-10 11:29:27 -07006223 if (mDebugDisplayConfigSetByBackdoor) {
6224 // ignore this request as config is overridden by backdoor
6225 return NO_ERROR;
6226 }
6227
Ady Abrahamabf91062019-10-18 14:17:23 -07006228 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006229 const auto display = getDisplayDeviceLocked(displayToken);
6230 if (!display) {
6231 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6232 displayToken.get());
6233 } else if (display->isVirtual()) {
6234 ALOGW("Attempt to set allowed display configs for virtual display");
6235 } else {
Ady Abrahamabf91062019-10-18 14:17:23 -07006236 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006237 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6238 }
Ady Abraham838de062019-02-04 10:24:03 -08006239 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006240
Ady Abraham838de062019-02-04 10:24:03 -08006241 return NO_ERROR;
6242}
6243
Dominik Laskowski22488f62019-03-28 09:53:04 -07006244status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006245 std::vector<int32_t>* outAllowedConfigs) {
6246 ATRACE_CALL();
6247
Dominik Laskowski22488f62019-03-28 09:53:04 -07006248 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006249 return BAD_VALUE;
6250 }
6251
Dominik Laskowski22488f62019-03-28 09:53:04 -07006252 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006253
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006254 const auto display = getDisplayDeviceLocked(displayToken);
6255 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006256 return NAME_NOT_FOUND;
6257 }
6258
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006259 if (display->isPrimary()) {
6260 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6261 }
6262
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006263 return NO_ERROR;
6264}
6265
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006266void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006267 mFlinger->setInputWindowsFinished();
6268}
6269
Robert Carrc0df3122019-04-11 13:18:21 -07006270sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6271 BBinder *b = handle->localBinder();
6272 if (b == nullptr) {
6273 return nullptr;
6274 }
6275 auto it = mLayersByLocalBinderToken.find(b);
6276 if (it != mLayersByLocalBinderToken.end()) {
6277 return it->second.promote();
6278 }
6279 return nullptr;
6280}
6281
Alec Mouri4545a8a2019-08-08 20:05:32 -07006282void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6283 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6284}
6285
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006286} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006287
Mathias Agopian3f844832013-08-07 21:24:32 -07006288#if defined(__gl_h_)
6289#error "don't include gl/gl.h in this file"
6290#endif
6291
6292#if defined(__gl2_h_)
6293#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006294#endif