blob: 5b8255667bed24b80b82c2e9d9897e152c30b664 [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>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070098#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700100#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/EventControlThread.h"
102#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700103#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
David Sodman7e4ae112018-02-09 15:02:28 -0800111#include "android-base/stringprintf.h"
112
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700116#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900117#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
chaviw1d044282017-09-27 12:19:28 -0700119#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900120#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700123
Jaesoo Lee43518572017-01-23 19:03:16 +0900124using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900125using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900126using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800127
Ady Abraham8532d012019-05-08 14:50:56 -0700128using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800129using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700130using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700131using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800132using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700133using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700134using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900135
Steven Thomasb02664d2017-07-26 18:48:28 -0700136namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700137
138#pragma clang diagnostic push
139#pragma clang diagnostic error "-Wswitch-enum"
140
141bool isWideColorMode(const ColorMode colorMode) {
142 switch (colorMode) {
143 case ColorMode::DISPLAY_P3:
144 case ColorMode::ADOBE_RGB:
145 case ColorMode::DCI_P3:
146 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700147 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700148 case ColorMode::BT2100_PQ:
149 case ColorMode::BT2100_HLG:
150 return true;
151 case ColorMode::NATIVE:
152 case ColorMode::STANDARD_BT601_625:
153 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
154 case ColorMode::STANDARD_BT601_525:
155 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
156 case ColorMode::STANDARD_BT709:
157 case ColorMode::SRGB:
158 return false;
159 }
160 return false;
161}
162
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700163bool isHdrColorMode(const ColorMode colorMode) {
164 switch (colorMode) {
165 case ColorMode::BT2100_PQ:
166 case ColorMode::BT2100_HLG:
167 return true;
168 case ColorMode::DISPLAY_P3:
169 case ColorMode::ADOBE_RGB:
170 case ColorMode::DCI_P3:
171 case ColorMode::BT2020:
172 case ColorMode::DISPLAY_BT2020:
173 case ColorMode::NATIVE:
174 case ColorMode::STANDARD_BT601_625:
175 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
176 case ColorMode::STANDARD_BT601_525:
177 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
178 case ColorMode::STANDARD_BT709:
179 case ColorMode::SRGB:
180 return false;
181 }
182 return false;
183}
184
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700185ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
186 switch (rotation) {
187 case ISurfaceComposer::eRotateNone:
188 return ui::Transform::ROT_0;
189 case ISurfaceComposer::eRotate90:
190 return ui::Transform::ROT_90;
191 case ISurfaceComposer::eRotate180:
192 return ui::Transform::ROT_180;
193 case ISurfaceComposer::eRotate270:
194 return ui::Transform::ROT_270;
195 }
196 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
197 return ui::Transform::ROT_0;
198}
199
Peiyong Linfca547f2018-07-09 13:03:33 -0700200#pragma clang diagnostic pop
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202class ConditionalLock {
203public:
204 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
205 if (lock) {
206 mMutex.lock();
207 }
208 }
209 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
210private:
211 Mutex& mMutex;
212 bool mLocked;
213};
Peiyong Linfca547f2018-07-09 13:03:33 -0700214
Peiyong Lin9d846a52018-11-05 13:18:20 -0800215// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
216bool validateCompositionDataspace(Dataspace dataspace) {
217 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
218}
219
Steven Thomasb02664d2017-07-26 18:48:28 -0700220} // namespace anonymous
221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222// ---------------------------------------------------------------------------
223
Mathias Agopian99b49842011-06-27 16:05:52 -0700224const String16 sHardwareTest("android.permission.HARDWARE_TEST");
225const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
226const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
227const String16 sDump("android.permission.DUMP");
228
229// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700230int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700231bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800232uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800233bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800234bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800235int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700237int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700244
Kalle Raitaa099a242017-01-11 11:17:29 -0800245std::string getHwcServiceName() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.hwc_service_name", value, "default");
248 ALOGI("Using HWComposer service: '%s'", value);
249 return std::string(value);
250}
251
252bool useTrebleTestingOverride() {
253 char value[PROPERTY_VALUE_MAX] = {};
254 property_get("debug.sf.treble_testing_override", value, "false");
255 ALOGI("Treble testing override: '%s'", value);
256 return std::string(value) == "true";
257}
258
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
260 switch(displayColorSetting) {
261 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800265 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Enhanced");
267 default:
268 return std::string("Unknown ") +
269 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800270 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271}
272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
276 : mFactory(factory),
277 mPhaseOffsets(mFactory.createPhaseOffsets()),
278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
279 mTimeStats(mFactory.createTimeStats()),
280 mEventQueue(mFactory.createMessageQueue()),
281 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800282
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700283SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293
Steven Thomas050b2c82017-03-06 11:45:16 -0800294 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 mDefaultCompositionDataspace =
304 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700305 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
306 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 defaultCompositionDataspace = mDefaultCompositionDataspace;
308 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
309 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
310 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
311 wideColorGamutCompositionPixelFormat =
312 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700313
Yichi Chenda901bf2019-06-28 14:58:27 +0800314 mColorSpaceAgnosticDataspace =
315 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
316
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900317 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
320 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
321 switch (tmpPrimaryDisplayOrientation) {
322 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
331 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800333 break;
334 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700335 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800336
Sundong Ahn85131bd2019-02-18 15:51:53 +0900337 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800338
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800339 // debugging stuff...
340 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700341
Mathias Agopianb4b17302013-03-20 18:36:41 -0700342 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700343 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800345 property_get("debug.sf.showupdates", value, "0");
346 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700347
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700348 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000349
350 // DDMS debugging deprecated (b/120782499)
351 property_get("debug.sf.ddms", value, "0");
352 int debugDdms = atoi(value);
353 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700354
355 property_get("debug.sf.disable_backpressure", value, "0");
356 mPropagateBackpressure = !atoi(value);
357 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700358
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800359 property_get("debug.sf.enable_hwc_vds", value, "0");
360 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800361 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800363 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800364 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700366
Yiwei Zhang243b3782018-05-15 17:40:04 -0700367 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700368 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
369 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
370
Ana Krulece5a06e02019-03-06 17:09:03 -0800371 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800372 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800373
374 int int_value = atoi(value);
375 if (int_value) {
376 mUseSmart90ForVideo = true;
377 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800378
Dan Stozaec460082018-12-17 15:35:09 -0800379 property_get("debug.sf.luma_sampling", value, "1");
380 mLumaSampling = atoi(value);
381
Ana Krulec757f63a2019-01-25 10:46:18 -0800382 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700383 mVsyncModulator.setPhaseOffsets(early, gl, late,
384 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700385
Romain Guy11d63f42017-07-20 12:47:14 -0700386 // We should be reading 'persist.sys.sf.color_saturation' here
387 // but since /data may be encrypted, we need to wait until after vold
388 // comes online to attempt to read the property. The property is
389 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800390
391 if (useTrebleTestingOverride()) {
392 // Without the override SurfaceFlinger cannot connect to HIDL
393 // services that are not listed in the manifests. Considered
394 // deriving the setting from the set service name, but it
395 // would be brittle if the name that's not 'default' is used
396 // for production purposes later on.
397 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
398 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399}
400
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800401void SurfaceFlinger::onFirstRef()
402{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800403 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404}
405
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700406SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407
Dan Stozac7014012014-02-14 15:03:43 -0800408void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409{
410 // the window manager died on us. prepare its eulogy.
411
Andy McFadden13a082e2012-08-24 10:16:42 -0700412 // restore initial conditions (default device unblank, etc)
413 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414
415 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700416 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417}
418
Robert Carr1db73f62016-12-21 12:58:51 -0800419static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700420 status_t err = client->initCheck();
421 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800422 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800423 }
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return nullptr;
425}
426
427sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
428 return initClient(new Client(this));
429}
430
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700431sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
432 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433{
434 class DisplayToken : public BBinder {
435 sp<SurfaceFlinger> flinger;
436 virtual ~DisplayToken() {
437 // no more references, this display must be terminated
438 Mutex::Autolock _l(flinger->mStateLock);
439 flinger->mCurrentState.displays.removeItem(this);
440 flinger->setTransactionFlags(eDisplayTransactionNeeded);
441 }
442 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700443 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700444 : flinger(flinger) {
445 }
446 };
447
448 sp<BBinder> token = new DisplayToken(this);
449
450 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 // Display ID is assigned when virtual display is allocated by HWC.
452 DisplayDeviceState state;
453 state.isSecure = secure;
454 state.displayName = displayName;
455 mCurrentState.displays.add(token, state);
456 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 return token;
458}
459
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700460void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 Mutex::Autolock _l(mStateLock);
462
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
464 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700465 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700466 return;
467 }
468
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
470 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700471 ALOGE("destroyDisplay called for non-virtual display");
472 return;
473 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700474 mInterceptor->saveDisplayDeletion(state.sequenceId);
475 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700476 setTransactionFlags(eDisplayTransactionNeeded);
477}
478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
480 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482 const auto internalDisplayId = getInternalDisplayIdLocked();
483 if (!internalDisplayId) {
484 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700485 }
486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487 std::vector<PhysicalDisplayId> displayIds;
488 displayIds.reserve(mPhysicalDisplayTokens.size());
489 displayIds.push_back(internalDisplayId->value);
490
491 for (const auto& [id, token] : mPhysicalDisplayTokens) {
492 if (id != *internalDisplayId) {
493 displayIds.push_back(id.value);
494 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700495 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800497 return displayIds;
498}
499
500sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
501 Mutex::Autolock lock(mStateLock);
502 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503}
504
Ady Abraham37965d42018-11-01 13:43:32 -0700505status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
506 if (!outGetColorManagement) {
507 return BAD_VALUE;
508 }
509 *outGetColorManagement = useColorManagement;
510 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700511}
512
Lloyd Pique441d5042018-10-18 16:49:51 -0700513HWComposer& SurfaceFlinger::getHwComposer() const {
514 return mCompositionEngine->getHwComposer();
515}
516
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700517renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
518 return mCompositionEngine->getRenderEngine();
519}
520
Lloyd Pique70d91362018-10-18 16:02:55 -0700521compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
522 return *mCompositionEngine.get();
523}
524
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800525void SurfaceFlinger::bootFinished()
526{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700527 if (mStartPropertySetThread->join() != NO_ERROR) {
528 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800529 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800530 const nsecs_t now = systemTime();
531 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000532 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533
534 // wait patiently for the window manager death
535 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700536 mWindowManager = defaultServiceManager()->getService(name);
537 if (mWindowManager != 0) {
538 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700539 }
Robert Carr720e5062018-07-30 17:45:14 -0700540 sp<IBinder> input(defaultServiceManager()->getService(
541 String16("inputflinger")));
542 if (input == nullptr) {
543 ALOGE("Failed to link to input service");
544 } else {
545 mInputFlinger = interface_cast<IInputFlinger>(input);
546 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700547
Steven Thomas050b2c82017-03-06 11:45:16 -0800548 if (mVrFlinger) {
549 mVrFlinger->OnBootFinished();
550 }
551
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700552 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700553 // formerly we would just kill the process, but we now ask it to exit so it
554 // can choose where to stop the animation.
555 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700556
557 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
558 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
559 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700560
Ana Krulecbd6654b2019-02-15 15:18:15 -0800561 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800562 readPersistentProperties();
563 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800564
Ady Abraham97d04232019-03-05 19:48:12 -0800565 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700566 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700567 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800568
Dominik Laskowski22488f62019-03-28 09:53:04 -0700569 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800570 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800572 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800573 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800574 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800575}
576
Dan Stoza436ccf32018-06-21 12:10:12 -0700577uint32_t SurfaceFlinger::getNewTexture() {
578 {
579 std::lock_guard lock(mTexturePoolMutex);
580 if (!mTexturePool.empty()) {
581 uint32_t name = mTexturePool.back();
582 mTexturePool.pop_back();
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
584 return name;
585 }
586
587 // The pool was too small, so increase it for the future
588 ++mTexturePoolSize;
589 }
590
591 // The pool was empty, so we need to get a new texture name directly using a
592 // blocking call to the main thread
593 uint32_t name = 0;
594 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
595 return name;
596}
597
Mathias Agopian3f844832013-08-07 21:24:32 -0700598void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700599 std::lock_guard lock(mTexturePoolMutex);
600 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
601 // to actually delete this or not based on mTexturePoolSize
602 mTexturePool.push_back(texture);
603 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700604}
605
Wei Wangf9b05ee2017-07-19 20:59:39 -0700606// Do not call property_set on main thread which will be blocked by init
607// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700609 ALOGI( "SurfaceFlinger's main thread ready to run. "
610 "Initializing graphics H/W...");
611
Ana Krulec757f63a2019-01-25 10:46:18 -0800612 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900613
Steven Thomasb02664d2017-07-26 18:48:28 -0700614 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800616 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700617 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
618 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800619 auto resyncCallback =
620 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800621
Ana Krulecc2870422019-01-29 19:00:58 -0800622 mAppConnectionHandle =
Ady Abraham45e4e362019-06-07 18:20:51 -0700623 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
624 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800625 resyncCallback,
626 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700627 mSfConnectionHandle =
628 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
629 mPhaseOffsets->getOffsetThresholdForNextVsync(),
630 resyncCallback, [this](nsecs_t timestamp) {
631 mInterceptor->saveVSyncEvent(timestamp);
632 });
Ana Krulecc2870422019-01-29 19:00:58 -0800633
634 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
635 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
636 mSfConnectionHandle.get());
637
Kevin DuBois413287f2019-02-25 08:46:47 -0800638 mRegionSamplingThread =
639 new RegionSamplingThread(*this, *mScheduler,
640 RegionSamplingThread::EnvironmentTimingTunables());
641
Steven Thomasb02664d2017-07-26 18:48:28 -0700642 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700643 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700644 renderEngineFeature |= (useColorManagement ?
645 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700646 renderEngineFeature |= (useContextPriority ?
647 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700648 renderEngineFeature |=
649 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
650 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700651
652 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800653 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700654 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700655 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800656 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700657
658 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
659 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700660 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
661 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800662 // Process any initial hotplug and resulting display changes.
663 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 const auto display = getDefaultDisplayDeviceLocked();
665 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700666 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800668
Steven Thomas050b2c82017-03-06 11:45:16 -0800669 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700670 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700671 // This callback is called from the vr flinger dispatch thread. We
672 // need to call signalTransaction(), which requires holding
673 // mStateLock when we're not on the main thread. Acquiring
674 // mStateLock from the vr flinger dispatch thread might trigger a
675 // deadlock in surface flinger (see b/66916578), so post a message
676 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
679 mVrFlingerRequestsDisplay = requestDisplay;
680 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700683 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
684 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700685 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700686 .value_or(0),
687 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800688 if (!mVrFlinger) {
689 ALOGE("Failed to start vrflinger");
690 }
691 }
692
Mathias Agopian92a979a2012-08-02 18:32:23 -0700693 // initialize our drawing state
694 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700695
Andy McFadden13a082e2012-08-24 10:16:42 -0700696 // set initial conditions (e.g. unblank default device)
697 initializeDisplays();
698
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700699 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700700
Wei Wangf9b05ee2017-07-19 20:59:39 -0700701 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700702
703 const bool presentFenceReliable =
704 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
705 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706
707 if (mStartPropertySetThread->Start() != NO_ERROR) {
708 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800709 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800710
Alec Mouri93bc83d2019-04-17 14:47:43 -0700711 mScheduler->setChangeRefreshRateCallback(
712 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
713 Mutex::Autolock lock(mStateLock);
714 setRefreshRateTo(type, event);
715 });
Alec Mouri7f015182019-07-11 13:56:22 -0700716 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
717 Mutex::Autolock lock(mStateLock);
718 const auto display = getDefaultDisplayDeviceLocked();
719 if (!display) {
720 // If we don't have a default display the fallback to the default
721 // refresh rate type
722 return RefreshRateType::DEFAULT;
723 }
724
725 const int configId = display->getActiveConfig();
726 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
727 if (refresh && refresh->configId == configId) {
728 return type;
729 }
730 }
731 // This should never happen, but just gracefully fallback to default.
732 return RefreshRateType::DEFAULT;
733 });
Alec Mouridc28b372019-04-18 21:17:13 -0700734 mScheduler->setGetVsyncPeriodCallback([this] {
735 Mutex::Autolock lock(mStateLock);
736 return getVsyncPeriod();
737 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700738
Dominik Laskowski22488f62019-03-28 09:53:04 -0700739 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
740 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800741
Dan Stoza9e56aa02015-11-02 13:00:03 -0800742 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700743}
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700746 Mutex::Autolock _l(mStateLock);
747
Romain Guy11d63f42017-07-20 12:47:14 -0700748 char value[PROPERTY_VALUE_MAX];
749
750 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800751 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700752 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100754
755 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700756 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800757
758 property_get("persist.sys.sf.color_mode", value, "0");
759 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700760}
761
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800763 // Start boot animation service by setting a property mailbox
764 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800766 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 if (mStartPropertySetThread->join() != NO_ERROR) {
768 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800769 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700770}
771
Mathias Agopian875d8e12013-06-07 15:35:48 -0700772size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700773 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800780// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800781
Jamie Gennis582270d2011-08-17 18:19:00 -0700782bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800784 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800785 return authenticateSurfaceTextureLocked(bufferProducer);
786}
787
788bool SurfaceFlinger::authenticateSurfaceTextureLocked(
789 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800790 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800791 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800792}
793
Brian Anderson6b376712017-04-04 10:51:39 -0700794status_t SurfaceFlinger::getSupportedFrameTimestamps(
795 std::vector<FrameEvent>* outSupported) const {
796 *outSupported = {
797 FrameEvent::REQUESTED_PRESENT,
798 FrameEvent::ACQUIRE,
799 FrameEvent::LATCH,
800 FrameEvent::FIRST_REFRESH_START,
801 FrameEvent::LAST_REFRESH_START,
802 FrameEvent::GPU_COMPOSITION_DONE,
803 FrameEvent::DEQUEUE_READY,
804 FrameEvent::RELEASE,
805 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700806 ConditionalLock _l(mStateLock,
807 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700808 if (!getHwComposer().hasCapability(
809 HWC2::Capability::PresentFenceIsNotReliable)) {
810 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
811 }
812 return NO_ERROR;
813}
814
Dominik Laskowski22488f62019-03-28 09:53:04 -0700815status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
816 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700817 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 return BAD_VALUE;
819 }
820
Dominik Laskowski22488f62019-03-28 09:53:04 -0700821 Mutex::Autolock lock(mStateLock);
822
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800823 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 if (!displayId) {
825 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700826 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827
Mathias Agopian8b736f12012-08-13 17:54:26 -0700828 // TODO: Not sure if display density should handled by SF any longer
829 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700832 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800833 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 }
836 return density;
837 }
838 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700839 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700840 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("ro.sf.lcd_density"); }
843 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700848 DisplayInfo info = DisplayInfo();
849
Dan Stoza9e56aa02015-11-02 13:00:03 -0800850 float xdpi = hwConfig->getDpiX();
851 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700853 info.w = hwConfig->getWidth();
854 info.h = hwConfig->getHeight();
855 // Default display viewport to display width and height
856 info.viewportW = info.w;
857 info.viewportH = info.h;
858
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800859 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 // The density of the device is provided by a build property
861 float density = Density::getBuildDensity() / 160.0f;
862 if (density == 0) {
863 // the build doesn't provide a density -- this is wrong!
864 // use xdpi instead
865 ALOGE("ro.sf.lcd_density must be defined as a build property");
866 density = xdpi / 160.0f;
867 }
868 if (Density::getEmuDensity()) {
869 // if "qemu.sf.lcd_density" is specified, it overrides everything
870 xdpi = ydpi = density = Density::getEmuDensity();
871 density /= 160.0f;
872 }
873 info.density = density;
874
875 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700876 const auto display = getDefaultDisplayDeviceLocked();
877 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700878
879 // This is for screenrecord
880 const Rect viewport = display->getViewport();
881 if (viewport.isValid()) {
882 info.viewportW = uint32_t(viewport.getWidth());
883 info.viewportH = uint32_t(viewport.getHeight());
884 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700885 } else {
886 // TODO: where should this value come from?
887 static const int TV_DENSITY = 213;
888 info.density = TV_DENSITY / 160.0f;
889 info.orientation = 0;
890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 info.xdpi = xdpi;
893 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700895 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
896 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
897 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800898
Andy McFadden91b2ca82014-06-13 14:04:23 -0700899 // This is how far in advance a buffer must be queued for
900 // presentation at a given time. If you want a buffer to appear
901 // on the screen at time N, you must submit the buffer before
902 // (N - presentationDeadline).
903 //
904 // Normally it's one full refresh period (to give SF a chance to
905 // latch the buffer), but this can be reduced by configuring a
906 // DispSync offset. Any additional delays introduced by the hardware
907 // composer or panel must be accounted for here.
908 //
909 // We add an additional 1ms to allow for processing time and
910 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700911 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700912
913 // All non-virtual displays are currently considered secure.
914 info.secure = true;
915
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800916 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700917 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800918 std::swap(info.w, info.h);
919 }
920
Michael Wright28f24d02016-07-12 13:30:53 -0700921 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700922 }
923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 return NO_ERROR;
925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
928 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return BAD_VALUE;
930 }
931
Ana Krulecc2870422019-01-29 19:00:58 -0800932 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700933 return NO_ERROR;
934}
935
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700936int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
937 const auto display = getDisplayDevice(displayToken);
938 if (!display) {
939 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800940 return BAD_VALUE;
941 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700944}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700945
Ady Abraham03b02dd2019-03-21 15:40:11 -0700946void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800948
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800950 // config twice. However event generation config might have changed so we need to update it
951 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800952 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700953 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
954 mDesiredActiveConfig = info;
955 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800956
957 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958 // This will trigger HWC refresh without resetting the idle timer.
959 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700960 // Start receiving vsync samples now, so that we can detect a period
961 // switch.
962 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700963 // As we called to set period, we will call to onRefreshRateChangeCompleted once
964 // DispSync model is locked.
965 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700966 mPhaseOffsets->setRefreshRateType(info.type);
967 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700968 mVsyncModulator.setPhaseOffsets(early, gl, late,
969 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800971 mDesiredActiveConfigChanged = true;
972 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700973
974 if (mRefreshRateOverlay) {
975 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
976 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977}
978
979status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
980 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800981
982 std::vector<int32_t> allowedConfig;
983 allowedConfig.push_back(mode);
984
985 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986}
987
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988void SurfaceFlinger::setActiveConfigInternal() {
989 ATRACE_CALL();
990
Dominik Laskowski22488f62019-03-28 09:53:04 -0700991 const auto display = getDefaultDisplayDeviceLocked();
992 if (!display) {
993 return;
994 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995
Dominik Laskowski22488f62019-03-28 09:53:04 -0700996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
997 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
998
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 display->setActiveConfig(mUpcomingActiveConfig.configId);
1000
Alec Mouri754c98a2019-03-18 18:53:42 -07001001 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001002 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001003 mVsyncModulator.setPhaseOffsets(early, gl, late,
1004 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001007 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001008 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1009 mUpcomingActiveConfig.configId);
1010 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011}
1012
Ady Abraham53852a52019-05-28 18:07:44 -07001013void SurfaceFlinger::desiredActiveConfigChangeDone() {
1014 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1015 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1016 mDesiredActiveConfigChanged = false;
1017 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1018
1019 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1020 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1021 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001022 mVsyncModulator.setPhaseOffsets(early, gl, late,
1023 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -07001024}
1025
Dominik Laskowski22488f62019-03-28 09:53:04 -07001026bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001027 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001029 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001031 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 return true;
1033 }
1034
1035 // We received the present fence from the HWC, so we assume it successfully updated
1036 // the config, hence we update SF.
1037 mCheckPendingFence = false;
1038 setActiveConfigInternal();
1039 }
1040
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001041 // Store the local variable to release the lock.
1042 ActiveConfigInfo desiredActiveConfig;
1043 {
1044 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 if (!mDesiredActiveConfigChanged) {
1046 return false;
1047 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001048 desiredActiveConfig = mDesiredActiveConfig;
1049 }
1050
Dominik Laskowski22488f62019-03-28 09:53:04 -07001051 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001052 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1053 // display is not valid or we are already in the requested mode
1054 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001055 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001057 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058
Ady Abraham838de062019-02-04 10:24:03 -08001059 // Desired active config was set, it is different than the config currently in use, however
1060 // allowed configs might have change by the time we process the refresh.
1061 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001062 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001063 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001064 return false;
1065 }
Alec Mouri7f015182019-07-11 13:56:22 -07001066
Ady Abrahamb838aed2019-02-12 15:30:16 -08001067 mUpcomingActiveConfig = desiredActiveConfig;
1068 const auto displayId = display->getId();
1069 LOG_ALWAYS_FATAL_IF(!displayId);
1070
1071 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1072 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1073
1074 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001075 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001076 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1081 Vector<ColorMode>* outColorModes) {
1082 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001083 return BAD_VALUE;
1084 }
1085
Peiyong Lina52f0292018-03-14 17:26:31 -07001086 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001087 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001088 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001089 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1090
1091 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1092 if (!displayId) {
1093 return NAME_NOT_FOUND;
1094 }
1095
Dominik Laskowski075d3172018-05-24 15:50:06 -07001096 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001097 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001098 }
Michael Wright28f24d02016-07-12 13:30:53 -07001099 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001100
1101 // If it's built-in display and the configuration claims it's not wide color capable,
1102 // filter out all wide color modes. The typical reason why this happens is that the
1103 // hardware is not good enough to support GPU composition of wide color, and thus the
1104 // OEMs choose to disable this capability.
1105 if (isInternalDisplay && !hasWideColorDisplay) {
1106 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1107 isWideColorMode);
1108 } else {
1109 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1110 }
Michael Wright28f24d02016-07-12 13:30:53 -07001111
1112 return NO_ERROR;
1113}
1114
Daniel Solomon42d04562019-01-20 21:03:19 -08001115status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1116 ui::DisplayPrimaries &primaries) {
1117 if (!displayToken) {
1118 return BAD_VALUE;
1119 }
1120
1121 // Currently we only support this API for a single internal display.
1122 if (getInternalDisplayToken() != displayToken) {
1123 return BAD_VALUE;
1124 }
1125
1126 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1127 return NO_ERROR;
1128}
1129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001130ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1131 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001132 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001133 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001134 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001135}
1136
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001138 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139 Vector<ColorMode> modes;
1140 getDisplayColorModes(displayToken, &modes);
1141 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1142 if (mode < ColorMode::NATIVE || !exists) {
1143 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1144 decodeColorMode(mode).c_str(), mode, displayToken.get());
1145 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001146 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001147 const auto display = getDisplayDevice(displayToken);
1148 if (!display) {
1149 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1150 decodeColorMode(mode).c_str(), mode, displayToken.get());
1151 } else if (display->isVirtual()) {
1152 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1153 decodeColorMode(mode).c_str(), mode);
1154 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001155 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1156 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157 }
1158 }));
1159
Michael Wright28f24d02016-07-12 13:30:53 -07001160 return NO_ERROR;
1161}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001162
Svetoslavd85084b2014-03-20 10:28:31 -07001163status_t SurfaceFlinger::clearAnimationFrameStats() {
1164 Mutex::Autolock _l(mStateLock);
1165 mAnimFrameTracker.clearStats();
1166 return NO_ERROR;
1167}
1168
1169status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1170 Mutex::Autolock _l(mStateLock);
1171 mAnimFrameTracker.getStats(outStats);
1172 return NO_ERROR;
1173}
1174
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001175status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1176 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001177 Mutex::Autolock _l(mStateLock);
1178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001179 const auto display = getDisplayDeviceLocked(displayToken);
1180 if (!display) {
1181 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001182 return BAD_VALUE;
1183 }
1184
Peiyong Linfb069302018-04-25 14:34:31 -07001185 // At this point the DisplayDeivce should already be set up,
1186 // meaning the luminance information is already queried from
1187 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001188 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001189 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1190 capabilities.getDesiredMaxLuminance(),
1191 capabilities.getDesiredMaxAverageLuminance(),
1192 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001193
1194 return NO_ERROR;
1195}
1196
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001197status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1198 ui::PixelFormat* outFormat,
1199 ui::Dataspace* outDataspace,
1200 uint8_t* outComponentMask) const {
1201 if (!outFormat || !outDataspace || !outComponentMask) {
1202 return BAD_VALUE;
1203 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001204 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001205 if (!display || !display->getId()) {
1206 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1207 return BAD_VALUE;
1208 }
1209 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1210 outDataspace, outComponentMask);
1211}
1212
Kevin DuBois74e53772018-11-19 10:52:38 -08001213status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1214 bool enable, uint8_t componentMask,
1215 uint64_t maxFrames) const {
1216 const auto display = getDisplayDevice(displayToken);
1217 if (!display || !display->getId()) {
1218 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1219 return BAD_VALUE;
1220 }
1221
1222 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1223 componentMask, maxFrames);
1224}
1225
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001226status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1227 uint64_t maxFrames, uint64_t timestamp,
1228 DisplayedFrameStats* outStats) const {
1229 const auto display = getDisplayDevice(displayToken);
1230 if (!display || !display->getId()) {
1231 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1232 return BAD_VALUE;
1233 }
1234
1235 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1236 outStats);
1237}
1238
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001239status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1240 if (!outSupported) {
1241 return BAD_VALUE;
1242 }
1243 *outSupported = getRenderEngine().supportsProtectedContent();
1244 return NO_ERROR;
1245}
1246
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001247status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1248 bool* outIsWideColorDisplay) const {
1249 if (!displayToken || !outIsWideColorDisplay) {
1250 return BAD_VALUE;
1251 }
1252 Mutex::Autolock _l(mStateLock);
1253 const auto display = getDisplayDeviceLocked(displayToken);
1254 if (!display) {
1255 return BAD_VALUE;
1256 }
Peiyong Linff84a152019-05-17 18:36:19 -07001257
1258 // Use hasWideColorDisplay to override built-in display.
1259 const auto displayId = display->getId();
1260 if (displayId && displayId == getInternalDisplayIdLocked()) {
1261 *outIsWideColorDisplay = hasWideColorDisplay;
1262 return NO_ERROR;
1263 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001264 *outIsWideColorDisplay = display->hasWideColorGamut();
1265 return NO_ERROR;
1266}
1267
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001268status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001269 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001270 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001271
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 if (mInjectVSyncs == enable) {
1273 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001274 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275
Ana Krulecc2870422019-01-29 19:00:58 -08001276 auto resyncCallback =
1277 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001278
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001279 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001280 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001281 if (enable) {
1282 ALOGV("VSync Injections enabled");
1283 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001284 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001285 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001286 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001287 impl::EventThread::InterceptVSyncsCallback(),
1288 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001289 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001290 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001291 } else {
1292 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001293 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1294 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001295 }
1296
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001297 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001298 }));
1299
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001300 return NO_ERROR;
1301}
1302
1303status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001304 Mutex::Autolock _l(mStateLock);
1305
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001306 if (!mInjectVSyncs) {
1307 ALOGE("VSync Injections not enabled");
1308 return BAD_VALUE;
1309 }
1310 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1311 ALOGV("Injecting VSync inside SurfaceFlinger");
1312 mVSyncInjector->onInjectSyncEvent(when);
1313 }
1314 return NO_ERROR;
1315}
1316
Lloyd Pique755e3192018-01-31 16:46:15 -08001317status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1318 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001319 // Try to acquire a lock for 1s, fail gracefully
1320 const status_t err = mStateLock.timedLock(s2ns(1));
1321 const bool locked = (err == NO_ERROR);
1322 if (!locked) {
1323 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1324 return TIMED_OUT;
1325 }
1326
1327 outLayers->clear();
1328 mCurrentState.traverseInZOrder([&](Layer* layer) {
1329 outLayers->push_back(layer->getLayerDebugInfo());
1330 });
1331
1332 mStateLock.unlock();
1333 return NO_ERROR;
1334}
1335
Peiyong Linc6780972018-10-28 15:24:08 -07001336status_t SurfaceFlinger::getCompositionPreference(
1337 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1338 Dataspace* outWideColorGamutDataspace,
1339 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001340 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001341 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001342 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001343 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001344 return NO_ERROR;
1345}
1346
Dan Stozaec460082018-12-17 15:35:09 -08001347status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1348 const sp<IBinder>& stopLayerHandle,
1349 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001350 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001351 return BAD_VALUE;
1352 }
1353 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001354 return NO_ERROR;
1355}
1356
Dan Stozaec460082018-12-17 15:35:09 -08001357status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001358 if (!listener) {
1359 return BAD_VALUE;
1360 }
Dan Stozaec460082018-12-17 15:35:09 -08001361 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001362 return NO_ERROR;
1363}
Dan Gittik57e63c52019-01-18 16:37:54 +00001364
1365status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1366 bool* outSupport) const {
1367 if (!displayToken || !outSupport) {
1368 return BAD_VALUE;
1369 }
1370 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1371 if (!displayId) {
1372 return NAME_NOT_FOUND;
1373 }
1374 *outSupport =
1375 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1376 return NO_ERROR;
1377}
1378
1379status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1380 float brightness) const {
1381 if (!displayToken) {
1382 return BAD_VALUE;
1383 }
1384 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1385 if (!displayId) {
1386 return NAME_NOT_FOUND;
1387 }
1388 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1389}
1390
Ady Abraham8532d012019-05-08 14:50:56 -07001391status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1392 PowerHint powerHint = static_cast<PowerHint>(hintId);
1393
1394 if (powerHint == PowerHint::INTERACTION) {
1395 mScheduler->notifyTouchEvent();
1396 }
1397
1398 return NO_ERROR;
1399}
1400
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001401// ----------------------------------------------------------------------------
1402
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001403sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001404 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001405 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001406 Mutex::Autolock lock(mStateLock);
1407 return getVsyncPeriod();
1408 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001409
Ana Krulecc2870422019-01-29 19:00:58 -08001410 const auto& handle =
1411 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001412
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001413 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1414 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001415}
1416
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001417// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001418
1419void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001420 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001421}
1422
1423void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001424 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001425 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426}
1427
1428void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001429 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001430 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431}
1432
1433void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001434 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001435 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001436}
1437
1438status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001439 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001440 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001441}
1442
1443status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001444 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001445 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001446 if (res == NO_ERROR) {
1447 msg->wait();
1448 }
1449 return res;
1450}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001451
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001452void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001453 do {
1454 waitForEvent();
1455 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001456}
1457
Dominik Laskowski83b88212018-12-11 13:34:06 -08001458nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001459 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001460 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1461 return 0;
1462 }
1463
1464 const auto config = getHwComposer().getActiveConfig(*displayId);
1465 return config ? config->getVsyncPeriod() : 0;
1466}
1467
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001468void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1469 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001470 ATRACE_NAME("SF onVsync");
1471
Steven Thomas3cfac282017-02-06 12:29:30 -08001472 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001474 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 return;
1476 }
1477
Dominik Laskowski075d3172018-05-24 15:50:06 -07001478 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001479 return;
1480 }
1481
Dominik Laskowski075d3172018-05-24 15:50:06 -07001482 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001483 // For now, we don't do anything with external display vsyncs.
1484 return;
1485 }
1486
Alec Mourif8e689c2019-05-20 18:32:22 -07001487 bool periodFlushed = false;
1488 mScheduler->addResyncSample(timestamp, &periodFlushed);
1489 if (periodFlushed) {
1490 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001491 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001492}
1493
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001494void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001495 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1496 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001497}
1498
Ady Abraham261614e2019-07-10 17:53:12 -07001499bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001500 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001501}
1502
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001503void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001504 const auto display = getDefaultDisplayDeviceLocked();
1505 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001506 return;
1507 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001508 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001509
Ana Krulec7d1d6832018-12-27 11:10:09 -08001510 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001511 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001512 if (!refreshRateConfig) {
1513 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001514 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001515 }
Ady Abraham1902d072019-03-01 17:18:59 -08001516
Alec Mouri0a1cc962019-03-14 12:33:02 -07001517 const int desiredConfigId = refreshRateConfig->configId;
1518
Dominik Laskowski22488f62019-03-28 09:53:04 -07001519 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001520 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1521 return;
1522 }
1523
Dominik Laskowski22488f62019-03-28 09:53:04 -07001524 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001525}
1526
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001527void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001528 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001529 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001530 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001531
Lloyd Piqueba04e622017-12-14 17:11:26 -08001532 // Ignore events that do not have the right sequenceId.
1533 if (sequenceId != getBE().mComposerSequenceId) {
1534 return;
1535 }
1536
Steven Thomasb02664d2017-07-26 18:48:28 -07001537 // Only lock if we're not on the main thread. This function is normally
1538 // called on a hwbinder thread, but for the primary display it's called on
1539 // the main thread with the state lock already held, so don't attempt to
1540 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001541 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001542
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001543 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001544
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001545 if (std::this_thread::get_id() == mMainThreadId) {
1546 // Process all pending hot plug events immediately if we are on the main thread.
1547 processDisplayHotplugEventsLocked();
1548 }
1549
Lloyd Piqueba04e622017-12-14 17:11:26 -08001550 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001551}
1552
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001553void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001554 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001555 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001556 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001557 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001558 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001559}
1560
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001561void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001562 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001563
1564 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1565 // display power state.
1566 postMessageAsync(new LambdaMessage(
1567 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1568}
1569
1570void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1571 ATRACE_CALL();
1572
Ady Abraham27c70212019-06-11 10:52:26 -07001573 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1574
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001575 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001576 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1577 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001578 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001579 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001580 }
Mathias Agopian86303202012-07-24 22:46:10 -07001581}
1582
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001583// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001584void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001585 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001586 // Clear the drawing state so that the logic inside of
1587 // handleTransactionLocked will fire. It will determine the delta between
1588 // mCurrentState and mDrawingState and re-apply all changes when we make the
1589 // transition.
1590 mDrawingState.displays.clear();
1591 mDisplays.clear();
1592}
1593
Steven Thomas050b2c82017-03-06 11:45:16 -08001594void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001595 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001596 if (!mVrFlinger)
1597 return;
1598 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001599 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001600 return;
1601 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001602
Lloyd Pique441d5042018-10-18 16:49:51 -07001603 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001604 ALOGE("Vr flinger is only supported for remote hardware composer"
1605 " service connections. Ignoring request to transition to vr"
1606 " flinger.");
1607 mVrFlingerRequestsDisplay = false;
1608 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001609 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001610
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001611 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001612
Steven Thomas0123ac62018-07-12 11:32:34 -07001613 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001614 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001615
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001616 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001617
1618 // Clear out all the output layers from the composition engine for all
1619 // displays before destroying the hardware composer interface. This ensures
1620 // any HWC layers are destroyed through that interface before it becomes
1621 // invalid.
1622 for (const auto& [token, displayDevice] : mDisplays) {
1623 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1624 compositionengine::Output::OutputLayers());
1625 }
1626
Steven Thomas0123ac62018-07-12 11:32:34 -07001627 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1628 // called below. Clear the reference now so we don't accidentally use it
1629 // later.
1630 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001631
Steven Thomasb02664d2017-07-26 18:48:28 -07001632 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001633 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001634 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001635
Steven Thomasb02664d2017-07-26 18:48:28 -07001636 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001637 // Delete the current instance before creating the new one
1638 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1639 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1640 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1641 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001642
Lloyd Pique441d5042018-10-18 16:49:51 -07001643 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001644 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001645
1646 if (vrFlingerRequestsDisplay) {
1647 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001648 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001649
1650 mVisibleRegionsDirty = true;
1651 invalidateHwcGeometry();
1652
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001653 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001654 display = getDefaultDisplayDeviceLocked();
1655 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001656 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001657
Steven Thomasb02664d2017-07-26 18:48:28 -07001658 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001659 const nsecs_t vsyncPeriod = getVsyncPeriod();
1660 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001661
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001662 // The present fences returned from vr_hwc are not an accurate
1663 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001664 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001665
Steven Thomasb02664d2017-07-26 18:48:28 -07001666 // Use phase of 0 since phase is not known.
1667 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001668 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001669 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001670
Ana Krulecc2870422019-01-29 19:00:58 -08001671 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001672
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001673 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001674 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001675}
1676
Ady Abrahambe0f9482019-04-24 15:41:53 -07001677bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1678 // We are storing the last 2 present fences. If sf's phase offset is to be
1679 // woken up before the actual vsync but targeting the next vsync, we need to check
1680 // fence N-2
1681 const sp<Fence>& fence =
1682 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1683 ? mPreviousPresentFences[0]
1684 : mPreviousPresentFences[1];
1685
1686 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1687}
1688
Alec Mouriaa614192019-06-06 13:28:34 -07001689nsecs_t SurfaceFlinger::getExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
1690 DisplayStatInfo stats;
1691 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001692 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001693 // Inflate the expected present time if we're targetting the next vsync.
1694 const nsecs_t correctedTime =
1695 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1696 ? presentTime
1697 : presentTime + stats.vsyncPeriod;
1698 return correctedTime;
1699}
1700
Dominik Laskowski22488f62019-03-28 09:53:04 -07001701void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001702 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001703 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001704 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001705 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001706 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1707 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1708 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1709 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1710 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1711 if (frameMissed) {
1712 mFrameMissedCount++;
1713 mTimeStats->incrementMissedFrames();
1714 }
1715
Alec Mouri40189b02019-03-05 15:07:54 -08001716 if (hwcFrameMissed) {
1717 mHwcFrameMissedCount++;
1718 }
1719
1720 if (gpuFrameMissed) {
1721 mGpuFrameMissedCount++;
1722 }
1723
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001724 if (mUseSmart90ForVideo) {
1725 // This call is made each time SF wakes up and creates a new frame. It is part
1726 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001727 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001728 }
1729
Ady Abrahamb838aed2019-02-12 15:30:16 -08001730 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001731 break;
1732 }
1733
Alec Mourife3dc942019-02-12 14:19:18 -08001734 // For now, only propagate backpressure when missing a hwc frame.
Alec Mourib0f45822019-05-06 11:01:35 -07001735 if (hwcFrameMissed && !gpuFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001736 if (mPropagateBackpressure) {
1737 signalLayerUpdate();
1738 break;
1739 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001740 }
Dan Stoza50182882016-07-08 12:02:20 -07001741
Steven Thomas050b2c82017-03-06 11:45:16 -08001742 // Now that we're going to make it to the handleMessageTransaction()
1743 // call below it's safe to call updateVrFlinger(), which will
1744 // potentially trigger a display handoff.
1745 updateVrFlinger();
1746
Dan Stoza6b9454d2014-11-07 16:00:59 -08001747 bool refreshNeeded = handleMessageTransaction();
1748 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001749
1750 updateCursorAsync();
1751 updateInputFlinger();
1752
Dan Stoza58784442014-12-02 16:58:17 -08001753 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001754 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001755 // Signal a refresh if a transaction modified the window state,
1756 // a new buffer was latched, or if HWC has requested a full
1757 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001758 signalRefresh();
1759 }
1760 break;
1761 }
1762 case MessageQueue::REFRESH: {
1763 handleMessageRefresh();
1764 break;
1765 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001766 }
1767}
1768
Dan Stoza6b9454d2014-11-07 16:00:59 -08001769bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001770 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001771 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001772
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001773 bool flushedATransaction = flushTransactionQueues();
1774
1775 bool runHandleTransaction = transactionFlags &&
1776 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1777
1778 if (runHandleTransaction) {
1779 handleTransaction(eTransactionMask);
1780 } else {
1781 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001782 }
1783
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001784 if (transactionFlushNeeded()) {
1785 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001786 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001787
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001788 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001789}
1790
Mathias Agopian4fec8732012-06-29 14:12:52 -07001791void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001792 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001793
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001794 mRefreshPending = false;
1795
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001796 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001797 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001798 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001799 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001800 for (const auto& [token, display] : mDisplays) {
1801 beginFrame(display);
1802 prepareFrame(display);
1803 doDebugFlashRegions(display, repaintEverything);
1804 doComposition(display, repaintEverything);
1805 }
1806
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001807 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001808
1809 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001810 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001811
Dan Stozabfbffeb2016-07-21 14:49:33 -07001812 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001813 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001814 for (const auto& [token, displayDevice] : mDisplays) {
1815 auto display = displayDevice->getCompositionDisplay();
1816 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001817 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001818 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001819 mHadDeviceComposition =
1820 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001821 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001822
Jorim Jaggi90535212018-05-23 23:44:06 +02001823 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001824
David Sodman7e4ae112018-02-09 15:02:28 -08001825 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001826 if (mVisibleRegionsDirty) {
1827 mVisibleRegionsDirty = false;
1828 if (mTracingEnabled) {
1829 mTracing.notify("visibleRegionsDirty");
1830 }
1831 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001833
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834
1835bool SurfaceFlinger::handleMessageInvalidate() {
1836 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001837 bool refreshNeeded = handlePageFlip();
1838
Vishnu Nair4351ad52019-02-11 14:13:02 -08001839 if (mVisibleRegionsDirty) {
1840 computeLayerBounds();
1841 }
1842
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001843 for (auto& layer : mLayersPendingRefresh) {
1844 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001845 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001846 invalidateLayerStack(layer, visibleReg);
1847 }
1848 mLayersPendingRefresh.clear();
1849 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001850}
1851
David Sodman79bba0e2018-08-05 18:07:49 -07001852void SurfaceFlinger::calculateWorkingSet() {
1853 ATRACE_CALL();
1854 ALOGV(__FUNCTION__);
1855
David Sodman79bba0e2018-08-05 18:07:49 -07001856 // build the h/w work list
1857 if (CC_UNLIKELY(mGeometryInvalid)) {
1858 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 for (const auto& [token, displayDevice] : mDisplays) {
1860 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001861
Lloyd Piquea83776c2019-01-29 18:42:32 -08001862 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001863
Lloyd Piquea83776c2019-01-29 18:42:32 -08001864 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1865 auto& compositionState = layer->editState();
1866 compositionState.forceClientComposition = false;
1867 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1868 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001869 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001870
Lloyd Piquea83776c2019-01-29 18:42:32 -08001871 // The output Z order is set here based on a simple counter.
1872 compositionState.z = zOrder++;
1873
1874 // Update the display independent composition state. This goes
1875 // to the general composition layer state structure.
1876 // TODO: Do this once per compositionengine::CompositionLayer.
1877 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1878 true);
1879
1880 // Recalculate the geometry state of the output layer.
1881 layer->updateCompositionState(true);
1882
1883 // Write the updated geometry state to the HWC
1884 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001885 }
1886 }
1887 }
1888
1889 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001890 for (const auto& [token, displayDevice] : mDisplays) {
1891 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001892 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001893 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001894 continue;
1895 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001896 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001897
1898 if (mDrawingState.colorMatrixChanged) {
1899 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001900 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001901 Dataspace targetDataspace = Dataspace::UNKNOWN;
1902 if (useColorManagement) {
1903 ColorMode colorMode;
1904 RenderIntent renderIntent;
1905 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1906 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001907
1908 if (isHdrColorMode(colorMode)) {
1909 targetDataspace = Dataspace::UNKNOWN;
1910 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1911 targetDataspace = mColorSpaceAgnosticDataspace;
1912 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001913 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001914
Lloyd Pique32cbe282018-10-19 13:09:22 -07001915 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001916 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001917 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001918 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1919 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001920 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001921 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001922 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1923 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001924 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001925 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001926 }
1927
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001928 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001929 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001930 }
1931
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001932 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001933 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001934 layer->setCompositionType(displayDevice,
1935 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001936 continue;
1937 }
1938
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001940 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001941 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001942 }
1943 }
1944
1945 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001946
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001947 for (const auto& [token, displayDevice] : mDisplays) {
1948 auto display = displayDevice->getCompositionDisplay();
1949 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001950 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1951 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1952 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001953 }
1954 }
David Sodman79bba0e2018-08-05 18:07:49 -07001955}
1956
Lloyd Pique32cbe282018-10-19 13:09:22 -07001957void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1958 bool repaintEverything) {
1959 auto display = displayDevice->getCompositionDisplay();
1960 const auto& displayState = display->getState();
1961
Mathias Agopiancd60f992012-08-16 16:28:27 -07001962 // is debugging enabled
1963 if (CC_LIKELY(!mDebugRegion))
1964 return;
1965
Lloyd Pique32cbe282018-10-19 13:09:22 -07001966 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001967 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001968 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001969 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001970 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001971 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001972 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001974 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001975 }
1976 }
1977
Lloyd Pique32cbe282018-10-19 13:09:22 -07001978 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979
1980 if (mDebugRegion > 1) {
1981 usleep(mDebugRegion * 1000);
1982 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001983
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001985}
1986
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001987void SurfaceFlinger::logLayerStats() {
1988 ATRACE_CALL();
1989 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001990 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001991 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001992 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001993 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001994 }
1995 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001996
1997 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001998 }
1999}
2000
David Sodman2b406362017-12-15 13:33:47 -08002001void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002003 ATRACE_CALL();
2004 ALOGV("preComposition");
2005
David Sodman2b406362017-12-15 13:33:47 -08002006 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2007
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002009 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002010 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011 needExtraInvalidate = true;
2012 }
Robert Carr2047fae2016-11-28 14:09:09 -08002013 });
2014
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015 if (needExtraInvalidate) {
2016 signalLayerUpdate();
2017 }
2018}
2019
Ana Krulece588e312018-09-18 12:32:24 -07002020void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2021 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002022 // Update queue of past composite+present times and determine the
2023 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002024 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002025 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002026 while (!getBE().mCompositePresentTimes.empty()) {
2027 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028 // Cached values should have been updated before calling this method,
2029 // which helps avoid duplicate syscalls.
2030 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2031 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2032 break;
2033 }
2034 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002035 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036 }
2037
2038 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002039 while (getBE().mCompositePresentTimes.size() > 16) {
2040 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041 }
2042
Ana Krulece588e312018-09-18 12:32:24 -07002043 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002044}
2045
Ana Krulece588e312018-09-18 12:32:24 -07002046void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2047 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002048 // Integer division and modulo round toward 0 not -inf, so we need to
2049 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002050 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2051 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2052 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053
Ana Krulec757f63a2019-01-25 10:46:18 -08002054 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002055 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002056 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002057 }
2058
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002059 // Snap the latency to a value that removes scheduling jitter from the
2060 // composition and present times, which often have >1ms of jitter.
2061 // Reducing jitter is important if an app attempts to extrapolate
2062 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002063 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002065 nsecs_t bias = stats.vsyncPeriod / 2;
2066 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2067 nsecs_t snappedCompositeToPresentLatency =
2068 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069
David Sodman99974d22017-11-28 12:04:33 -08002070 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002071 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2072 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002073 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002074}
2075
David Sodman2b406362017-12-15 13:33:47 -08002076void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002077{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 ATRACE_CALL();
2079 ALOGV("postComposition");
2080
Brian Anderson3546a3f2016-07-14 11:51:14 -07002081 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002082 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002083 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002084 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002085 }
2086
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002087 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002088 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002089
David Sodman73beded2017-11-15 11:56:06 -08002090 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002091 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002092 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002093 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002094 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2095 ->getRenderSurface()
2096 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002097 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002098 } else {
2099 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2100 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002101
David Sodman73beded2017-11-15 11:56:06 -08002102 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002103 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2104 mPreviousPresentFences[0] = displayDevice
2105 ? getHwComposer().getPresentFence(*displayDevice->getId())
2106 : Fence::NO_FENCE;
2107 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002108 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002109
Ana Krulece588e312018-09-18 12:32:24 -07002110 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002111 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002112
David Sodman2b406362017-12-15 13:33:47 -08002113 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002114 // when we started doing work for this frame, but that should be okay
2115 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002116 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002117 CompositorTiming compositorTiming;
2118 {
David Sodman99974d22017-11-28 12:04:33 -08002119 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2120 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002121 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002122
Robert Carr2047fae2016-11-28 14:09:09 -08002123 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002124 bool frameLatched =
2125 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2126 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002127 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002128 recordBufferingStats(layer->getName().string(),
2129 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002130 }
Robert Carr2047fae2016-11-28 14:09:09 -08002131 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002132
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002133 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002134 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002135 }
2136
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002137 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002138 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2139 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002140 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002141 }
2142 }
2143
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002144 if (mAnimCompositionPending) {
2145 mAnimCompositionPending = false;
2146
Brian Anderson4e606e32017-03-16 15:34:57 -07002147 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002148 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002149 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002150 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002151 // The HWC doesn't support present fences, so use the refresh
2152 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002153 const nsecs_t presentTime =
2154 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002155 mAnimFrameTracker.setActualPresentTime(presentTime);
2156 }
2157 mAnimFrameTracker.advanceFrame();
2158 }
Dan Stozab90cf072015-03-05 11:05:59 -08002159
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002160 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002161 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002162 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002163 }
2164
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002165 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002166
Lloyd Pique32cbe282018-10-19 13:09:22 -07002167 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2168 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002169 return;
2170 }
2171
2172 nsecs_t currentTime = systemTime();
2173 if (mHasPoweredOff) {
2174 mHasPoweredOff = false;
2175 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002176 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002177 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002178 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2179 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002180 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002181 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002182 }
David Sodman4a36e932017-11-07 14:29:47 -08002183 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002184 }
David Sodman4a36e932017-11-07 14:29:47 -08002185 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002186
2187 {
2188 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002189 if (mTexturePool.size() < mTexturePoolSize) {
2190 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002191 const size_t offset = mTexturePool.size();
2192 mTexturePool.resize(mTexturePoolSize);
2193 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2194 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002195 } else if (mTexturePool.size() > mTexturePoolSize) {
2196 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2197 const size_t offset = mTexturePoolSize;
2198 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2199 mTexturePool.resize(mTexturePoolSize);
2200 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002201 }
2202 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002203
Ady Abrahambe0f9482019-04-24 15:41:53 -07002204 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002205 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002206
Kevin DuBois413287f2019-02-25 08:46:47 -08002207 if (mLumaSampling && mRegionSamplingThread) {
2208 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002209 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002210
2211 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2212 // side-effect of getTotalSize(), so we check that again here
2213 if (ATRACE_ENABLED()) {
2214 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2215 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002216}
2217
Vishnu Nair4351ad52019-02-11 14:13:02 -08002218void SurfaceFlinger::computeLayerBounds() {
2219 for (const auto& pair : mDisplays) {
2220 const auto& displayDevice = pair.second;
2221 const auto display = displayDevice->getCompositionDisplay();
2222 for (const auto& layer : mDrawingState.layersSortedByZ) {
2223 // only consider the layers on the given layer stack
2224 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002225 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002226 }
2227
2228 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2229 }
2230 }
2231}
2232
Mathias Agopiancd60f992012-08-16 16:28:27 -07002233void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 ATRACE_CALL();
2235 ALOGV("rebuildLayerStacks");
2236
Mathias Agopiancd60f992012-08-16 16:28:27 -07002237 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002238 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002239 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002241
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002242 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002243 const auto& displayDevice = pair.second;
2244 auto display = displayDevice->getCompositionDisplay();
2245 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002246 Region opaqueRegion;
2247 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002248 compositionengine::Output::OutputLayers layersSortedByZ;
2249 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002250 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002251 const ui::Transform& tr = displayState.transform;
2252 const Rect bounds = displayState.bounds;
2253 if (displayState.isEnabled) {
2254 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002255
Jeff Sharkey76488112017-02-27 14:15:18 -07002256 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002257 auto compositionLayer = layer->getCompositionLayer();
2258 if (compositionLayer == nullptr) {
2259 return;
2260 }
2261
Lloyd Pique32cbe282018-10-19 13:09:22 -07002262 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002263 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2264 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2265
Lloyd Pique07e33212018-12-18 16:33:37 -08002266 bool needsOutputLayer = false;
2267
Lloyd Piqueef36b002019-01-23 17:52:04 -08002268 if (display->belongsInOutput(layer->getLayerStack(),
2269 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002270 Region drawRegion(tr.transform(
2271 layer->visibleNonTransparentRegion));
2272 drawRegion.andSelf(bounds);
2273 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002274 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002275 }
Chia-I Wu83806892017-11-16 10:50:20 -08002276 }
2277
Lloyd Pique07e33212018-12-18 16:33:37 -08002278 if (needsOutputLayer) {
2279 layersSortedByZ.emplace_back(
2280 display->getOrCreateOutputLayer(displayId, compositionLayer,
2281 layerFE));
2282 deprecated_layersSortedByZ.add(layer);
2283
2284 auto& outputLayerState = layersSortedByZ.back()->editState();
2285 outputLayerState.visibleRegion =
2286 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2287 } else if (displayId) {
2288 // For layers that are being removed from a HWC display,
2289 // and that have queued frames, add them to a a list of
2290 // released layers so we can properly set a fence.
2291 bool hasExistingOutputLayer =
2292 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2293 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2294 mLayersWithQueuedFrames.cend(),
2295 layer) != mLayersWithQueuedFrames.cend();
2296
2297 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002298 layersNeedingFences.add(layer);
2299 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002300 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002301 });
2302 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002303
2304 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2305
2306 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002307 displayDevice->setLayersNeedingFences(layersNeedingFences);
2308
2309 Region undefinedRegion{bounds};
2310 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2311
2312 display->editState().undefinedRegion = undefinedRegion;
2313 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002314 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002315 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002316}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002317
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002319// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002320// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002322// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002323// The returned HDR data space is one of
2324// - Dataspace::UNKNOWN
2325// - Dataspace::BT2020_HLG
2326// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002327Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2328 Dataspace* outHdrDataSpace,
2329 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002330 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 *outHdrDataSpace = Dataspace::UNKNOWN;
2332
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002334 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 case Dataspace::V0_SCRGB:
2336 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002337 case Dataspace::BT2020:
2338 case Dataspace::BT2020_ITU:
2339 case Dataspace::BT2020_LINEAR:
2340 case Dataspace::DISPLAY_BT2020:
2341 bestDataSpace = Dataspace::DISPLAY_BT2020;
2342 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002343 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002344 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002345 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346 case Dataspace::BT2020_PQ:
2347 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002348 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002349 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002350 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002351 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002352 case Dataspace::BT2020_HLG:
2353 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002354 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002355 // When there's mixed PQ content and HLG content, we set the HDR
2356 // data space to be BT2020_PQ and convert HLG to PQ.
2357 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2358 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002359 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002360 break;
2361 default:
2362 break;
2363 }
Romain Guy54f154a2017-10-24 21:40:32 +01002364 }
2365
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002367}
2368
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002369// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002370void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2371 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002372 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2373 *outMode = ColorMode::NATIVE;
2374 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002375 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002376 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002377 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002378
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002379 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002380 bool isHdrClientComposition = false;
2381 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002382
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002383 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2384
Peiyong Lina3ea5592019-02-10 14:45:00 -08002385 switch (mForceColorMode) {
2386 case ColorMode::SRGB:
2387 bestDataSpace = Dataspace::V0_SRGB;
2388 break;
2389 case ColorMode::DISPLAY_P3:
2390 bestDataSpace = Dataspace::DISPLAY_P3;
2391 break;
2392 default:
2393 break;
2394 }
2395
Peiyong Lindfde5112018-06-05 10:58:41 -07002396 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002397 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2398 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002399 if (isHdr) {
2400 bestDataSpace = hdrDataSpace;
2401 }
2402
Chia-I Wu0d711262018-05-21 15:19:35 -07002403 RenderIntent intent;
2404 switch (mDisplayColorSetting) {
2405 case DisplayColorSetting::MANAGED:
2406 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002407 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002408 break;
2409 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002410 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002411 break;
2412 default: // vendor display color setting
2413 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2414 break;
2415 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002416
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002417 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002418}
2419
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2421 auto display = displayDevice->getCompositionDisplay();
2422 const auto& displayState = display->getState();
2423
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002424 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2426 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002427
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428 // If nothing has changed (!dirty), don't recompose.
2429 // If something changed, but we don't currently have any visible layers,
2430 // and didn't when we last did a composition, then skip it this time.
2431 // The second rule does two things:
2432 // - When all layers are removed from a display, we'll emit one black
2433 // frame, then nothing more until we get new layers.
2434 // - When a display is created with a private layer stack, we won't
2435 // emit any black frames until a layer is added to the layer stack.
2436 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002437
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 const char flagPrefix[] = {'-', '+'};
2439 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2441 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2442 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2443 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002444
Lloyd Pique31cb2942018-10-19 17:23:03 -07002445 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002446
David Sodmanfa9b2af2017-12-24 13:28:59 -08002447 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002449 }
2450}
2451
Lloyd Pique32cbe282018-10-19 13:09:22 -07002452void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2453 auto display = displayDevice->getCompositionDisplay();
2454 const auto& displayState = display->getState();
2455
2456 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002457 return;
David Sodman2b406362017-12-15 13:33:47 -08002458 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002460 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002462 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002463}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002464
Lloyd Pique32cbe282018-10-19 13:09:22 -07002465void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002466 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002467 ALOGV("doComposition");
2468
Lloyd Pique32cbe282018-10-19 13:09:22 -07002469 auto display = displayDevice->getCompositionDisplay();
2470 const auto& displayState = display->getState();
2471
2472 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002473 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002474 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002475
David Sodmanfa9b2af2017-12-24 13:28:59 -08002476 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002477 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002478
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002480 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002481 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002482 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002483}
2484
David Sodmanfa9b2af2017-12-24 13:28:59 -08002485void SurfaceFlinger::postFrame()
2486{
2487 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002488 const auto display = getDefaultDisplayDeviceLocked();
2489 if (display && getHwComposer().isConnected(*display->getId())) {
2490 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002491 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2492 logFrameStats();
2493 }
2494 }
2495}
2496
Lloyd Pique32cbe282018-10-19 13:09:22 -07002497void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002498 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002500
Lloyd Pique32cbe282018-10-19 13:09:22 -07002501 auto display = displayDevice->getCompositionDisplay();
2502 const auto& displayState = display->getState();
2503 const auto displayId = display->getId();
2504
Lloyd Pique32cbe282018-10-19 13:09:22 -07002505 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002506 if (displayId) {
2507 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002508 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002509 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002510 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002511 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002512 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002513
Chia-I Wu7b549592017-11-15 09:14:57 -08002514 // The layer buffer from the previous frame (if any) is released
2515 // by HWC only when the release fence from this frame (if any) is
2516 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002517 if (layer->getState().hwc) {
2518 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002519 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002520 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2521 usedClientComposition =
2522 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002523 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002524
2525 // If the layer was client composited in the previous frame, we
2526 // need to merge with the previous client target acquire fence.
2527 // Since we do not track that, always merge with the current
2528 // client target acquire fence when it is available, even though
2529 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002530 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002531 releaseFence =
2532 Fence::merge("LayerRelease", releaseFence,
2533 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002534 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002535
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002536 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002537 }
Chia-I Wu83806892017-11-16 10:50:20 -08002538
2539 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002540 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002541 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002542 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002543 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002544 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002545 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002546 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002547 }
2548 }
2549
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550 if (displayId) {
2551 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002552 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554}
2555
Mathias Agopian87baae12012-07-31 12:38:26 -07002556void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557{
Mathias Agopian841cde52012-03-01 15:44:37 -08002558 ATRACE_CALL();
2559
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002560 // here we keep a copy of the drawing state (that is the state that's
2561 // going to be overwritten by handleTransactionLocked()) outside of
2562 // mStateLock so that the side-effects of the State assignment
2563 // don't happen with mStateLock held (which can cause deadlocks).
2564 State drawingState(mDrawingState);
2565
Mathias Agopianca4d3602011-05-19 15:38:14 -07002566 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002567 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568
Mathias Agopianca4d3602011-05-19 15:38:14 -07002569 // Here we're guaranteed that some transaction flags are set
2570 // so we can call handleTransactionLocked() unconditionally.
2571 // We call getTransactionFlags(), which will also clear the flags,
2572 // with mStateLock held to guarantee that mCurrentState won't change
2573 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002574
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002575 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002576 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002577 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002578
Mathias Agopianca4d3602011-05-19 15:38:14 -07002579 mDebugInTransaction = 0;
2580 invalidateHwcGeometry();
2581 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002582}
2583
Lloyd Piqueba04e622017-12-14 17:11:26 -08002584void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2585 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 const std::optional<DisplayIdentificationInfo> info =
2587 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002588
Dominik Laskowski075d3172018-05-24 15:50:06 -07002589 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590 continue;
2591 }
2592
Lloyd Piqueba04e622017-12-14 17:11:26 -08002593 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002595 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 mPhysicalDisplayTokens[info->id] = new BBinder();
2597 DisplayDeviceState state;
2598 state.displayId = info->id;
2599 state.isSecure = true; // All physical displays are currently considered secure.
2600 state.displayName = info->name;
2601 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2602 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002603 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002604 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002605 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2608 if (index >= 0) {
2609 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2610 mInterceptor->saveDisplayDeletion(state.sequenceId);
2611 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002612 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002614 }
2615
2616 processDisplayChangesLocked();
2617 }
2618
2619 mPendingHotplugEvents.clear();
2620}
2621
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002622void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002623 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2624 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002625}
2626
Lloyd Pique99d3da52018-01-22 17:48:03 -08002627sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002629 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 const sp<IGraphicBufferProducer>& producer) {
2631 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002632 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002633 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002634 creationArgs.isSecure = state.isSecure;
2635 creationArgs.displaySurface = dispSurface;
2636 creationArgs.hasWideColorGamut = false;
2637 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002638
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002639 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002640 creationArgs.isPrimary = isInternalDisplay;
2641
2642 if (useColorManagement && displayId) {
2643 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002645 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002646 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002648
Dominik Laskowski7e045462018-05-30 13:02:02 -07002649 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002650 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002651 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002652 }
tangrobin6753a022018-08-10 10:58:54 +08002653 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 if (displayId) {
2656 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002657 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002658 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002659 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002660
Lloyd Pique90c115d2018-09-18 21:39:42 -07002661 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002663 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665 // Make sure that composition can never be stalled by a virtual display
2666 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002667 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002668 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2670 }
2671
Dominik Laskowski075d3172018-05-24 15:50:06 -07002672 creationArgs.displayInstallOrientation =
2673 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002674
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002676 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677
Lloyd Pique90c115d2018-09-18 21:39:42 -07002678 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679
2680 if (maxFrameBufferAcquiredBuffers >= 3) {
2681 nativeWindowSurface->preallocateBuffers();
2682 }
2683
2684 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002685 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002686 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002687 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002688 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002690 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2691 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002692 if (!state.isVirtual()) {
2693 LOG_ALWAYS_FATAL_IF(!displayId);
2694 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002695 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002696
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002697 display->setLayerStack(state.layerStack);
2698 display->setProjection(state.orientation, state.viewport, state.frame);
2699 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002700
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702}
2703
Lloyd Pique347200f2017-12-14 17:00:15 -08002704void SurfaceFlinger::processDisplayChangesLocked() {
2705 // here we take advantage of Vector's copy-on-write semantics to
2706 // improve performance by skipping the transaction entirely when
2707 // know that the lists are identical
2708 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2709 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2710 if (!curr.isIdenticalTo(draw)) {
2711 mVisibleRegionsDirty = true;
2712 const size_t cc = curr.size();
2713 size_t dc = draw.size();
2714
2715 // find the displays that were removed
2716 // (ie: in drawing state but not in current state)
2717 // also handle displays that changed
2718 // (ie: displays that are in both lists)
2719 for (size_t i = 0; i < dc;) {
2720 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2721 if (j < 0) {
2722 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002723 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002724 // Save display ID before disconnecting.
2725 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002726 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002727
2728 if (!display->isVirtual()) {
2729 LOG_ALWAYS_FATAL_IF(!displayId);
2730 dispatchDisplayHotplugEvent(displayId->value, false);
2731 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002732 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002733
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002734 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 } else {
2736 // this display is in both lists. see if something changed.
2737 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002738 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002739 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2740 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2741 if (state_binder != draw_binder) {
2742 // changing the surface is like destroying and
2743 // recreating the DisplayDevice, so we just remove it
2744 // from the drawing state, so that it get re-added
2745 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002746 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002747 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002748 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002749 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 mDrawingState.displays.removeItemsAt(i);
2751 dc--;
2752 // at this point we must loop to the next item
2753 continue;
2754 }
2755
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002756 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002758 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 }
2760 if ((state.orientation != draw[i].orientation) ||
2761 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002762 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002763 }
2764 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002765 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002766 }
2767 }
2768 }
2769 ++i;
2770 }
2771
2772 // find displays that were added
2773 // (ie: in current state but not in drawing state)
2774 for (size_t i = 0; i < cc; i++) {
2775 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2776 const DisplayDeviceState& state(curr[i]);
2777
Lloyd Pique542307f2018-10-19 13:24:08 -07002778 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002779 sp<IGraphicBufferProducer> producer;
2780 sp<IGraphicBufferProducer> bqProducer;
2781 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002782 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002783
Dominik Laskowski075d3172018-05-24 15:50:06 -07002784 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002785 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 // Virtual displays without a surface are dormant:
2787 // they have external state (layer stack, projection,
2788 // etc.) but no internal state (i.e. a DisplayDevice).
2789 if (state.surface != nullptr) {
2790 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002791 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 int width = 0;
2793 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2794 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2795 int height = 0;
2796 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2797 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2798 int intFormat = 0;
2799 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2800 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002801 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002802
Dominik Laskowski075d3172018-05-24 15:50:06 -07002803 displayId =
2804 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002805 }
2806
2807 // TODO: Plumb requested format back up to consumer
2808
2809 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002810 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002811 bqProducer, bqConsumer,
2812 state.displayName);
2813
2814 dispSurface = vds;
2815 producer = vds;
2816 }
2817 } else {
2818 ALOGE_IF(state.surface != nullptr,
2819 "adding a supported display, but rendering "
2820 "surface is provided (%p), ignoring it",
2821 state.surface.get());
2822
Dominik Laskowski075d3172018-05-24 15:50:06 -07002823 displayId = state.displayId;
2824 LOG_ALWAYS_FATAL_IF(!displayId);
2825 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002826 producer = bqProducer;
2827 }
2828
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002829 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002830 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002831 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002832 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002833 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002834 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002835 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002836 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002837 }
2838 }
2839 }
2840 }
2841 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002842
2843 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002844}
2845
Mathias Agopian87baae12012-07-31 12:38:26 -07002846void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002847{
Dan Stoza7dde5992015-05-22 09:51:44 -07002848 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002849 mCurrentState.traverseInZOrder([](Layer* layer) {
2850 layer->notifyAvailableFrames();
2851 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002852
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853 /*
2854 * Traversal of the children
2855 * (perform the transaction for each of them if needed)
2856 */
2857
Marissa Wall06255332019-03-27 13:48:27 -07002858 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002859 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002860 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002861 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862
2863 const uint32_t flags = layer->doTransaction(0);
2864 if (flags & Layer::eVisibleRegion)
2865 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002866
2867 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002868 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002869 }
Robert Carr2047fae2016-11-28 14:09:09 -08002870 });
Marissa Wall06255332019-03-27 13:48:27 -07002871 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 }
2873
2874 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002875 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 */
2877
Mathias Agopiane57f2922012-08-09 16:29:12 -07002878 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002879 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002880 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002881 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002883 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002884 // The transform hint might have changed for some layers
2885 // (either because a display has changed, or because a layer
2886 // as changed).
2887 //
2888 // Walk through all the layers in currentLayers,
2889 // and update their transform hint.
2890 //
2891 // If a layer is visible only on a single display, then that
2892 // display is used to calculate the hint, otherwise we use the
2893 // default display.
2894 //
2895 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2896 // the hint is set before we acquire a buffer from the surface texture.
2897 //
2898 // NOTE: layer transactions have taken place already, so we use their
2899 // drawing state. However, SurfaceFlinger's own transaction has not
2900 // happened yet, so we must use the current state layer list
2901 // (soon to become the drawing state list).
2902 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002904 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002905 bool first = true;
2906 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002907 // NOTE: we rely on the fact that layers are sorted by
2908 // layerStack first (so we don't have to traverse the list
2909 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002911 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002912 currentlayerStack = layerStack;
2913 // figure out if this layerstack is mirrored
2914 // (more than one display) if so, pick the default display,
2915 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002916 hintDisplay = nullptr;
2917 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002918 if (display->getCompositionDisplay()
2919 ->belongsInOutput(layer->getLayerStack(),
2920 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002921 if (hintDisplay) {
2922 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002923 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002924 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002926 }
2927 }
2928 }
2929 }
Chet Haase91d25932013-04-11 15:24:55 -07002930
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002931 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002932 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2933 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002934
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002935 // could be null when this layer is using a layerStack
2936 // that is not visible on any display. Also can occur at
2937 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002938 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002939 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002940
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002941 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002942 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002943 if (hintDisplay) {
2944 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002945 }
Robert Carr2047fae2016-11-28 14:09:09 -08002946
2947 first = false;
2948 });
Mathias Agopian84300952012-11-21 16:02:13 -08002949 }
2950
2951
Mathias Agopian3559b072012-08-15 13:46:03 -07002952 /*
2953 * Perform our own transaction if needed
2954 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955
2956 if (mLayersAdded) {
2957 mLayersAdded = false;
2958 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002959 mVisibleRegionsDirty = true;
2960 }
2961
2962 // some layers might have been removed, so
2963 // we need to update the regions they're exposing.
2964 if (mLayersRemoved) {
2965 mLayersRemoved = false;
2966 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002967 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002968 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002969 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002970 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002971 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002972 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002973 }
Robert Carr2047fae2016-11-28 14:09:09 -08002974 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975 }
2976
Vishnu Nairec0ab382019-02-13 15:32:56 -08002977 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002979}
2980
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002981void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002982 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002983 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002984 return;
2985 }
2986
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002987 if (mVisibleRegionsDirty || mInputInfoChanged) {
2988 mInputInfoChanged = false;
2989 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002990 } else if (mInputWindowCommands.syncInputWindows) {
2991 // If the caller requested to sync input windows, but there are no
2992 // changes to input windows, notify immediately.
2993 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002994 }
2995
2996 executeInputWindowCommands();
2997}
2998
2999void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003000 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003001
3002 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3003 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003004 // When calculating the screen bounds we ignore the transparent region since it may
3005 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003006 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003007 }
3008 });
chaviw291d88a2019-02-14 10:33:58 -08003009
3010 mInputFlinger->setInputWindows(inputHandles,
3011 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3012 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003013}
3014
Vishnu Nairec0ab382019-02-13 15:32:56 -08003015void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003016 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003017 mPendingInputWindowCommands.clear();
3018}
3019
chaviwfbe5d9c2018-12-26 12:23:37 -08003020void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003021 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3022 if (transferTouchFocusCommand.fromToken != nullptr &&
3023 transferTouchFocusCommand.toToken != nullptr &&
3024 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3025 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3026 transferTouchFocusCommand.toToken);
3027 }
3028 }
3029
3030 mInputWindowCommands.clear();
3031}
3032
Riley Andrews03414a12014-07-01 14:22:59 -07003033void SurfaceFlinger::updateCursorAsync()
3034{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003035 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003036 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003037 continue;
3038 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003040 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3041 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003042 }
3043 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003044}
3045
chaviw61626f22018-11-15 16:26:27 -08003046void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3047 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003048 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003049 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003050 }
3051 layer->releasePendingBuffer(systemTime());
3052}
3053
Mathias Agopian4fec8732012-06-29 14:12:52 -07003054void SurfaceFlinger::commitTransaction()
3055{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003056 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003057 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003058 for (const auto& l : mLayersPendingRemoval) {
3059 recordBufferingStats(l->getName().string(),
3060 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003061
Lloyd Pique07e33212018-12-18 16:33:37 -08003062 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003063 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003064 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003065 }
chaviw74d90ad2019-04-26 14:45:26 -07003066
3067 // If the layer has been removed and has no parent, then it will not be reachable
3068 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3069 // ensure we can copy its current to drawing state.
3070 if (!l->getParent()) {
3071 mOffscreenLayers.emplace(l.get());
3072 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003073 }
3074 mLayersPendingRemoval.clear();
3075 }
3076
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003077 // If this transaction is part of a window animation then the next frame
3078 // we composite should be considered an animation as well.
3079 mAnimCompositionPending = mAnimTransactionPending;
3080
Nataniel Borges2b796da2019-02-15 13:32:18 -08003081 withTracingLock([&]() {
3082 mDrawingState = mCurrentState;
3083 // clear the "changed" flags in current state
3084 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003085
chaviw74d90ad2019-04-26 14:45:26 -07003086 mDrawingState.traverseInZOrder([&](Layer* layer) {
3087 layer->commitChildList();
3088
3089 // If the layer can be reached when traversing mDrawingState, then the layer is no
3090 // longer offscreen. Remove the layer from the offscreenLayer set.
3091 if (mOffscreenLayers.count(layer)) {
3092 mOffscreenLayers.erase(layer);
3093 }
3094 });
3095
3096 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003097 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003098
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003099 mTransactionPending = false;
3100 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003101 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003102}
3103
Nataniel Borges2b796da2019-02-15 13:32:18 -08003104void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3105 if (mTracingEnabledChanged) {
3106 mTracingEnabled = mTracing.isEnabled();
3107 mTracingEnabledChanged = false;
3108 }
3109
3110 // Synchronize with Tracing thread
3111 std::unique_lock<std::mutex> lock;
3112 if (mTracingEnabled) {
3113 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3114 }
3115
3116 lockedOperation();
3117
3118 // Synchronize with Tracing thread
3119 if (mTracingEnabled) {
3120 lock.unlock();
3121 }
3122}
3123
chaviw74d90ad2019-04-26 14:45:26 -07003124void SurfaceFlinger::commitOffscreenLayers() {
3125 for (Layer* offscreenLayer : mOffscreenLayers) {
3126 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3127 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3128 if (!trFlags) return;
3129
3130 layer->doTransaction(0);
3131 layer->commitChildList();
3132 });
3133 }
3134}
3135
Lloyd Pique32cbe282018-10-19 13:09:22 -07003136void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003137 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003138 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003139 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003140
Lloyd Pique32cbe282018-10-19 13:09:22 -07003141 auto display = displayDevice->getCompositionDisplay();
3142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003143 Region aboveOpaqueLayers;
3144 Region aboveCoveredLayers;
3145 Region dirty;
3146
Mathias Agopian87baae12012-07-31 12:38:26 -07003147 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148
Robert Carr2047fae2016-11-28 14:09:09 -08003149 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003150 // start with the whole surface at its current location
3151 const Layer::State& s(layer->getDrawingState());
3152
Jesse Hall01e29052013-02-19 16:13:35 -08003153 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003154 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003155 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003156 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003157
Mathias Agopianab028732010-03-16 16:41:46 -07003158 /*
3159 * opaqueRegion: area of a surface that is fully opaque.
3160 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003162
3163 /*
3164 * visibleRegion: area of a surface that is visible on screen
3165 * and not fully transparent. This is essentially the layer's
3166 * footprint minus the opaque regions above it.
3167 * Areas covered by a translucent surface are considered visible.
3168 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003170
3171 /*
3172 * coveredRegion: area of a surface that is covered by all
3173 * visible regions above it (which includes the translucent areas).
3174 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003175 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003176
Jesse Halla8026d22012-09-25 13:25:04 -07003177 /*
3178 * transparentRegion: area of a surface that is hinted to be completely
3179 * transparent. This is only used to tell when the layer has no visible
3180 * non-transparent regions and can be removed from the layer list. It
3181 * does not affect the visibleRegion of this layer or any layers
3182 * beneath it. The hint may not be correct if apps don't respect the
3183 * SurfaceView restrictions (which, sadly, some don't).
3184 */
3185 Region transparentRegion;
3186
Mathias Agopianab028732010-03-16 16:41:46 -07003187
3188 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003189 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003190 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003191 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003192
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003194 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003195 if (!visibleRegion.isEmpty()) {
3196 // Remove the transparent area from the visible region
3197 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003198 if (tr.preserveRects()) {
3199 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003200 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003201 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003202 // transformation too complex, can't do the
3203 // transparent region optimization.
3204 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003205 }
Mathias Agopianab028732010-03-16 16:41:46 -07003206 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003207
Mathias Agopianab028732010-03-16 16:41:46 -07003208 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003209 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003210 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003211 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003212 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003213 // the opaque region is the layer's footprint
3214 opaqueRegion = visibleRegion;
3215 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 }
3217 }
3218
Robert Carre5f4f692018-01-12 13:12:28 -08003219 if (visibleRegion.isEmpty()) {
3220 layer->clearVisibilityRegions();
3221 return;
3222 }
3223
Mathias Agopianab028732010-03-16 16:41:46 -07003224 // Clip the covered region to the visible region
3225 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3226
3227 // Update aboveCoveredLayers for next (lower) layer
3228 aboveCoveredLayers.orSelf(visibleRegion);
3229
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230 // subtract the opaque region covered by the layers above us
3231 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232
3233 // compute this layer's dirty region
3234 if (layer->contentDirty) {
3235 // we need to invalidate the whole region
3236 dirty = visibleRegion;
3237 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003238 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 layer->contentDirty = false;
3240 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003241 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003242 * the exposed region consists of two components:
3243 * 1) what's VISIBLE now and was COVERED before
3244 * 2) what's EXPOSED now less what was EXPOSED before
3245 *
3246 * note that (1) is conservative, we start with the whole
3247 * visible region but only keep what used to be covered by
3248 * something -- which mean it may have been exposed.
3249 *
3250 * (2) handles areas that were not covered by anything but got
3251 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003252 */
Mathias Agopianab028732010-03-16 16:41:46 -07003253 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003254 const Region oldVisibleRegion = layer->visibleRegion;
3255 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003256 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3257 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003258 }
3259 dirty.subtractSelf(aboveOpaqueLayers);
3260
3261 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003262 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263
Mathias Agopianab028732010-03-16 16:41:46 -07003264 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003266
Jesse Halla8026d22012-09-25 13:25:04 -07003267 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003268 layer->setVisibleRegion(visibleRegion);
3269 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003270 layer->setVisibleNonTransparentRegion(
3271 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003272 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273
Mathias Agopian87baae12012-07-31 12:38:26 -07003274 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275}
3276
Chia-I Wuab0c3192017-08-01 11:29:00 -07003277void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003278 for (const auto& [token, displayDevice] : mDisplays) {
3279 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003280 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003281 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003282 }
3283 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003284}
3285
Dan Stoza6b9454d2014-11-07 16:00:59 -08003286bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287{
Ady Abraham09bd3922019-04-08 10:44:56 -07003288 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003289 ALOGV("handlePageFlip");
3290
Brian Andersond6927fb2016-07-23 23:37:30 -07003291 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003292
Mathias Agopian4fec8732012-06-29 14:12:52 -07003293 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003294 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003295 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003296
3297 // Store the set of layers that need updates. This set must not change as
3298 // buffers are being latched, as this could result in a deadlock.
3299 // Example: Two producers share the same command stream and:
3300 // 1.) Layer 0 is latched
3301 // 2.) Layer 0 gets a new frame
3302 // 2.) Layer 1 gets a new frame
3303 // 3.) Layer 1 is latched.
3304 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3305 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003306 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003307 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003308 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003309 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003310 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003311 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003312 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003313 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003314 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003315 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003316 } else {
3317 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003318 }
Robert Carr2047fae2016-11-28 14:09:09 -08003319 });
3320
Lloyd Piquef2c79392018-12-20 16:23:33 -08003321 if (!mLayersWithQueuedFrames.empty()) {
3322 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3323 // writes to Layer current state. See also b/119481871
3324 Mutex::Autolock lock(mStateLock);
3325
3326 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003327 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003328 mLayersPendingRefresh.push_back(layer);
3329 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003330 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003331 if (layer->isBufferLatched()) {
3332 newDataLatched = true;
3333 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003334 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003335 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003336
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003337 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003338
3339 // If we will need to wake up at some time in the future to deal with a
3340 // queued frame that shouldn't be displayed during this vsync period, wake
3341 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003342 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003343 signalLayerUpdate();
3344 }
3345
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003346 // enter boot animation on first buffer latch
3347 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3348 ALOGI("Enter boot animation");
3349 mBootStage = BootStage::BOOTANIMATION;
3350 }
3351
Dan Stoza6b9454d2014-11-07 16:00:59 -08003352 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003353 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003354}
3355
Mathias Agopianad456f92011-01-13 17:53:01 -08003356void SurfaceFlinger::invalidateHwcGeometry()
3357{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003358 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003359}
3360
Lloyd Pique32cbe282018-10-19 13:09:22 -07003361void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003362 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003363 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003364 // We only need to actually compose the display if:
3365 // 1) It is being handled by hardware composer, which may need this to
3366 // keep its virtual display state machine in sync, or
3367 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003368 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003370 return;
3371 }
3372
Dan Stoza9e56aa02015-11-02 13:00:03 -08003373 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003374 base::unique_fd readyFence;
3375 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003376
3377 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003378 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003379}
3380
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003381bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3382 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003383 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003384 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003385
Lloyd Pique32cbe282018-10-19 13:09:22 -07003386 auto display = displayDevice->getCompositionDisplay();
3387 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003388 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003389 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003390 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003391
3392 const Region bounds(displayState.bounds);
3393 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003394 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003395 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003396
Chia-I Wu8e50e692018-05-04 10:12:37 -07003397 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003398
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003399 renderengine::DisplaySettings clientCompositionDisplay;
3400 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3401 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003402 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003403
Dan Stoza9e56aa02015-11-02 13:00:03 -08003404 if (hasClientComposition) {
3405 ALOGV("hasClientComposition");
3406
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003407 if (displayDevice->isPrimary() && supportProtectedContent) {
3408 bool needsProtected = false;
3409 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3410 // If the layer is a protected layer, mark protected context is needed.
3411 if (layer->isProtected()) {
3412 needsProtected = true;
3413 break;
3414 }
3415 }
Peiyong Lin52010312019-05-02 14:22:16 -07003416 if (needsProtected != renderEngine.isProtected()) {
3417 renderEngine.useProtectedContext(needsProtected);
3418 }
3419 if (needsProtected != display->getRenderSurface()->isProtected() &&
3420 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003421 display->getRenderSurface()->setProtected(needsProtected);
3422 }
3423 }
3424
Alec Mouri6338c9d2019-02-07 16:57:51 -08003425 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003426
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003427 if (buf == nullptr) {
3428 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3429 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003430 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003431 return false;
3432 }
3433
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003434 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3435 clientCompositionDisplay.clip = displayState.scissor;
3436 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003437 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003438 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003439
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003440 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003441 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003442 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003443 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003444 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003445 clientCompositionDisplay.outputDataspace = outputDataspace;
3446 clientCompositionDisplay.maxLuminance =
3447 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003448
Lloyd Pique441d5042018-10-18 16:49:51 -07003449 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003450 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003451 getHwComposer()
3452 .hasDisplayCapability(displayId,
3453 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003454
Peiyong Lind3788632018-09-18 16:01:31 -07003455 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003456 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3457 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003458 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003459 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003460 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003461
Mathias Agopian85d751c2012-08-29 16:59:24 -07003462 /*
3463 * and then, render the layers targeted at the framebuffer
3464 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003465
Dan Stoza9e56aa02015-11-02 13:00:03 -08003466 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003467 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003468 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003469 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003470 const Region viewportRegion(displayState.viewport);
3471 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003472 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003473 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003474 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003475 switch (layer->getCompositionType(displayDevice)) {
3476 case Hwc2::IComposerClient::Composition::CURSOR:
3477 case Hwc2::IComposerClient::Composition::DEVICE:
3478 case Hwc2::IComposerClient::Composition::SIDEBAND:
3479 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003480 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003481 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003482 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003483 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003484 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003485 // never clear the very first layer since we're
3486 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003487 renderengine::LayerSettings layerSettings;
3488 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003489 bool prepared =
3490 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3491 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003492
3493 if (prepared) {
3494 layerSettings.source.buffer.buffer = nullptr;
3495 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3496 layerSettings.alpha = half(0.0);
3497 layerSettings.disableBlending = true;
3498 clientCompositionLayers.push_back(layerSettings);
3499 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003500 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003501 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003502 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003503 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003504 renderengine::LayerSettings layerSettings;
3505 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003506 layer->prepareClientLayer(renderArea, clip, clearRegion,
3507 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003508 if (prepared) {
3509 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003510 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003511 break;
3512 }
3513 default:
3514 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003515 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003516 } else {
3517 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003518 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003519 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003520 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003521
Alec Mouri820c7402019-01-23 13:02:39 -08003522 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003523 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003524 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003525
3526 // We boost GPU frequency here because there will be color spaces conversion
3527 // and it's expensive. We boost the GPU frequency so that GPU composition can
3528 // finish in time. We must reset GPU frequency afterwards, because high frequency
3529 // consumes extra battery.
3530 const bool expensiveRenderingExpected =
3531 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3532 if (expensiveRenderingExpected && displayId) {
3533 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3534 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003535 if (!debugRegion.isEmpty()) {
3536 Region::const_iterator it = debugRegion.begin();
3537 Region::const_iterator end = debugRegion.end();
3538 while (it != end) {
3539 const Rect& rect = *it++;
3540 renderengine::LayerSettings layerSettings;
3541 layerSettings.source.buffer.buffer = nullptr;
3542 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3543 layerSettings.geometry.boundaries = rect.toFloatRect();
3544 layerSettings.alpha = half(1.0);
3545 clientCompositionLayers.push_back(layerSettings);
3546 }
3547 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003548 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003549 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3550 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003551 } else if (displayId) {
3552 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003553 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003554 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555}
3556
Robert Carrc0df3122019-04-11 13:18:21 -07003557status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3558 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3559 const sp<IBinder>& parentHandle,
3560 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003561 // add this layer to the current state list
3562 {
3563 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003564 sp<Layer> parent;
3565 if (parentHandle != nullptr) {
3566 parent = fromHandle(parentHandle);
3567 if (parent == nullptr) {
3568 return NAME_NOT_FOUND;
3569 }
3570 } else {
3571 parent = parentLayer;
3572 }
3573
Robert Carr1f0a16a2016-10-24 16:27:39 -07003574 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003575 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3576 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003577 return NO_MEMORY;
3578 }
Robert Carrc0df3122019-04-11 13:18:21 -07003579
3580 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3581
Robert Carrb89ea9d2018-12-10 13:01:14 -08003582 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003583 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003584 } else if (parent == nullptr) {
3585 lbc->onRemovedFromCurrentState();
3586 } else if (parent->isRemovedFromCurrentState()) {
3587 parent->addChild(lbc);
3588 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003589 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003590 parent->addChild(lbc);
3591 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003592
Yiwei Zhang243b3782018-05-15 17:40:04 -07003593 if (gbc != nullptr) {
3594 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3595 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3596 mMaxGraphicBufferProducerListSize,
3597 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3598 mGraphicBufferProducerList.size(),
3599 mMaxGraphicBufferProducerListSize, mNumLayers);
3600 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003601 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003602 }
3603
Mathias Agopian96f08192010-06-02 23:28:45 -07003604 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003605 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003606
Dan Stoza7d89d062015-04-30 13:29:25 -07003607 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003608}
3609
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003610uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003611 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003612}
3613
Mathias Agopian3f844832013-08-07 21:24:32 -07003614uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003615 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003616}
3617
Mathias Agopian3f844832013-08-07 21:24:32 -07003618uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003619 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003620}
3621
3622uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003623 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003624 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003625 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003627 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003628 }
3629 return old;
3630}
3631
Marissa Wall713b63f2018-10-17 15:42:43 -07003632bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003633 // to prevent onHandleDestroyed from being called while the lock is held,
3634 // we must keep a copy of the transactions (specifically the composer
3635 // states) around outside the scope of the lock
3636 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003637 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003638 {
3639 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003640
Valerie Haufce31b82019-04-30 16:41:14 -07003641 auto it = mTransactionQueues.begin();
3642 while (it != mTransactionQueues.end()) {
3643 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003644
Valerie Haufce31b82019-04-30 16:41:14 -07003645 while (!transactionQueue.empty()) {
3646 const auto& transaction = transactionQueue.front();
3647 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3648 transaction.states)) {
3649 setTransactionFlags(eTransactionFlushNeeded);
3650 break;
3651 }
3652 transactions.push_back(transaction);
3653 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3654 mPendingInputWindowCommands, transaction.desiredPresentTime,
3655 transaction.buffer, transaction.callback,
3656 transaction.postTime, transaction.privileged,
3657 /*isMainThread*/ true);
3658 transactionQueue.pop();
3659 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003660 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003661
Valerie Haufce31b82019-04-30 16:41:14 -07003662 if (transactionQueue.empty()) {
3663 it = mTransactionQueues.erase(it);
3664 mTransactionCV.broadcast();
3665 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003666 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003667 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003668 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003669 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003670 return flushedATransaction;
3671}
3672
3673bool SurfaceFlinger::transactionFlushNeeded() {
3674 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003675}
3676
chaviwca27f252018-02-06 16:46:39 -08003677bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3678 for (const ComposerState& state : states) {
3679 // Here we need to check that the interface we're given is indeed
3680 // one of our own. A malicious client could give us a nullptr
3681 // IInterface, or one of its own or even one of our own but a
3682 // different type. All these situations would cause us to crash.
3683 if (state.client == nullptr) {
3684 return true;
3685 }
3686
3687 sp<IBinder> binder = IInterface::asBinder(state.client);
3688 if (binder == nullptr) {
3689 return true;
3690 }
3691
3692 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3693 return true;
3694 }
3695 }
3696 return false;
3697}
3698
Marissa Wall17b4e452018-12-26 16:32:34 -08003699bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3700 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003701 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003702 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3703 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3704 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3705 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3706 return false;
3707 }
3708
Marissa Wall713b63f2018-10-17 15:42:43 -07003709 for (const ComposerState& state : states) {
3710 const layer_state_t& s = state.state;
3711 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3712 continue;
3713 }
3714 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003715 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003716 }
3717 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003718 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003719}
3720
3721void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3722 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003723 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003724 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003725 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003726 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003727 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003728 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003729
Valerie Haubc6ddb12019-03-08 11:10:15 -08003730 const int64_t postTime = systemTime();
3731
Robert Carr14167e02019-02-13 13:50:55 -08003732 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3733
Mathias Agopian698c0872011-06-28 19:09:31 -07003734 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003735
chaviwca27f252018-02-06 16:46:39 -08003736 if (containsAnyInvalidClientState(states)) {
3737 return;
3738 }
3739
Marissa Wall713b63f2018-10-17 15:42:43 -07003740 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003741 auto itr = mTransactionQueues.find(applyToken);
3742 // if this is an animation frame, wait until prior animation frame has
3743 // been applied by SF
3744 if (flags & eAnimation) {
3745 while (itr != mTransactionQueues.end()) {
3746 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3747 if (CC_UNLIKELY(err != NO_ERROR)) {
3748 ALOGW_IF(err == TIMED_OUT,
3749 "setTransactionState timed out "
3750 "waiting for animation frame to apply");
3751 break;
3752 }
3753 itr = mTransactionQueues.find(applyToken);
3754 }
3755 }
3756 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003757 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003758 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003759 uncacheBuffer, listenerCallbacks, postTime,
3760 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003761 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003762 return;
3763 }
3764
Valerie Haubc6ddb12019-03-08 11:10:15 -08003765 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003766 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003767}
3768
3769void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003770 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003771 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003772 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003773 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003774 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003775 const int64_t postTime, bool privileged,
3776 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003777 uint32_t transactionFlags = 0;
3778
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003779 if (flags & eAnimation) {
3780 // For window updates that are part of an animation we must wait for
3781 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003782 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003783 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003784 if (CC_UNLIKELY(err != NO_ERROR)) {
3785 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003786 // caller after a few seconds.
3787 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3788 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003789 mAnimTransactionPending = false;
3790 break;
3791 }
3792 }
3793 }
3794
chaviwca27f252018-02-06 16:46:39 -08003795 for (const DisplayState& display : displays) {
3796 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003797 }
3798
Marissa Walld600d572019-03-26 15:38:50 -07003799 // In case the client has sent a Transaction that should receive callbacks but without any
3800 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3801 // to the callback thread so it can send an empty callback
3802 if (!listenerCallbacks.empty()) {
3803 mTransactionCompletedThread.run();
3804 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003805 for (const auto& listenerCallback : listenerCallbacks) {
3806 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003807 }
3808
Marissa Walle2ffb422018-10-12 11:33:52 -07003809 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003810 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003811 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3812 postTime, privileged);
3813 }
3814
Marissa Wallefb71af2019-06-27 14:45:53 -07003815 for (const auto& listenerCallback : listenerCallbacks) {
3816 mTransactionCompletedThread.endRegistration(listenerCallback);
3817 }
3818
Marissa Walle2ffb422018-10-12 11:33:52 -07003819 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003820 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003821 mTransactionCompletedThread.sendCallbacks();
3822 }
3823 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003824
chaviw273171b2018-12-26 11:46:30 -08003825 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3826
Marissa Wall947d34e2019-03-29 14:03:53 -07003827 if (uncacheBuffer.isValid()) {
3828 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003829 }
3830
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003831 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3832 // anyway. This can be used as a flush mechanism for previous async transactions.
3833 // Empty animation transaction can be used to simulate back-pressure, so also force a
3834 // transaction for empty animation transactions.
3835 if (transactionFlags == 0 &&
3836 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003837 transactionFlags = eTransactionNeeded;
3838 }
3839
Marissa Wall06255332019-03-27 13:48:27 -07003840 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3841 // so we don't have to wake up again next frame to preform an uneeded traversal.
3842 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3843 transactionFlags = transactionFlags & (~eTraversalNeeded);
3844 mTraversalNeededMainThread = true;
3845 }
3846
Mathias Agopian386aa982011-11-07 21:58:03 -08003847 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003848 if (mInterceptor->isEnabled()) {
3849 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003850 }
Irvel468051e2016-06-13 16:44:44 -07003851
Mathias Agopian386aa982011-11-07 21:58:03 -08003852 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003853 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3854 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003855 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003856
3857 // if this is a synchronous transaction, wait for it to take effect
3858 // before returning.
3859 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003860 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003861 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003862 if (flags & eAnimation) {
3863 mAnimTransactionPending = true;
3864 }
chaviw4fe36852019-04-15 16:25:49 -07003865 if (mPendingInputWindowCommands.syncInputWindows) {
3866 mPendingSyncInputWindows = true;
3867 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003868
3869 // applyTransactionState can be called by either the main SF thread or by
3870 // another process through setTransactionState. While a given process may wish
3871 // to wait on synchronous transactions, the main SF thread should never
3872 // be blocked. Therefore, we only wait if isMainThread is false.
3873 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003874 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3875 if (CC_UNLIKELY(err != NO_ERROR)) {
3876 // just in case something goes wrong in SF, return to the
3877 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003878 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3879 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003880 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003881 break;
3882 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003884 }
3885}
3886
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003887uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3888 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3889 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003890
Mathias Agopiane57f2922012-08-09 16:29:12 -07003891 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003892 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3893
3894 const uint32_t what = s.what;
3895 if (what & DisplayState::eSurfaceChanged) {
3896 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3897 state.surface = s.surface;
3898 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003899 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003900 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003901 if (what & DisplayState::eLayerStackChanged) {
3902 if (state.layerStack != s.layerStack) {
3903 state.layerStack = s.layerStack;
3904 flags |= eDisplayTransactionNeeded;
3905 }
3906 }
3907 if (what & DisplayState::eDisplayProjectionChanged) {
3908 if (state.orientation != s.orientation) {
3909 state.orientation = s.orientation;
3910 flags |= eDisplayTransactionNeeded;
3911 }
3912 if (state.frame != s.frame) {
3913 state.frame = s.frame;
3914 flags |= eDisplayTransactionNeeded;
3915 }
3916 if (state.viewport != s.viewport) {
3917 state.viewport = s.viewport;
3918 flags |= eDisplayTransactionNeeded;
3919 }
3920 }
3921 if (what & DisplayState::eDisplaySizeChanged) {
3922 if (state.width != s.width) {
3923 state.width = s.width;
3924 flags |= eDisplayTransactionNeeded;
3925 }
3926 if (state.height != s.height) {
3927 state.height = s.height;
3928 flags |= eDisplayTransactionNeeded;
3929 }
3930 }
3931
Mathias Agopiane57f2922012-08-09 16:29:12 -07003932 return flags;
3933}
3934
Robert Carr14167e02019-02-13 13:50:55 -08003935bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003936 IPCThreadState* ipc = IPCThreadState::self();
3937 const int pid = ipc->getCallingPid();
3938 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003939 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003940 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003941 return false;
3942 }
3943 return true;
3944}
3945
Marissa Wall3dad52d2019-03-22 14:03:19 -07003946uint32_t SurfaceFlinger::setClientStateLocked(
3947 const ComposerState& composerState, int64_t desiredPresentTime,
3948 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3949 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003950 const layer_state_t& s = composerState.state;
3951 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3952
Mathias Agopian13127d82013-03-05 17:47:11 -08003953 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003954 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003955 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003956 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003957 new CallbackHandle(listenerCallback.transactionCompletedListener,
3958 listenerCallback.callbackIds, s.surface));
3959 }
chaviw8b3871a2017-11-01 17:41:01 -07003960 return 0;
3961 }
3962
chaviw8b3871a2017-11-01 17:41:01 -07003963 uint32_t flags = 0;
3964
Garfield Tan8a3083e2018-12-03 13:21:07 -08003965 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003966 bool geometryAppliesWithResize =
3967 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003968
3969 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3970 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003971 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003972 layer->pushPendingState();
3973 }
3974
chaviw8b3871a2017-11-01 17:41:01 -07003975 if (what & layer_state_t::ePositionChanged) {
3976 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3977 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003978 }
chaviw8b3871a2017-11-01 17:41:01 -07003979 }
3980 if (what & layer_state_t::eLayerChanged) {
3981 // NOTE: index needs to be calculated before we update the state
3982 const auto& p = layer->getParent();
3983 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003984 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003985 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003986 mCurrentState.layersSortedByZ.removeAt(idx);
3987 mCurrentState.layersSortedByZ.add(layer);
3988 // we need traversal (state changed)
3989 // AND transaction (list changed)
3990 flags |= eTransactionNeeded|eTraversalNeeded;
3991 }
chaviw8b3871a2017-11-01 17:41:01 -07003992 } else {
3993 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003994 flags |= eTransactionNeeded|eTraversalNeeded;
3995 }
3996 }
chaviw8b3871a2017-11-01 17:41:01 -07003997 }
3998 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003999 // NOTE: index needs to be calculated before we update the state
4000 const auto& p = layer->getParent();
4001 if (p == nullptr) {
4002 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4003 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4004 mCurrentState.layersSortedByZ.removeAt(idx);
4005 mCurrentState.layersSortedByZ.add(layer);
4006 // we need traversal (state changed)
4007 // AND transaction (list changed)
4008 flags |= eTransactionNeeded|eTraversalNeeded;
4009 }
4010 } else {
4011 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4012 flags |= eTransactionNeeded|eTraversalNeeded;
4013 }
chaviw8b3871a2017-11-01 17:41:01 -07004014 }
4015 }
4016 if (what & layer_state_t::eSizeChanged) {
4017 if (layer->setSize(s.w, s.h)) {
4018 flags |= eTraversalNeeded;
4019 }
4020 }
4021 if (what & layer_state_t::eAlphaChanged) {
4022 if (layer->setAlpha(s.alpha))
4023 flags |= eTraversalNeeded;
4024 }
4025 if (what & layer_state_t::eColorChanged) {
4026 if (layer->setColor(s.color))
4027 flags |= eTraversalNeeded;
4028 }
Peiyong Lind3788632018-09-18 16:01:31 -07004029 if (what & layer_state_t::eColorTransformChanged) {
4030 if (layer->setColorTransform(s.colorTransform)) {
4031 flags |= eTraversalNeeded;
4032 }
4033 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004034 if (what & layer_state_t::eBackgroundColorChanged) {
4035 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4036 flags |= eTraversalNeeded;
4037 }
4038 }
chaviw8b3871a2017-11-01 17:41:01 -07004039 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004040 // TODO: b/109894387
4041 //
4042 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4043 // rotation. To see the problem observe that if we have a square parent, and a child
4044 // of the same size, then we rotate the child 45 degrees around it's center, the child
4045 // must now be cropped to a non rectangular 8 sided region.
4046 //
4047 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4048 // private API, and the WindowManager only uses rotation in one case, which is on a top
4049 // level layer in which cropping is not an issue.
4050 //
4051 // However given that abuse of rotation matrices could lead to surfaces extending outside
4052 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4053 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4054 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004055 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004056 flags |= eTraversalNeeded;
4057 }
4058 if (what & layer_state_t::eTransparentRegionChanged) {
4059 if (layer->setTransparentRegionHint(s.transparentRegion))
4060 flags |= eTraversalNeeded;
4061 }
4062 if (what & layer_state_t::eFlagsChanged) {
4063 if (layer->setFlags(s.flags, s.mask))
4064 flags |= eTraversalNeeded;
4065 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004066 if (what & layer_state_t::eCropChanged_legacy) {
4067 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004068 flags |= eTraversalNeeded;
4069 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004070 if (what & layer_state_t::eCornerRadiusChanged) {
4071 if (layer->setCornerRadius(s.cornerRadius))
4072 flags |= eTraversalNeeded;
4073 }
chaviw8b3871a2017-11-01 17:41:01 -07004074 if (what & layer_state_t::eLayerStackChanged) {
4075 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4076 // We only allow setting layer stacks for top level layers,
4077 // everything else inherits layer stack from its parent.
4078 if (layer->hasParent()) {
4079 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4080 layer->getName().string());
4081 } else if (idx < 0) {
4082 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4083 "that also does not appear in the top level layer list. Something"
4084 " has gone wrong.", layer->getName().string());
4085 } else if (layer->setLayerStack(s.layerStack)) {
4086 mCurrentState.layersSortedByZ.removeAt(idx);
4087 mCurrentState.layersSortedByZ.add(layer);
4088 // we need traversal (state changed)
4089 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004090 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004091 }
4092 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004093 if (what & layer_state_t::eDeferTransaction_legacy) {
4094 if (s.barrierHandle_legacy != nullptr) {
4095 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4096 } else if (s.barrierGbp_legacy != nullptr) {
4097 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004098 if (authenticateSurfaceTextureLocked(gbp)) {
4099 const auto& otherLayer =
4100 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004101 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004102 } else {
4103 ALOGE("Attempt to defer transaction to to an"
4104 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004105 }
4106 }
chaviw8b3871a2017-11-01 17:41:01 -07004107 // We don't trigger a traversal here because if no other state is
4108 // changed, we don't want this to cause any more work
4109 }
4110 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004111 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004112 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004113 if (!hadParent) {
4114 mCurrentState.layersSortedByZ.remove(layer);
4115 }
chaviw8b3871a2017-11-01 17:41:01 -07004116 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004117 }
chaviw8b3871a2017-11-01 17:41:01 -07004118 }
4119 if (what & layer_state_t::eReparentChildren) {
4120 if (layer->reparentChildren(s.reparentHandle)) {
4121 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004122 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004123 }
chaviw8b3871a2017-11-01 17:41:01 -07004124 if (what & layer_state_t::eDetachChildren) {
4125 layer->detachChildren();
4126 }
4127 if (what & layer_state_t::eOverrideScalingModeChanged) {
4128 layer->setOverrideScalingMode(s.overrideScalingMode);
4129 // We don't trigger a traversal here because if no other state is
4130 // changed, we don't want this to cause any more work
4131 }
Marissa Wall61c58622018-07-18 10:12:20 -07004132 if (what & layer_state_t::eTransformChanged) {
4133 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4134 }
4135 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4136 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4137 flags |= eTraversalNeeded;
4138 }
4139 if (what & layer_state_t::eCropChanged) {
4140 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4141 }
Marissa Wall861616d2018-10-22 12:52:23 -07004142 if (what & layer_state_t::eFrameChanged) {
4143 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4144 }
Marissa Wall61c58622018-07-18 10:12:20 -07004145 if (what & layer_state_t::eAcquireFenceChanged) {
4146 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4147 }
4148 if (what & layer_state_t::eDataspaceChanged) {
4149 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4150 }
4151 if (what & layer_state_t::eHdrMetadataChanged) {
4152 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4153 }
4154 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4155 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4156 }
4157 if (what & layer_state_t::eApiChanged) {
4158 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4159 }
4160 if (what & layer_state_t::eSidebandStreamChanged) {
4161 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4162 }
Robert Carr720e5062018-07-30 17:45:14 -07004163 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004164 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004165 layer->setInputInfo(s.inputInfo);
4166 flags |= eTraversalNeeded;
4167 } else {
4168 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4169 }
Robert Carr720e5062018-07-30 17:45:14 -07004170 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004171 if (what & layer_state_t::eMetadataChanged) {
4172 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4173 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004174 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4175 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4176 flags |= eTraversalNeeded;
4177 }
4178 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004179 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004180 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004181 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004182 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4183 }
4184 }
Marissa Wall78b72202019-03-15 14:58:34 -07004185 bool bufferChanged = what & layer_state_t::eBufferChanged;
4186 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4187 sp<GraphicBuffer> buffer;
4188 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004189 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri1c8d7202019-06-01 18:51:35 -07004190 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4191 wp<ClientCache::ErasedRecipient>(layer));
4192 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004193 buffer = s.buffer;
4194 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004195 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004196 } else if (bufferChanged) {
4197 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004198 }
Marissa Wall78b72202019-03-15 14:58:34 -07004199 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004200 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004201 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004202 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004203 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004204 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4205 // Do not put anything that updates layer state or modifies flags after
4206 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004207 return flags;
4208}
4209
chaviw273171b2018-12-26 11:46:30 -08004210uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4211 uint32_t flags = 0;
4212 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4213 flags |= eTraversalNeeded;
4214 }
4215
chaviwa911b102019-02-14 10:18:33 -08004216 if (inputWindowCommands.syncInputWindows) {
4217 flags |= eTraversalNeeded;
4218 }
4219
Vishnu Nairec0ab382019-02-13 15:32:56 -08004220 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004221 return flags;
4222}
4223
Marissa Wall2d814fb2019-04-09 18:52:57 +00004224status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4225 uint32_t h, PixelFormat format, uint32_t flags,
4226 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004227 sp<IGraphicBufferProducer>* gbp,
4228 const sp<IBinder>& parentHandle,
4229 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004230 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004231 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004232 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004233 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004234 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004235
Robert Carrc0df3122019-04-11 13:18:21 -07004236 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4237 "Expected only one of parentLayer or parentHandle to be non-null. "
4238 "Programmer error?");
4239
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004240 status_t result = NO_ERROR;
4241
4242 sp<Layer> layer;
4243
Cody Northropbc755282017-03-31 12:00:08 -06004244 String8 uniqueName = getUniqueLayerName(name);
4245
Evan Roskya1f1e152019-01-24 16:17:46 -08004246 bool primaryDisplayOnly = false;
4247
4248 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4249 // TODO b/64227542
4250 if (metadata.has(METADATA_WINDOW_TYPE)) {
4251 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4252 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004253 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004254 primaryDisplayOnly = true;
4255 }
4256 }
4257
Mathias Agopian3165cc22012-08-08 19:42:09 -07004258 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004259 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004260 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4261 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004262
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004263 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004264 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004265 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4266 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004267 break;
chaviw13fdc492017-06-27 12:40:18 -07004268 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004269 // check if buffer size is set for color layer.
4270 if (w > 0 || h > 0) {
4271 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4272 int(w), int(h));
4273 return BAD_VALUE;
4274 }
4275
Evan Roskya1f1e152019-01-24 16:17:46 -08004276 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4277 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004278 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004279 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004280 // check if buffer size is set for container layer.
4281 if (w > 0 || h > 0) {
4282 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4283 int(w), int(h));
4284 return BAD_VALUE;
4285 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004286 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4287 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004288 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004289 default:
4290 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004291 break;
4292 }
4293
Dan Stoza7d89d062015-04-30 13:29:25 -07004294 if (result != NO_ERROR) {
4295 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004296 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004297
Evan Roskya1f1e152019-01-24 16:17:46 -08004298 if (primaryDisplayOnly) {
4299 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004300 }
4301
Robert Carrb89ea9d2018-12-10 13:01:14 -08004302 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004303 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4304 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004305 if (result != NO_ERROR) {
4306 return result;
4307 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004308 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004309
4310 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004311 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004312}
4313
Cody Northropbc755282017-03-31 12:00:08 -06004314String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4315{
4316 bool matchFound = true;
4317 uint32_t dupeCounter = 0;
4318
4319 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4320 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4321
Dan Stoza436ccf32018-06-21 12:10:12 -07004322 // Grab the state lock since we're accessing mCurrentState
4323 Mutex::Autolock lock(mStateLock);
4324
Cody Northropbc755282017-03-31 12:00:08 -06004325 // Loop over layers until we're sure there is no matching name
4326 while (matchFound) {
4327 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004328 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004329 if (layer->getName() == uniqueName) {
4330 matchFound = true;
4331 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4332 }
4333 });
4334 }
4335
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004336 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4337 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004338
4339 return uniqueName;
4340}
4341
Marissa Wallfd668622018-05-10 10:21:13 -07004342status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4343 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004344 LayerMetadata metadata, PixelFormat& format,
4345 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004346 sp<IGraphicBufferProducer>* gbp,
4347 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004348 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004349 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004350 case PIXEL_FORMAT_TRANSPARENT:
4351 case PIXEL_FORMAT_TRANSLUCENT:
4352 format = PIXEL_FORMAT_RGBA_8888;
4353 break;
4354 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004355 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004356 break;
4357 }
4358
Evan Roskya1f1e152019-01-24 16:17:46 -08004359 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4360 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004361 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004362 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004363 *handle = layer->getHandle();
4364 *gbp = layer->getProducer();
4365 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004366 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004367
Marissa Wallfd668622018-05-10 10:21:13 -07004368 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004369 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004370}
4371
Marissa Wall61c58622018-07-18 10:12:20 -07004372status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4373 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004374 LayerMetadata metadata, sp<IBinder>* handle,
4375 sp<Layer>* outLayer) {
4376 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4377 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004378 *handle = layer->getHandle();
4379 *outLayer = layer;
4380
4381 return NO_ERROR;
4382}
4383
Evan Roskya1f1e152019-01-24 16:17:46 -08004384status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4385 uint32_t h, uint32_t flags, LayerMetadata metadata,
4386 sp<IBinder>* handle, sp<Layer>* outLayer) {
4387 *outLayer = getFactory().createColorLayer(
4388 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004389 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004390 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004391}
4392
Evan Roskya1f1e152019-01-24 16:17:46 -08004393status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4394 uint32_t w, uint32_t h, uint32_t flags,
4395 LayerMetadata metadata, sp<IBinder>* handle,
4396 sp<Layer>* outLayer) {
4397 *outLayer = getFactory().createContainerLayer(
4398 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004399 *handle = (*outLayer)->getHandle();
4400 return NO_ERROR;
4401}
4402
4403
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004404void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004405 mLayersPendingRemoval.add(layer);
4406 mLayersRemoved = true;
4407 setTransactionFlags(eTransactionNeeded);
4408}
4409
Robert Carr695d5282018-12-18 15:27:58 -08004410void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004411{
Robert Carr2e102c92018-10-23 12:11:15 -07004412 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004413 // If a layer has a parent, we allow it to out-live it's handle
4414 // with the idea that the parent holds a reference and will eventually
4415 // be cleaned up. However no one cleans up the top-level so we do so
4416 // here.
4417 if (layer->getParent() == nullptr) {
4418 mCurrentState.layersSortedByZ.remove(layer);
4419 }
4420 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004421
4422 auto it = mLayersByLocalBinderToken.begin();
4423 while (it != mLayersByLocalBinderToken.end()) {
4424 if (it->second == layer) {
4425 it = mLayersByLocalBinderToken.erase(it);
4426 } else {
4427 it++;
4428 }
4429 }
4430
Robert Carr695d5282018-12-18 15:27:58 -08004431 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004432}
4433
Mathias Agopianb60314a2012-04-10 22:09:54 -07004434// ---------------------------------------------------------------------------
4435
Andy McFadden13a082e2012-08-24 10:16:42 -07004436void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004437 const auto display = getDefaultDisplayDeviceLocked();
4438 if (!display) return;
4439
4440 const sp<IBinder> token = display->getDisplayToken().promote();
4441 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004442
Jesse Hall01e29052013-02-19 16:13:35 -08004443 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004444 Vector<ComposerState> state;
4445 Vector<DisplayState> displays;
4446 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004447 d.what = DisplayState::eDisplayProjectionChanged |
4448 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004449 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004450 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004451 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004452 d.frame.makeInvalid();
4453 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004454 d.width = 0;
4455 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004456 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004457 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004458
Dominik Laskowskie9774092018-12-11 10:04:24 -08004459 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004460
Dominik Laskowski83b88212018-12-11 13:34:06 -08004461 const nsecs_t vsyncPeriod = getVsyncPeriod();
4462 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004463
Brian Andersond0010582017-03-07 13:20:31 -08004464 // Use phase of 0 since phase is not known.
4465 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004466 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004467 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004468}
4469
4470void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004471 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004472 postMessageAsync(
4473 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004474}
4475
Ady Abraham27c70212019-06-11 10:52:26 -07004476void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4477 if (mHWCVsyncState != enabled) {
4478 getHwComposer().setVsyncEnabled(displayId, enabled);
4479 mHWCVsyncState = enabled;
4480 }
4481}
4482
Dominik Laskowskie9774092018-12-11 10:04:24 -08004483void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004484 if (display->isVirtual()) {
4485 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004486 return;
4487 }
4488
Dominik Laskowski075d3172018-05-24 15:50:06 -07004489 const auto displayId = display->getId();
4490 LOG_ALWAYS_FATAL_IF(!displayId);
4491
Dominik Laskowski34157762018-10-31 13:07:19 -07004492 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004493
4494 int currentMode = display->getPowerMode();
4495 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004496 return;
4497 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004498
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004499 display->setPowerMode(mode);
4500
Lloyd Pique4dccc412018-01-22 17:21:36 -08004501 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004502 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004503 }
4504
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004505 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004506 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004507 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004508 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004509 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004510 mScheduler->onScreenAcquired(mAppConnectionHandle);
4511 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004512 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004514 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004515 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004516 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004517
4518 struct sched_param param = {0};
4519 param.sched_priority = 1;
4520 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4521 ALOGW("Couldn't set SCHED_FIFO on display on");
4522 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004523 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004524 // Turn off the display
4525 struct sched_param param = {0};
4526 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4527 ALOGW("Couldn't set SCHED_OTHER on display off");
4528 }
4529
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004530 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004531 mScheduler->disableHardwareVsync(true);
4532 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004533 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004534
Ady Abraham27c70212019-06-11 10:52:26 -07004535 // Make sure HWVsync is disabled before turning off the display
4536 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4537
Dominik Laskowski075d3172018-05-24 15:50:06 -07004538 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004539 mVisibleRegionsDirty = true;
4540 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004541 } else if (mode == HWC_POWER_MODE_DOZE ||
4542 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004543 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004544 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004546 mScheduler->onScreenAcquired(mAppConnectionHandle);
4547 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004548 }
4549 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4550 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004551 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004552 mScheduler->disableHardwareVsync(true);
4553 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004555 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004556 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004557 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004558 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004559 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004560
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004561 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004562 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004563 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004564 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004565 }
4566
Dominik Laskowski34157762018-10-31 13:07:19 -07004567 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004568}
4569
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004570void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004571 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004572 const auto display = getDisplayDevice(displayToken);
4573 if (!display) {
4574 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4575 displayToken.get());
4576 } else if (display->isVirtual()) {
4577 ALOGW("Attempt to set power mode %d for virtual display", mode);
4578 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004579 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004580 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004581 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004582}
4583
4584// ---------------------------------------------------------------------------
4585
Dominik Laskowskic2867142019-01-21 11:33:38 -08004586status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4587 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004589
Mathias Agopianbd115332013-04-18 16:41:04 -07004590 IPCThreadState* ipc = IPCThreadState::self();
4591 const int pid = ipc->getCallingPid();
4592 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004593
Mathias Agopianbd115332013-04-18 16:41:04 -07004594 if ((uid != AID_SHELL) &&
4595 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4597 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004599 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004600 // (this would indicate SF is stuck, but we want to be able to
4601 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004602 status_t err = mStateLock.timedLock(s2ns(1));
4603 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004604 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004605 StringAppendF(&result,
4606 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4607 "(no locks held)\n",
4608 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004609 }
4610
Dominik Laskowskic2867142019-01-21 11:33:38 -08004611 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004612
Dominik Laskowskic2867142019-01-21 11:33:38 -08004613 static const std::unordered_map<std::string, Dumper> dumpers = {
4614 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4615 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4616 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004617 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004618 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004619 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004620 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4621 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004622 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4623 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4624 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4625 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4626 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4627 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004628 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004629 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4630 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004631
Dominik Laskowskic2867142019-01-21 11:33:38 -08004632 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004633
Dominik Laskowskic2867142019-01-21 11:33:38 -08004634 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4635 (it->second)(args, asProto, result);
4636 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004637 if (asProto) {
4638 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4639 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4640 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004641 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004642 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004643 }
4644
Mathias Agopian9795c422009-08-26 16:36:26 -07004645 if (locked) {
4646 mStateLock.unlock();
4647 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004648 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004650 return NO_ERROR;
4651}
4652
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004653status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4654 if (asProto && mTracing.isEnabled()) {
4655 mTracing.writeToFileAsync();
4656 }
4657
4658 return doDump(fd, DumpArgs(), asProto);
4659}
4660
Dominik Laskowskic2867142019-01-21 11:33:38 -08004661void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004662 mCurrentState.traverseInZOrder(
4663 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004664}
4665
Dominik Laskowskic2867142019-01-21 11:33:38 -08004666void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004667 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004668
Dominik Laskowskic2867142019-01-21 11:33:38 -08004669 if (args.size() > 1) {
4670 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004671 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004672 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004673 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004674 }
Robert Carr2047fae2016-11-28 14:09:09 -08004675 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004676 } else {
4677 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678 }
4679}
4680
Dominik Laskowskic2867142019-01-21 11:33:38 -08004681void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004682 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004683 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004684 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004685 }
Robert Carr2047fae2016-11-28 14:09:09 -08004686 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004687
Svetoslavd85084b2014-03-20 10:28:31 -07004688 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004689}
4690
Dominik Laskowskic2867142019-01-21 11:33:38 -08004691void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4692 mTimeStats->parseArgs(asProto, args, result);
4693}
4694
Jamie Gennis6547ff42013-07-16 20:12:42 -07004695// This should only be called from the main thread. Otherwise it would need
4696// the lock and should use mCurrentState rather than mDrawingState.
4697void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004698 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004699 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004700 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004701
4702 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4703}
4704
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004706 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004707
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004708 if (isLayerTripleBufferingDisabled())
4709 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004710
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4712 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4713 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4714 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4715 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4716 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004717 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004718}
4719
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004720void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004721 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004722 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004723 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004724 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004725
Ady Abraham97d04232019-03-05 19:48:12 -08004726 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004727 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4728 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004729 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham261614e2019-07-10 17:53:12 -07004730 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4731 if (refresh.second && isDisplayConfigAllowed(refresh.second->configId)) {
4732 StringAppendF(&result, "%dHz, ", refresh.second->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004733 }
4734 }
4735 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4736 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004737 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004738}
4739
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4741 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004742 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4743 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004744 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004745 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004747 }
David Sodman4a36e932017-11-07 14:29:47 -08004748 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004749 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004750 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4752 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004753}
4754
Dan Stozae77c7662016-05-13 11:37:28 -07004755void SurfaceFlinger::recordBufferingStats(const char* layerName,
4756 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004757 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4758 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004759 for (const auto& segment : history) {
4760 if (!segment.usedThirdBuffer) {
4761 stats.twoBufferTime += segment.totalTime;
4762 }
4763 if (segment.occupancyAverage < 1.0f) {
4764 stats.doubleBufferedTime += segment.totalTime;
4765 } else if (segment.occupancyAverage < 2.0f) {
4766 stats.tripleBufferedTime += segment.totalTime;
4767 }
4768 ++stats.numSegments;
4769 stats.totalTime += segment.totalTime;
4770 }
4771}
4772
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4774 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004775
4776 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4777 const size_t count = currentLayers.size();
4778 for (size_t i=0 ; i<count ; i++) {
4779 currentLayers[i]->dumpFrameEvents(result);
4780 }
4781}
4782
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004784 result.append("Buffering stats:\n");
4785 result.append(" [Layer name] <Active time> <Two buffer> "
4786 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004787 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004788 typedef std::tuple<std::string, float, float, float> BufferTuple;
4789 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004790 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004791 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004792 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004793 if (stats.numSegments == 0) {
4794 continue;
4795 }
4796 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4797 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4798 stats.totalTime;
4799 float doubleBufferRatio = static_cast<float>(
4800 stats.doubleBufferedTime) / stats.totalTime;
4801 float tripleBufferRatio = static_cast<float>(
4802 stats.tripleBufferedTime) / stats.totalTime;
4803 sorted.insert({activeTime, {name, twoBufferRatio,
4804 doubleBufferRatio, tripleBufferRatio}});
4805 }
4806 for (const auto& sortedPair : sorted) {
4807 float activeTime = sortedPair.first;
4808 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4810 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004811 }
4812 result.append("\n");
4813}
4814
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004816 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817 const auto displayId = display->getId();
4818 if (!displayId) {
4819 continue;
4820 }
4821 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004822 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004823 continue;
4824 }
4825
Yiwei Zhang5434a782018-12-05 18:06:32 -08004826 StringAppendF(&result,
4827 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4828 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004829 uint8_t port;
4830 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004831 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004832 result.append("no identification data\n");
4833 continue;
4834 }
4835
4836 if (!isEdid(data)) {
4837 result.append("unknown identification data: ");
4838 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004839 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004840 }
4841 result.append("\n");
4842 continue;
4843 }
4844
4845 const auto edid = parseEdid(data);
4846 if (!edid) {
4847 result.append("invalid EDID: ");
4848 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004850 }
4851 result.append("\n");
4852 continue;
4853 }
4854
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004856 result.append(edid->displayName.data(), edid->displayName.length());
4857 result.append("\"\n");
4858 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004859}
4860
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004862 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4864 StringAppendF(&result, "DisplayColorSetting: %s\n",
4865 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004866
4867 // TODO: print out if wide-color mode is active or not
4868
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004869 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004870 const auto displayId = display->getId();
4871 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004872 continue;
4873 }
4874
Yiwei Zhang5434a782018-12-05 18:06:32 -08004875 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004876 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004877 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004879 }
4880
Lloyd Pique32cbe282018-10-19 13:09:22 -07004881 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004882 StringAppendF(&result, " Current color mode: %s (%d)\n",
4883 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004884 }
4885 result.append("\n");
4886}
4887
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004888LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4889 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004890 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004891 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4892 const State& state = useDrawing ? mDrawingState : mCurrentState;
4893 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004894 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004895 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004896 });
4897
4898 return layersProto;
4899}
4900
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004901LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4902 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004903 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004904
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004905 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004906 resolution->set_w(displayDevice->getWidth());
4907 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004908
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004909 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004910 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004911
Lloyd Pique32cbe282018-10-19 13:09:22 -07004912 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4913 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4914 layersProto.set_global_transform(displayState.orientation);
4915
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004916 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004917 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004918 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004919 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004920 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004921 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004922 }
4923 });
4924
4925 return layersProto;
4926}
4927
Dominik Laskowskic2867142019-01-21 11:33:38 -08004928void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4929 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004930 Colorizer colorizer(colorize);
4931
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004932 // figure out if we're stuck somewhere
4933 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004934 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004935 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4936
4937 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004938 * Dump library configuration.
4939 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004940
4941 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004942 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004943 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004944 appendSfConfigString(result);
4945 appendUiConfigString(result);
4946 appendGuiConfigString(result);
4947 result.append("\n");
4948
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004949 result.append("\nDisplay identification data:\n");
4950 dumpDisplayIdentificationData(result);
4951
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004952 result.append("\nWide-Color information:\n");
4953 dumpWideColorInfo(result);
4954
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004955 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004956 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004957 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004958 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004959 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004960
Andy McFadden41d67d72014-04-25 16:58:34 -07004961 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004962 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004963 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004964 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004965 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004966
Dan Stozab90cf072015-03-05 11:05:59 -08004967 dumpStaticScreenStats(result);
4968 result.append("\n");
4969
Alec Mouri40189b02019-03-05 15:07:54 -08004970 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4971 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4972 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004973
Dan Stozae77c7662016-05-13 11:37:28 -07004974 dumpBufferingStats(result);
4975
Andy McFadden4803b742012-09-24 19:07:20 -07004976 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004977 * Dump the visible layer list
4978 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004979 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004980 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4981 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4982 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004983 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004984
Chia-I Wu2f884132018-09-13 15:17:58 -07004985 {
4986 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4987 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004988 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004989 result.append("\n");
4990 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004991
Lloyd Pique207def92019-02-28 16:09:52 -08004992 {
4993 StringAppendF(&result, "Composition layers\n");
4994 mDrawingState.traverseInZOrder([&](Layer* layer) {
4995 auto compositionLayer = layer->getCompositionLayer();
4996 if (compositionLayer) compositionLayer->dump(result);
4997 });
4998 }
4999
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005000 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005001 * Dump Display state
5002 */
5003
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005004 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005005 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005006 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005007 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005008 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005009 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005010 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005011
5012 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005013 * Dump SurfaceFlinger global state
5014 */
5015
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005016 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005017 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005018 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005019
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005020 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005021
Dominik Laskowski075d3172018-05-24 15:50:06 -07005022 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005023 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5024 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005025 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5026 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005027 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005028 StringAppendF(&result,
5029 " transaction-flags : %08x\n"
5030 " gpu_to_cpu_unsupported : %d\n",
5031 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005032
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005033 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005034 displayId && getHwComposer().isConnected(*displayId)) {
5035 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005036 StringAppendF(&result,
5037 " refresh-rate : %f fps\n"
5038 " x-dpi : %f\n"
5039 " y-dpi : %f\n",
5040 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5041 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005042 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005043
Yiwei Zhang5434a782018-12-05 18:06:32 -08005044 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005045
Dan Stozae22aec72016-08-01 13:20:59 -07005046 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005047 * Tracing state
5048 */
5049 mTracing.dump(result);
5050 result.append("\n");
5051
5052 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005053 * HWC layer minidump
5054 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005055 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005056 const auto displayId = display->getId();
5057 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005058 continue;
5059 }
5060
Yiwei Zhang5434a782018-12-05 18:06:32 -08005061 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005062 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005063 const sp<DisplayDevice> displayDevice = display;
5064 mCurrentState.traverseInZOrder(
5065 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005066 result.append("\n");
5067 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005068
5069 /*
5070 * Dump HWComposer state
5071 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005072 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005073 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005074 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005075 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005076 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005077 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005078
5079 /*
5080 * Dump gralloc state
5081 */
5082 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5083 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005084
5085 /*
5086 * Dump VrFlinger state if in use.
5087 */
5088 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5089 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005090 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005091 result.append("\n");
5092 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005093
5094 /**
5095 * Scheduler dump state.
5096 */
Ana Krulecc2870422019-01-29 19:00:58 -08005097 result.append("\nScheduler state:\n");
5098 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005099 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005100 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005101
5102 result.append(mTimeStats->miniDump());
5103 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005104}
5105
Dominik Laskowski075d3172018-05-24 15:50:06 -07005106const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005107 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005108 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005109 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005110 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005111 }
5112 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005113
Dominik Laskowski34157762018-10-31 13:07:19 -07005114 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005115 static const Vector<sp<Layer>> empty;
5116 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005117}
5118
Chia-I Wu28f320b2018-05-03 11:02:56 -07005119void SurfaceFlinger::updateColorMatrixLocked() {
5120 mat4 colorMatrix;
5121 if (mGlobalSaturationFactor != 1.0f) {
5122 // Rec.709 luma coefficients
5123 float3 luminance{0.213f, 0.715f, 0.072f};
5124 luminance *= 1.0f - mGlobalSaturationFactor;
5125 mat4 saturationMatrix = mat4(
5126 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5127 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5128 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5129 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5130 );
5131 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5132 } else {
5133 colorMatrix = mClientColorMatrix * mDaltonizer();
5134 }
5135
5136 if (mCurrentState.colorMatrix != colorMatrix) {
5137 mCurrentState.colorMatrix = colorMatrix;
5138 mCurrentState.colorMatrixChanged = true;
5139 setTransactionFlags(eTransactionNeeded);
5140 }
5141}
5142
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005143status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005144#pragma clang diagnostic push
5145#pragma clang diagnostic error "-Wswitch-enum"
5146 switch (static_cast<ISurfaceComposerTag>(code)) {
5147 // These methods should at minimum make sure that the client requested
5148 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005149 case BOOT_FINISHED:
5150 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005151 case CREATE_DISPLAY:
5152 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005153 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005154 case GET_ANIMATION_FRAME_STATS:
5155 case GET_HDR_CAPABILITIES:
5156 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005157 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005158 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005159 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005160 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005161 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005162 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005163 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005164 case GET_DISPLAYED_CONTENT_SAMPLE:
5165 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005166 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5167 IPCThreadState* ipc = IPCThreadState::self();
5168 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5169 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005170 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005171 }
Robert Carr1db73f62016-12-21 12:58:51 -08005172 return OK;
5173 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005174 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005175 IPCThreadState* ipc = IPCThreadState::self();
5176 const int pid = ipc->getCallingPid();
5177 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005178 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5179 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005180 return PERMISSION_DENIED;
5181 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005182 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005183 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005184 // Used by apps to hook Choreographer to SurfaceFlinger.
5185 case CREATE_DISPLAY_EVENT_CONNECTION:
5186 // The following calls are currently used by clients that do not
5187 // request necessary permissions. However, they do not expose any secret
5188 // information, so it is OK to pass them.
5189 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005190 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005191 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005192 case GET_PHYSICAL_DISPLAY_IDS:
5193 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005194 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005195 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005196 case GET_DISPLAY_CONFIGS:
5197 case GET_DISPLAY_STATS:
5198 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5199 // Calling setTransactionState is safe, because you need to have been
5200 // granted a reference to Client* and Handle* to do anything with it.
5201 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005202 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005203 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005204 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005205 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005206 case IS_WIDE_COLOR_DISPLAY:
5207 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5208 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005209 return OK;
5210 }
Chong Zhangda6c1592019-07-16 13:45:06 -07005211 case CAPTURE_LAYERS: {
5212 IPCThreadState* ipc = IPCThreadState::self();
5213 const int pid = ipc->getCallingPid();
5214 const int uid = ipc->getCallingUid();
5215 // allow media to capture layer for video thumbnails
5216 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
5217 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5218 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
5219 return PERMISSION_DENIED;
5220 }
5221 return OK;
5222 }
Dan Stoza84ab9372018-12-17 15:27:57 -08005223 case CAPTURE_SCREEN:
5224 case ADD_REGION_SAMPLING_LISTENER:
5225 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005226 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005227 IPCThreadState* ipc = IPCThreadState::self();
5228 const int pid = ipc->getCallingPid();
5229 const int uid = ipc->getCallingUid();
5230 if ((uid != AID_GRAPHICS) &&
5231 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5232 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5233 return PERMISSION_DENIED;
5234 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005235 return OK;
5236 }
5237 // The following codes are deprecated and should never be allowed to access SF.
5238 case CONNECT_DISPLAY_UNUSED:
5239 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5240 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5241 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005242 }
chaviw93df2ea2019-04-30 16:45:12 -07005243 case CAPTURE_SCREEN_BY_ID: {
5244 IPCThreadState* ipc = IPCThreadState::self();
5245 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005246 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005247 return OK;
5248 }
5249 return PERMISSION_DENIED;
5250 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005251 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005252
5253 // These codes are used for the IBinder protocol to either interrogate the recipient
5254 // side of the transaction for its canonical interface descriptor or to dump its state.
5255 // We let them pass by default.
5256 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5257 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5258 code == IBinder::SYSPROPS_TRANSACTION) {
5259 return OK;
5260 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005261 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005262 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005263 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005264 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5265 return OK;
5266 }
5267 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5268 return PERMISSION_DENIED;
5269#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005270}
5271
Ana Krulec13be8ad2018-08-21 02:43:56 +00005272status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5273 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005274 status_t credentialCheck = CheckTransactCodeCredentials(code);
5275 if (credentialCheck != OK) {
5276 return credentialCheck;
5277 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005278
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005279 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5280 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005281 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005282 IPCThreadState* ipc = IPCThreadState::self();
5283 const int uid = ipc->getCallingUid();
5284 if (CC_UNLIKELY(uid != AID_SYSTEM
5285 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005286 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005287 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005288 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005289 return PERMISSION_DENIED;
5290 }
5291 int n;
5292 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005293 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005294 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005295 return NO_ERROR;
5296 case 1002: // SHOW_UPDATES
5297 n = data.readInt32();
5298 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005299 invalidateHwcGeometry();
5300 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005301 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005302 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005303 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005304 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005305 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005306 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005307 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005308 setTransactionFlags(
5309 eTransactionNeeded|
5310 eDisplayTransactionNeeded|
5311 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005312 return NO_ERROR;
5313 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005314 case 1006:{ // send empty update
5315 signalRefresh();
5316 return NO_ERROR;
5317 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005318 case 1008: // toggle use of hw composer
5319 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005320 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005321 invalidateHwcGeometry();
5322 repaintEverything();
5323 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005324 case 1009: // toggle use of transform hint
5325 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005326 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005327 invalidateHwcGeometry();
5328 repaintEverything();
5329 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005330 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005331 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005332 reply->writeInt32(0);
5333 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005334 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005335 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005336 return NO_ERROR;
5337 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005338 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005339 if (!display) {
5340 return NAME_NOT_FOUND;
5341 }
5342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005343 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005344 return NO_ERROR;
5345 }
5346 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005347 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005348 // daltonize
5349 n = data.readInt32();
5350 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005351 case 1:
5352 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5353 break;
5354 case 2:
5355 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5356 break;
5357 case 3:
5358 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5359 break;
5360 default:
5361 mDaltonizer.setType(ColorBlindnessType::None);
5362 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005363 }
5364 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005365 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005366 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005367 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005368 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005369
5370 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005371 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005372 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005373 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005374 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005375 // apply a color matrix
5376 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005377 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005378 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005379 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005380 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005381 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005382 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005383 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005384 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005385 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005386 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005387
5388 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5389 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005390 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005391 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5392 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5393 }
5394
Chia-I Wu28f320b2018-05-03 11:02:56 -07005395 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005396 return NO_ERROR;
5397 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005398 // This is an experimental interface
5399 // Needs to be shifted to proper binder interface when we productize
5400 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005401 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005402 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005403 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005404 return NO_ERROR;
5405 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005406 case 1017: {
5407 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005408 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005409 return NO_ERROR;
5410 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005411 case 1018: { // Modify Choreographer's phase offset
5412 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005413 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005414 return NO_ERROR;
5415 }
5416 case 1019: { // Modify SurfaceFlinger's phase offset
5417 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005418 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005419 return NO_ERROR;
5420 }
Irvel468051e2016-06-13 16:44:44 -07005421 case 1020: { // Layer updates interceptor
5422 n = data.readInt32();
5423 if (n) {
5424 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005425 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005426 }
5427 else{
5428 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005429 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005430 }
5431 return NO_ERROR;
5432 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005433 case 1021: { // Disable HWC virtual displays
5434 n = data.readInt32();
5435 mUseHwcVirtualDisplays = !n;
5436 return NO_ERROR;
5437 }
Romain Guy0147a172017-06-01 13:53:56 -07005438 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005439 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005440 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005441
Chia-I Wu28f320b2018-05-03 11:02:56 -07005442 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005443 return NO_ERROR;
5444 }
Romain Guy54f154a2017-10-24 21:40:32 +01005445 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005446 int32_t colorMode;
5447
Chia-I Wu0d711262018-05-21 15:19:35 -07005448 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005449 if (data.readInt32(&colorMode) == NO_ERROR) {
5450 mForceColorMode = static_cast<ColorMode>(colorMode);
5451 }
Romain Guy54f154a2017-10-24 21:40:32 +01005452 invalidateHwcGeometry();
5453 repaintEverything();
5454 return NO_ERROR;
5455 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005456 // Deprecate, use 1030 to check whether the device is color managed.
5457 case 1024: {
5458 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005459 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005460 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005461 n = data.readInt32();
5462 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005463 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005464 Mutex::Autolock lock(mStateLock);
5465 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005466 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005467 reply->writeInt32(NO_ERROR);
5468 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005469 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005470 bool writeFile = false;
5471 {
5472 Mutex::Autolock lock(mStateLock);
5473 mTracingEnabledChanged = true;
5474 writeFile = mTracing.disable();
5475 }
5476
5477 if (writeFile) {
5478 reply->writeInt32(mTracing.writeToFile());
5479 } else {
5480 reply->writeInt32(NO_ERROR);
5481 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005482 }
5483 return NO_ERROR;
5484 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005485 case 1026: { // Get layer tracing status
5486 reply->writeBool(mTracing.isEnabled());
5487 return NO_ERROR;
5488 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005489 // Is a DisplayColorSetting supported?
5490 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005491 const auto display = getDefaultDisplayDevice();
5492 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005493 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005494 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005495
5496 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5497 switch (setting) {
5498 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005499 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005500 break;
5501 case DisplayColorSetting::UNMANAGED:
5502 reply->writeBool(true);
5503 break;
5504 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005505 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005506 break;
5507 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005508 reply->writeBool(
5509 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005510 break;
5511 }
5512 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005513 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005514 // Is VrFlinger active?
5515 case 1028: {
5516 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005517 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005518 return NO_ERROR;
5519 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005520 // Set buffer size for SF tracing (value in KB)
5521 case 1029: {
5522 n = data.readInt32();
5523 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5524 ALOGW("Invalid buffer size: %d KB", n);
5525 reply->writeInt32(BAD_VALUE);
5526 return BAD_VALUE;
5527 }
5528
5529 ALOGD("Updating trace buffer to %d KB", n);
5530 mTracing.setBufferSize(n * 1024);
5531 reply->writeInt32(NO_ERROR);
5532 return NO_ERROR;
5533 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005534 // Is device color managed?
5535 case 1030: {
5536 reply->writeBool(useColorManagement);
5537 return NO_ERROR;
5538 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005539 // Override default composition data space
5540 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5541 // && adb shell stop zygote && adb shell start zygote
5542 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5543 // adb shell stop zygote && adb shell start zygote
5544 case 1031: {
5545 Mutex::Autolock _l(mStateLock);
5546 n = data.readInt32();
5547 if (n) {
5548 n = data.readInt32();
5549 if (n) {
5550 Dataspace dataspace = static_cast<Dataspace>(n);
5551 if (!validateCompositionDataspace(dataspace)) {
5552 return BAD_VALUE;
5553 }
5554 mDefaultCompositionDataspace = dataspace;
5555 }
5556 n = data.readInt32();
5557 if (n) {
5558 Dataspace dataspace = static_cast<Dataspace>(n);
5559 if (!validateCompositionDataspace(dataspace)) {
5560 return BAD_VALUE;
5561 }
5562 mWideColorGamutCompositionDataspace = dataspace;
5563 }
5564 } else {
5565 // restore composition data space.
5566 mDefaultCompositionDataspace = defaultCompositionDataspace;
5567 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5568 }
5569 return NO_ERROR;
5570 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005571 // Set trace flags
5572 case 1033: {
5573 n = data.readUint32();
5574 ALOGD("Updating trace flags to 0x%x", n);
5575 mTracing.setTraceFlags(n);
5576 reply->writeInt32(NO_ERROR);
5577 return NO_ERROR;
5578 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005579 case 1034: {
5580 // TODO(b/129297325): expose this via developer menu option
5581 n = data.readInt32();
5582 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005583 RefreshRateType type;
5584 {
5585 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5586 type = mDesiredActiveConfig.type;
5587 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005588 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005589 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005590 } else if (!n) {
5591 mRefreshRateOverlay.reset();
5592 }
5593 return NO_ERROR;
5594 }
Ady Abraham34392f72019-04-10 11:29:27 -07005595 case 1035: {
5596 n = data.readInt32();
5597 mDebugDisplayConfigSetByBackdoor = false;
5598 if (n >= 0) {
5599 const auto displayToken = getInternalDisplayToken();
5600 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5601 if (result != NO_ERROR) {
5602 return result;
5603 }
5604 mDebugDisplayConfigSetByBackdoor = true;
5605 }
5606 return NO_ERROR;
5607 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005608 }
5609 }
5610 return err;
5611}
5612
Steven Thomas6d8110b2017-08-31 18:24:21 -07005613void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005614 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005615 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005616}
5617
Ana Krulec7d1d6832018-12-27 11:10:09 -08005618void SurfaceFlinger::repaintEverythingForHWC() {
5619 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005620 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005621}
5622
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005623// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5624class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005625public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005626 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5627 ~WindowDisconnector() {
5628 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005629 }
5630
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005631private:
5632 ANativeWindow* mWindow;
5633 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005634};
5635
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005636status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005637 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5638 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005639 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005640 uint32_t reqWidth, uint32_t reqHeight,
5641 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005642 ISurfaceComposer::Rotation rotation,
5643 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005645
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005646 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005647
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005648 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5649
Chia-I Wu20261cb2018-08-23 12:55:44 -07005650 sp<DisplayDevice> display;
5651 {
5652 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005653
Chia-I Wu20261cb2018-08-23 12:55:44 -07005654 display = getDisplayDeviceLocked(displayToken);
5655 if (!display) return BAD_VALUE;
5656
Chia-I Wucb023152018-08-28 12:57:23 -07005657 // set the requested width/height to the logical display viewport size
5658 // by default
5659 if (reqWidth == 0 || reqHeight == 0) {
5660 reqWidth = uint32_t(display->getViewport().width());
5661 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005662 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005663 }
5664
Peiyong Lin0e003c92018-09-17 11:09:51 -07005665 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005666 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005667
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005668 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5669 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005670 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005671 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005672}
5673
chaviw93df2ea2019-04-30 16:45:12 -07005674static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5675 switch (colorMode) {
5676 case ColorMode::DISPLAY_P3:
5677 case ColorMode::BT2100_PQ:
5678 case ColorMode::BT2100_HLG:
5679 case ColorMode::DISPLAY_BT2020:
5680 return Dataspace::DISPLAY_P3;
5681 default:
5682 return Dataspace::V0_SRGB;
5683 }
5684}
5685
5686const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5687 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5688 if (displayToken) {
5689 return getDisplayDeviceLocked(displayToken);
5690 }
5691 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5692 // may not have a displayId.
5693 for (const auto& [token, display] : mDisplays) {
5694 if (display->getLayerStack() == displayOrLayerStack) {
5695 return display;
5696 }
5697 }
5698 return nullptr;
5699}
5700
5701status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5702 sp<GraphicBuffer>* outBuffer) {
5703 sp<DisplayDevice> display;
5704 uint32_t width;
5705 uint32_t height;
5706 ui::Transform::orientation_flags captureOrientation;
5707 {
5708 Mutex::Autolock _l(mStateLock);
5709 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5710 if (!display) {
5711 return BAD_VALUE;
5712 }
5713
5714 width = uint32_t(display->getViewport().width());
5715 height = uint32_t(display->getViewport().height());
5716
5717 captureOrientation = fromSurfaceComposerRotation(
5718 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005719 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5720 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5721 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5722 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5723 }
chaviw93df2ea2019-04-30 16:45:12 -07005724 *outDataspace =
5725 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5726 }
5727
5728 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5729 false /* captureSecureLayers */);
5730
5731 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5732 std::placeholders::_1);
5733 bool ignored = false;
5734 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5735 false /* useIdentityTransform */,
5736 ignored /* outCapturedSecureLayers */);
5737}
5738
Robert Carr866455f2019-04-02 16:28:26 -07005739status_t SurfaceFlinger::captureLayers(
5740 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5741 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5742 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5743 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005744 ATRACE_CALL();
5745
5746 class LayerRenderArea : public RenderArea {
5747 public:
Robert Carr578038f2018-03-09 12:25:24 -08005748 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005749 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5750 bool childrenOnly)
5751 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005752 mLayer(layer),
5753 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005754 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005755 mFlinger(flinger),
5756 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005757 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005758 Rect getBounds() const override {
5759 const Layer::State& layerState(mLayer->getDrawingState());
5760 return mLayer->getBufferSize(layerState);
5761 }
Marissa Wall61c58622018-07-18 10:12:20 -07005762 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005763 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005764 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005765 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005766 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005767 }
chaviwa76b2712017-09-20 12:02:26 -07005768 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005769 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005770 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005771 Rect getSourceCrop() const override {
5772 if (mCrop.isEmpty()) {
5773 return getBounds();
5774 } else {
5775 return mCrop;
5776 }
5777 }
Robert Carr578038f2018-03-09 12:25:24 -08005778 class ReparentForDrawing {
5779 public:
5780 const sp<Layer>& oldParent;
5781 const sp<Layer>& newParent;
5782
Vishnu Nair4351ad52019-02-11 14:13:02 -08005783 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5784 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005785 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005786 // Compute and cache the bounds for the new parent layer.
5787 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005788 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005789 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005790 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005791 };
5792
5793 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005794 const Rect sourceCrop = getSourceCrop();
5795 // no need to check rotation because there is none
5796 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5797 sourceCrop.height() != getReqHeight();
5798
Robert Carr578038f2018-03-09 12:25:24 -08005799 if (!mChildrenOnly) {
5800 mTransform = mLayer->getTransform().inverse();
5801 drawLayers();
5802 } else {
5803 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005804 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005805 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005806 bounds.getWidth(), bounds.getHeight(), 0,
5807 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005808
Vishnu Nair4351ad52019-02-11 14:13:02 -08005809 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005810 drawLayers();
5811 }
5812 }
chaviwa76b2712017-09-20 12:02:26 -07005813
chaviwa76b2712017-09-20 12:02:26 -07005814 private:
chaviw7206d492017-11-10 16:16:12 -08005815 const sp<Layer> mLayer;
5816 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005817
5818 // In the "childrenOnly" case we reparent the children to a screenshot
5819 // layer which has no properties set and which does not draw.
5820 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005821 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005822 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005823
5824 SurfaceFlinger* mFlinger;
5825 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005826 };
5827
Robert Carrc0df3122019-04-11 13:18:21 -07005828 int reqWidth = 0;
5829 int reqHeight = 0;
5830 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005831 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005832 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005833
Robert Carrc0df3122019-04-11 13:18:21 -07005834 {
5835 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005836
Robert Carrc0df3122019-04-11 13:18:21 -07005837 parent = fromHandle(layerHandleBinder);
5838 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5839 ALOGE("captureLayers called with an invalid or removed parent");
5840 return NAME_NOT_FOUND;
5841 }
5842
5843 const int uid = IPCThreadState::self()->getCallingUid();
5844 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5845 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5846 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5847 return PERMISSION_DENIED;
5848 }
5849
5850 if (sourceCrop.width() <= 0) {
5851 crop.left = 0;
5852 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5853 }
5854
5855 if (sourceCrop.height() <= 0) {
5856 crop.top = 0;
5857 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5858 }
5859 reqWidth = crop.width() * frameScale;
5860 reqHeight = crop.height() * frameScale;
5861
5862 for (const auto& handle : excludeHandles) {
5863 sp<Layer> excludeLayer = fromHandle(handle);
5864 if (excludeLayer != nullptr) {
5865 excludeLayers.emplace(excludeLayer);
5866 } else {
5867 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5868 return NAME_NOT_FOUND;
5869 }
5870 }
5871 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005872
Chia-I Wu20261cb2018-08-23 12:55:44 -07005873 // really small crop or frameScale
5874 if (reqWidth <= 0) {
5875 reqWidth = 1;
5876 }
5877 if (reqHeight <= 0) {
5878 reqHeight = 1;
5879 }
5880
Robert Carr866455f2019-04-02 16:28:26 -07005881 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5882 auto traverseLayers = [parent, childrenOnly,
5883 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005884 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5885 if (!layer->isVisible()) {
5886 return;
Robert Carr578038f2018-03-09 12:25:24 -08005887 } else if (childrenOnly && layer == parent.get()) {
5888 return;
chaviwa76b2712017-09-20 12:02:26 -07005889 }
Robert Carr866455f2019-04-02 16:28:26 -07005890
5891 sp<Layer> p = layer;
5892 while (p != nullptr) {
5893 if (excludeLayers.count(p) != 0) {
5894 return;
5895 }
5896 p = p->getParent();
5897 }
5898
chaviwa76b2712017-09-20 12:02:26 -07005899 visitor(layer);
5900 });
5901 };
Robert Carr108b2c72019-04-02 16:32:58 -07005902
5903 bool outCapturedSecureLayers = false;
5904 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5905 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005906}
5907
5908status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5909 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005910 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005911 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005912 bool useIdentityTransform,
5913 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005914 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005915
Peiyong Lin0e003c92018-09-17 11:09:51 -07005916 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005917 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5918 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005919 *outBuffer =
5920 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5921 static_cast<android_pixel_format>(reqPixelFormat), 1,
5922 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005923
Robert Carr108b2c72019-04-02 16:32:58 -07005924 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5925 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005926}
5927
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005928status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5929 TraverseLayersFunction traverseLayers,
5930 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005931 bool useIdentityTransform,
5932 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005933 // This mutex protects syncFd and captureResult for communication of the return values from the
5934 // main thread back to this Binder thread
5935 std::mutex captureMutex;
5936 std::condition_variable captureCondition;
5937 std::unique_lock<std::mutex> captureLock(captureMutex);
5938 int syncFd = -1;
5939 std::optional<status_t> captureResult;
5940
Robert Carr03480e22018-01-04 16:02:06 -08005941 const int uid = IPCThreadState::self()->getCallingUid();
5942 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5943
Dominik Laskowski8c001672018-05-30 16:52:06 -07005944 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005945 // If there is a refresh pending, bug out early and tell the binder thread to try again
5946 // after the refresh.
5947 if (mRefreshPending) {
5948 ATRACE_NAME("Skipping screenshot for now");
5949 std::unique_lock<std::mutex> captureLock(captureMutex);
5950 captureResult = std::make_optional<status_t>(EAGAIN);
5951 captureCondition.notify_one();
5952 return;
5953 }
5954
5955 status_t result = NO_ERROR;
5956 int fd = -1;
5957 {
5958 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005959 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005960 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005961 useIdentityTransform, forSystem, &fd,
5962 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005963 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005964 }
5965
5966 {
5967 std::unique_lock<std::mutex> captureLock(captureMutex);
5968 syncFd = fd;
5969 captureResult = std::make_optional<status_t>(result);
5970 captureCondition.notify_one();
5971 }
5972 });
5973
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005974 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005975 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005976 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005977 while (*captureResult == EAGAIN) {
5978 captureResult.reset();
5979 result = postMessageAsync(message);
5980 if (result != NO_ERROR) {
5981 return result;
5982 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005983 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005984 }
5985 result = *captureResult;
5986 }
5987
5988 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005989 sync_wait(syncFd, -1);
5990 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005991 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005992
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005993 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005994}
5995
chaviwa76b2712017-09-20 12:02:26 -07005996void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005997 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005998 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5999 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006000 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006001
chaviwa76b2712017-09-20 12:02:26 -07006002 const auto reqWidth = renderArea.getReqWidth();
6003 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006004 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006005 const auto transform = renderArea.getTransform();
6006 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006007
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006008 renderengine::DisplaySettings clientCompositionDisplay;
6009 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006010
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006011 // assume that bounds are never offset, and that they are the same as the
6012 // buffer bounds.
6013 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006014 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006015 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006016
6017 // Now take into account the rotation flag. We append a transform that
6018 // rotates the layer stack about the origin, then translate by buffer
6019 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006020 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006021 int displacementX = 0;
6022 int displacementY = 0;
6023 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6024 switch (rotation) {
6025 case ui::Transform::ROT_90:
6026 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006027 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006028 break;
6029 case ui::Transform::ROT_180:
6030 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006031 displacementY = renderArea.getBounds().getWidth();
6032 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006033 break;
6034 case ui::Transform::ROT_270:
6035 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006036 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006037 break;
6038 default:
6039 break;
6040 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006041
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006042 // We need to transform the clipping window into the right spot.
6043 // First, rotate the clipping rectangle by the rotation hint to get the
6044 // right orientation
6045 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6046 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6047 const vec4 rotClipTL = rotMatrix * clipTL;
6048 const vec4 rotClipBR = rotMatrix * clipBR;
6049 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6050 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6051 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6052 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6053
6054 // Now reposition the clipping rectangle with the displacement vector
6055 // computed above.
6056 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006057 clientCompositionDisplay.clip =
6058 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6059 newClipRight + displacementX, newClipBottom + displacementY);
6060
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006061 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006062 clientCompositionDisplay.globalTransform =
6063 clipTransform * clientCompositionDisplay.globalTransform;
6064
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006065 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6066 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006067
chaviw50da5042018-04-09 13:49:37 -07006068 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006069
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006070 renderengine::LayerSettings fillLayer;
6071 fillLayer.source.buffer.buffer = nullptr;
6072 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6073 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6074 fillLayer.alpha = half(alpha);
6075 clientCompositionLayers.push_back(fillLayer);
6076
6077 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006078 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006079 renderengine::LayerSettings layerSettings;
6080 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006081 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006082 if (prepared) {
6083 clientCompositionLayers.push_back(layerSettings);
6084 }
chaviwa76b2712017-09-20 12:02:26 -07006085 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006086
6087 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006088 // Use an empty fence for the buffer fence, since we just created the buffer so
6089 // there is no need for synchronization with the GPU.
6090 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006091 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006092 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006093 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006094 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006095
6096 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006097}
6098
chaviwa76b2712017-09-20 12:02:26 -07006099status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6100 TraverseLayersFunction traverseLayers,
6101 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006102 bool useIdentityTransform, bool forSystem,
6103 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006104 ATRACE_CALL();
6105
chaviwa76b2712017-09-20 12:02:26 -07006106 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006107 outCapturedSecureLayers =
6108 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006109 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006110
Robert Carr03480e22018-01-04 16:02:06 -08006111 // We allow the system server to take screenshots of secure layers for
6112 // use in situations like the Screen-rotation animation and place
6113 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006114 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006115 ALOGW("FB is protected: PERMISSION_DENIED");
6116 return PERMISSION_DENIED;
6117 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006118 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006119 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006120}
6121
chaviw95ef3c42019-02-14 10:55:09 -08006122void SurfaceFlinger::setInputWindowsFinished() {
6123 Mutex::Autolock _l(mStateLock);
6124
6125 mPendingSyncInputWindows = false;
6126 mTransactionCV.broadcast();
6127}
chaviw5f21a5e2019-02-14 10:00:34 -08006128
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006129// ---------------------------------------------------------------------------
6130
Dan Stoza412903f2017-04-27 13:42:17 -07006131void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6132 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006133}
6134
Dan Stoza412903f2017-04-27 13:42:17 -07006135void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6136 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006137}
6138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006139void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006140 const LayerVector::Visitor& visitor) {
6141 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006142 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006143 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006144 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006145 continue;
6146 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006147 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006148 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006149 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006150 return;
6151 }
chaviwa76b2712017-09-20 12:02:26 -07006152 if (!layer->isVisible()) {
6153 return;
6154 }
6155 visitor(layer);
6156 });
6157 }
6158}
6159
Dominik Laskowski22488f62019-03-28 09:53:04 -07006160void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6161 const std::vector<int32_t>& allowedConfigs) {
6162 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006163 return;
6164 }
6165
6166 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006167 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006168
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006169 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006170 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006171 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006172 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006173 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006174 setDesiredActiveConfig(
6175 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006176 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006177 }
6178 }
Ady Abraham838de062019-02-04 10:24:03 -08006179}
6180
Dominik Laskowski22488f62019-03-28 09:53:04 -07006181status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006182 const std::vector<int32_t>& allowedConfigs) {
6183 ATRACE_CALL();
6184
Dominik Laskowski22488f62019-03-28 09:53:04 -07006185 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006186 return BAD_VALUE;
6187 }
6188
Ady Abraham34392f72019-04-10 11:29:27 -07006189 if (mDebugDisplayConfigSetByBackdoor) {
6190 // ignore this request as config is overridden by backdoor
6191 return NO_ERROR;
6192 }
6193
Ady Abraham838de062019-02-04 10:24:03 -08006194 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006195 const auto display = getDisplayDeviceLocked(displayToken);
6196 if (!display) {
6197 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6198 displayToken.get());
6199 } else if (display->isVirtual()) {
6200 ALOGW("Attempt to set allowed display configs for virtual display");
6201 } else {
6202 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6203 }
Ady Abraham838de062019-02-04 10:24:03 -08006204 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006205
Ady Abraham838de062019-02-04 10:24:03 -08006206 return NO_ERROR;
6207}
6208
Dominik Laskowski22488f62019-03-28 09:53:04 -07006209status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006210 std::vector<int32_t>* outAllowedConfigs) {
6211 ATRACE_CALL();
6212
Dominik Laskowski22488f62019-03-28 09:53:04 -07006213 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006214 return BAD_VALUE;
6215 }
6216
Dominik Laskowski22488f62019-03-28 09:53:04 -07006217 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006218
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006219 const auto display = getDisplayDeviceLocked(displayToken);
6220 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006221 return NAME_NOT_FOUND;
6222 }
6223
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006224 if (display->isPrimary()) {
6225 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6226 }
6227
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006228 return NO_ERROR;
6229}
6230
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006231void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006232 mFlinger->setInputWindowsFinished();
6233}
6234
Robert Carrc0df3122019-04-11 13:18:21 -07006235sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6236 BBinder *b = handle->localBinder();
6237 if (b == nullptr) {
6238 return nullptr;
6239 }
6240 auto it = mLayersByLocalBinderToken.find(b);
6241 if (it != mLayersByLocalBinderToken.end()) {
6242 return it->second.promote();
6243 }
6244 return nullptr;
6245}
6246
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006247} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006248
Mathias Agopian3f844832013-08-07 21:24:32 -07006249#if defined(__gl_h_)
6250#error "don't include gl/gl.h in this file"
6251#endif
6252
6253#if defined(__gl2_h_)
6254#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006255#endif