blob: 604ad34ebda1fb6e93a5bb3332557c780f5c7d32 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
52
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070054#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080055#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080056#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080057#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070059#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <ui/ColorSpace.h>
61#include <ui/DebugUtils.h>
62#include <ui/DisplayInfo.h>
63#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070064#include <ui/GraphicBufferAllocator.h>
65#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070066#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070068#include <utils/String16.h>
69#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070070#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080071#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070072#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopian921e6ac2012-07-23 23:11:29 -070074#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070075#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Robert Carr578038f2018-03-09 12:25:24 -080077#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070078#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070079#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020082#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080084#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070086#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080087#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070088#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070089#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070092#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Steven Thomasb02664d2017-07-26 18:48:28 -070094#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070095#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070096#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070097#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070098#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070099#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700100#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700102#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103#include "Scheduler/EventControlThread.h"
104#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700105#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700106#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700107#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700108#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800109#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700110
Mathias Agopianff2ed702013-09-01 21:36:12 -0700111#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700112
David Sodman7e4ae112018-02-09 15:02:28 -0800113#include "android-base/stringprintf.h"
114
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800116#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
117#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700118#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900119#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
chaviw1d044282017-09-27 12:19:28 -0700121#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700125
Jaesoo Lee43518572017-01-23 19:03:16 +0900126using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900128using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800129
Ady Abraham8532d012019-05-08 14:50:56 -0700130using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800131using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700132using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700133using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800134using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700135using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700136using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900137
Steven Thomasb02664d2017-07-26 18:48:28 -0700138namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700139
140#pragma clang diagnostic push
141#pragma clang diagnostic error "-Wswitch-enum"
142
143bool isWideColorMode(const ColorMode colorMode) {
144 switch (colorMode) {
145 case ColorMode::DISPLAY_P3:
146 case ColorMode::ADOBE_RGB:
147 case ColorMode::DCI_P3:
148 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700149 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700150 case ColorMode::BT2100_PQ:
151 case ColorMode::BT2100_HLG:
152 return true;
153 case ColorMode::NATIVE:
154 case ColorMode::STANDARD_BT601_625:
155 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
156 case ColorMode::STANDARD_BT601_525:
157 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
158 case ColorMode::STANDARD_BT709:
159 case ColorMode::SRGB:
160 return false;
161 }
162 return false;
163}
164
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700165bool isHdrColorMode(const ColorMode colorMode) {
166 switch (colorMode) {
167 case ColorMode::BT2100_PQ:
168 case ColorMode::BT2100_HLG:
169 return true;
170 case ColorMode::DISPLAY_P3:
171 case ColorMode::ADOBE_RGB:
172 case ColorMode::DCI_P3:
173 case ColorMode::BT2020:
174 case ColorMode::DISPLAY_BT2020:
175 case ColorMode::NATIVE:
176 case ColorMode::STANDARD_BT601_625:
177 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
178 case ColorMode::STANDARD_BT601_525:
179 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
180 case ColorMode::STANDARD_BT709:
181 case ColorMode::SRGB:
182 return false;
183 }
184 return false;
185}
186
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700187ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
188 switch (rotation) {
189 case ISurfaceComposer::eRotateNone:
190 return ui::Transform::ROT_0;
191 case ISurfaceComposer::eRotate90:
192 return ui::Transform::ROT_90;
193 case ISurfaceComposer::eRotate180:
194 return ui::Transform::ROT_180;
195 case ISurfaceComposer::eRotate270:
196 return ui::Transform::ROT_270;
197 }
198 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
199 return ui::Transform::ROT_0;
200}
201
Peiyong Linfca547f2018-07-09 13:03:33 -0700202#pragma clang diagnostic pop
203
Steven Thomasb02664d2017-07-26 18:48:28 -0700204class ConditionalLock {
205public:
206 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
207 if (lock) {
208 mMutex.lock();
209 }
210 }
211 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
212private:
213 Mutex& mMutex;
214 bool mLocked;
215};
Peiyong Linfca547f2018-07-09 13:03:33 -0700216
Peiyong Lin9d846a52018-11-05 13:18:20 -0800217// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
218bool validateCompositionDataspace(Dataspace dataspace) {
219 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
220}
221
Steven Thomasb02664d2017-07-26 18:48:28 -0700222} // namespace anonymous
223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224// ---------------------------------------------------------------------------
225
Mathias Agopian99b49842011-06-27 16:05:52 -0700226const String16 sHardwareTest("android.permission.HARDWARE_TEST");
227const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
228const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
229const String16 sDump("android.permission.DUMP");
230
231// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700232int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700233bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800234uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800235bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800236bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800237int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600238bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700239int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700240bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700241bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700242Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
244Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
245ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700246
Kalle Raitaa099a242017-01-11 11:17:29 -0800247std::string getHwcServiceName() {
248 char value[PROPERTY_VALUE_MAX] = {};
249 property_get("debug.sf.hwc_service_name", value, "default");
250 ALOGI("Using HWComposer service: '%s'", value);
251 return std::string(value);
252}
253
254bool useTrebleTestingOverride() {
255 char value[PROPERTY_VALUE_MAX] = {};
256 property_get("debug.sf.treble_testing_override", value, "false");
257 ALOGI("Treble testing override: '%s'", value);
258 return std::string(value) == "true";
259}
260
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
262 switch(displayColorSetting) {
263 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800265 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700268 return std::string("Enhanced");
269 default:
270 return std::string("Unknown ") +
271 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800273}
274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800276
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700277SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
278 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700279 mInterceptor(mFactory.createSurfaceInterceptor(this)),
280 mTimeStats(mFactory.createTimeStats()),
281 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700282 mCompositionEngine(mFactory.createCompositionEngine()),
283 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800284
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700285SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 mDefaultCompositionDataspace =
306 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700307 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
308 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 defaultCompositionDataspace = mDefaultCompositionDataspace;
310 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
311 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
312 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
313 wideColorGamutCompositionPixelFormat =
314 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700315
Yichi Chenda901bf2019-06-28 14:58:27 +0800316 mColorSpaceAgnosticDataspace =
317 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
322 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
323 switch (tmpPrimaryDisplayOrientation) {
324 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700325 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700328 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800338
Sundong Ahn85131bd2019-02-18 15:51:53 +0900339 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 // debugging stuff...
342 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700345 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 property_get("debug.sf.showupdates", value, "0");
348 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700350 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000351
352 // DDMS debugging deprecated (b/120782499)
353 property_get("debug.sf.ddms", value, "0");
354 int debugDdms = atoi(value);
355 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700356
357 property_get("debug.sf.disable_backpressure", value, "0");
358 mPropagateBackpressure = !atoi(value);
359 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700360
Ady Abraham4658e112019-07-22 13:07:26 -0700361 property_get("debug.sf.enable_gl_backpressure", value, "0");
362 mPropagateBackpressureClientComposition = atoi(value);
363 ALOGI_IF(mPropagateBackpressureClientComposition,
364 "Enabling backpressure propagation for Client Composition");
365
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800366 property_get("debug.sf.enable_hwc_vds", value, "0");
367 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800368 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800370 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800371 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700373
Yiwei Zhang243b3782018-05-15 17:40:04 -0700374 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
376 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
377
Ana Krulece5a06e02019-03-06 17:09:03 -0800378 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800379 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800380
381 int int_value = atoi(value);
382 if (int_value) {
383 mUseSmart90ForVideo = true;
384 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800385
Dan Stozaec460082018-12-17 15:35:09 -0800386 property_get("debug.sf.luma_sampling", value, "1");
387 mLumaSampling = atoi(value);
388
Romain Guy11d63f42017-07-20 12:47:14 -0700389 // We should be reading 'persist.sys.sf.color_saturation' here
390 // but since /data may be encrypted, we need to wait until after vold
391 // comes online to attempt to read the property. The property is
392 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800393
394 if (useTrebleTestingOverride()) {
395 // Without the override SurfaceFlinger cannot connect to HIDL
396 // services that are not listed in the manifests. Considered
397 // deriving the setting from the set service name, but it
398 // would be brittle if the name that's not 'default' is used
399 // for production purposes later on.
400 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
401 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402}
403
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404void SurfaceFlinger::onFirstRef()
405{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800406 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407}
408
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700409SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800410
Dan Stozac7014012014-02-14 15:03:43 -0800411void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800412{
413 // the window manager died on us. prepare its eulogy.
414
Andy McFadden13a082e2012-08-24 10:16:42 -0700415 // restore initial conditions (default device unblank, etc)
416 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417
418 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700419 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Robert Carr1db73f62016-12-21 12:58:51 -0800422static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700423 status_t err = client->initCheck();
424 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 }
Robert Carr1db73f62016-12-21 12:58:51 -0800427 return nullptr;
428}
429
430sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
431 return initClient(new Client(this));
432}
433
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700434sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
435 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436{
437 class DisplayToken : public BBinder {
438 sp<SurfaceFlinger> flinger;
439 virtual ~DisplayToken() {
440 // no more references, this display must be terminated
441 Mutex::Autolock _l(flinger->mStateLock);
442 flinger->mCurrentState.displays.removeItem(this);
443 flinger->setTransactionFlags(eDisplayTransactionNeeded);
444 }
445 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700446 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447 : flinger(flinger) {
448 }
449 };
450
451 sp<BBinder> token = new DisplayToken(this);
452
453 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454 // Display ID is assigned when virtual display is allocated by HWC.
455 DisplayDeviceState state;
456 state.isSecure = secure;
457 state.displayName = displayName;
458 mCurrentState.displays.add(token, state);
459 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 return token;
461}
462
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700463void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700464 Mutex::Autolock _l(mStateLock);
465
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
467 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700468 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 return;
470 }
471
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
473 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 ALOGE("destroyDisplay called for non-virtual display");
475 return;
476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 mInterceptor->saveDisplayDeletion(state.sequenceId);
478 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 setTransactionFlags(eDisplayTransactionNeeded);
480}
481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
483 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485 const auto internalDisplayId = getInternalDisplayIdLocked();
486 if (!internalDisplayId) {
487 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 }
489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490 std::vector<PhysicalDisplayId> displayIds;
491 displayIds.reserve(mPhysicalDisplayTokens.size());
492 displayIds.push_back(internalDisplayId->value);
493
494 for (const auto& [id, token] : mPhysicalDisplayTokens) {
495 if (id != *internalDisplayId) {
496 displayIds.push_back(id.value);
497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 return displayIds;
501}
502
503sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
504 Mutex::Autolock lock(mStateLock);
505 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
Ady Abraham37965d42018-11-01 13:43:32 -0700508status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
509 if (!outGetColorManagement) {
510 return BAD_VALUE;
511 }
512 *outGetColorManagement = useColorManagement;
513 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700514}
515
Lloyd Pique441d5042018-10-18 16:49:51 -0700516HWComposer& SurfaceFlinger::getHwComposer() const {
517 return mCompositionEngine->getHwComposer();
518}
519
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700520renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
521 return mCompositionEngine->getRenderEngine();
522}
523
Lloyd Pique70d91362018-10-18 16:02:55 -0700524compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
525 return *mCompositionEngine.get();
526}
527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528void SurfaceFlinger::bootFinished()
529{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700530 if (mStartPropertySetThread->join() != NO_ERROR) {
531 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800532 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533 const nsecs_t now = systemTime();
534 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000535 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536
537 // wait patiently for the window manager death
538 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700539 mWindowManager = defaultServiceManager()->getService(name);
540 if (mWindowManager != 0) {
541 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700542 }
Robert Carr720e5062018-07-30 17:45:14 -0700543 sp<IBinder> input(defaultServiceManager()->getService(
544 String16("inputflinger")));
545 if (input == nullptr) {
546 ALOGE("Failed to link to input service");
547 } else {
548 mInputFlinger = interface_cast<IInputFlinger>(input);
549 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550
Steven Thomas050b2c82017-03-06 11:45:16 -0800551 if (mVrFlinger) {
552 mVrFlinger->OnBootFinished();
553 }
554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700556 // formerly we would just kill the process, but we now ask it to exit so it
557 // can choose where to stop the animation.
558 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700559
560 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
561 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
562 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700563
Ana Krulecbd6654b2019-02-15 15:18:15 -0800564 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800565 readPersistentProperties();
566 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800567
Ady Abraham97d04232019-03-05 19:48:12 -0800568 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700569 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700570 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800571
Dominik Laskowski22488f62019-03-28 09:53:04 -0700572 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800573 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800574 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800575 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800576 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800577 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800578}
579
Dan Stoza436ccf32018-06-21 12:10:12 -0700580uint32_t SurfaceFlinger::getNewTexture() {
581 {
582 std::lock_guard lock(mTexturePoolMutex);
583 if (!mTexturePool.empty()) {
584 uint32_t name = mTexturePool.back();
585 mTexturePool.pop_back();
586 ATRACE_INT("TexturePoolSize", mTexturePool.size());
587 return name;
588 }
589
590 // The pool was too small, so increase it for the future
591 ++mTexturePoolSize;
592 }
593
594 // The pool was empty, so we need to get a new texture name directly using a
595 // blocking call to the main thread
596 uint32_t name = 0;
597 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
598 return name;
599}
600
Mathias Agopian3f844832013-08-07 21:24:32 -0700601void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700602 std::lock_guard lock(mTexturePoolMutex);
603 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
604 // to actually delete this or not based on mTexturePoolSize
605 mTexturePool.push_back(texture);
606 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700607}
608
Wei Wangf9b05ee2017-07-19 20:59:39 -0700609// Do not call property_set on main thread which will be blocked by init
610// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700612 ALOGI( "SurfaceFlinger's main thread ready to run. "
613 "Initializing graphics H/W...");
614
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700615 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900616
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800619 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700620 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
621 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800622 auto resyncCallback =
623 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800624
Ana Krulecc2870422019-01-29 19:00:58 -0800625 mAppConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700626 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700627 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800628 resyncCallback,
629 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700630 mSfConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700631 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700632 mPhaseOffsets->getOffsetThresholdForNextVsync(),
633 resyncCallback, [this](nsecs_t timestamp) {
634 mInterceptor->saveVSyncEvent(timestamp);
635 });
Ana Krulecc2870422019-01-29 19:00:58 -0800636
637 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700638
639 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
640 mPhaseOffsets->getCurrentOffsets());
Ana Krulecc2870422019-01-29 19:00:58 -0800641
Kevin DuBois413287f2019-02-25 08:46:47 -0800642 mRegionSamplingThread =
643 new RegionSamplingThread(*this, *mScheduler,
644 RegionSamplingThread::EnvironmentTimingTunables());
645
Steven Thomasb02664d2017-07-26 18:48:28 -0700646 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700647 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700648 renderEngineFeature |= (useColorManagement ?
649 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700650 renderEngineFeature |= (useContextPriority ?
651 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700652 renderEngineFeature |=
653 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
654 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700655
656 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800657 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700658 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700659 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800660 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700661
662 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
663 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700664 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
665 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800666 // Process any initial hotplug and resulting display changes.
667 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700668 const auto display = getDefaultDisplayDeviceLocked();
669 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700670 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800672
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700674 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700675 // This callback is called from the vr flinger dispatch thread. We
676 // need to call signalTransaction(), which requires holding
677 // mStateLock when we're not on the main thread. Acquiring
678 // mStateLock from the vr flinger dispatch thread might trigger a
679 // deadlock in surface flinger (see b/66916578), so post a message
680 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700681 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700682 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
683 mVrFlingerRequestsDisplay = requestDisplay;
684 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700685 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800686 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700687 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
688 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700689 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 .value_or(0),
691 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800692 if (!mVrFlinger) {
693 ALOGE("Failed to start vrflinger");
694 }
695 }
696
Mathias Agopian92a979a2012-08-02 18:32:23 -0700697 // initialize our drawing state
698 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700699
Andy McFadden13a082e2012-08-24 10:16:42 -0700700 // set initial conditions (e.g. unblank default device)
701 initializeDisplays();
702
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700703 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700704
Wei Wangf9b05ee2017-07-19 20:59:39 -0700705 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700706
707 const bool presentFenceReliable =
708 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
709 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700710
711 if (mStartPropertySetThread->Start() != NO_ERROR) {
712 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800713 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800714
Alec Mouri93bc83d2019-04-17 14:47:43 -0700715 mScheduler->setChangeRefreshRateCallback(
716 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
717 Mutex::Autolock lock(mStateLock);
718 setRefreshRateTo(type, event);
719 });
Alec Mouri7f015182019-07-11 13:56:22 -0700720 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
721 Mutex::Autolock lock(mStateLock);
722 const auto display = getDefaultDisplayDeviceLocked();
723 if (!display) {
724 // If we don't have a default display the fallback to the default
725 // refresh rate type
726 return RefreshRateType::DEFAULT;
727 }
728
729 const int configId = display->getActiveConfig();
730 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
731 if (refresh && refresh->configId == configId) {
732 return type;
733 }
734 }
735 // This should never happen, but just gracefully fallback to default.
736 return RefreshRateType::DEFAULT;
737 });
Alec Mouridc28b372019-04-18 21:17:13 -0700738 mScheduler->setGetVsyncPeriodCallback([this] {
739 Mutex::Autolock lock(mStateLock);
740 return getVsyncPeriod();
741 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700742
Dominik Laskowski22488f62019-03-28 09:53:04 -0700743 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
744 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800745
Dan Stoza9e56aa02015-11-02 13:00:03 -0800746 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700747}
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700750 Mutex::Autolock _l(mStateLock);
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752 char value[PROPERTY_VALUE_MAX];
753
754 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700756 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800757 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100758
759 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700760 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800761
762 property_get("persist.sys.sf.color_mode", value, "0");
763 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700764}
765
Mathias Agopiana67e4182012-06-19 17:26:12 -0700766void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800767 // Start boot animation service by setting a property mailbox
768 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800770 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700771 if (mStartPropertySetThread->join() != NO_ERROR) {
772 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800773 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700774}
775
Mathias Agopian875d8e12013-06-07 15:35:48 -0700776size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700777 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700778}
779
Mathias Agopian875d8e12013-06-07 15:35:48 -0700780size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700781 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700782}
783
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800784// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800785
Jamie Gennis582270d2011-08-17 18:19:00 -0700786bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800788 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800789 return authenticateSurfaceTextureLocked(bufferProducer);
790}
791
792bool SurfaceFlinger::authenticateSurfaceTextureLocked(
793 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800794 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800795 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800796}
797
Brian Anderson6b376712017-04-04 10:51:39 -0700798status_t SurfaceFlinger::getSupportedFrameTimestamps(
799 std::vector<FrameEvent>* outSupported) const {
800 *outSupported = {
801 FrameEvent::REQUESTED_PRESENT,
802 FrameEvent::ACQUIRE,
803 FrameEvent::LATCH,
804 FrameEvent::FIRST_REFRESH_START,
805 FrameEvent::LAST_REFRESH_START,
806 FrameEvent::GPU_COMPOSITION_DONE,
807 FrameEvent::DEQUEUE_READY,
808 FrameEvent::RELEASE,
809 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700810 ConditionalLock _l(mStateLock,
811 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700812 if (!getHwComposer().hasCapability(
813 HWC2::Capability::PresentFenceIsNotReliable)) {
814 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
815 }
816 return NO_ERROR;
817}
818
Dominik Laskowski22488f62019-03-28 09:53:04 -0700819status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
820 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700821 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 return BAD_VALUE;
823 }
824
Dominik Laskowski22488f62019-03-28 09:53:04 -0700825 Mutex::Autolock lock(mStateLock);
826
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800827 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700828 if (!displayId) {
829 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700830 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 // TODO: Not sure if display density should handled by SF any longer
833 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700834 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700836 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800837 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700838 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 }
840 return density;
841 }
842 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700845 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 return getDensityFromProperty("ro.sf.lcd_density"); }
847 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 DisplayInfo info = DisplayInfo();
853
Dan Stoza9e56aa02015-11-02 13:00:03 -0800854 float xdpi = hwConfig->getDpiX();
855 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700856
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700857 info.w = hwConfig->getWidth();
858 info.h = hwConfig->getHeight();
859 // Default display viewport to display width and height
860 info.viewportW = info.w;
861 info.viewportH = info.h;
862
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800863 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 // The density of the device is provided by a build property
865 float density = Density::getBuildDensity() / 160.0f;
866 if (density == 0) {
867 // the build doesn't provide a density -- this is wrong!
868 // use xdpi instead
869 ALOGE("ro.sf.lcd_density must be defined as a build property");
870 density = xdpi / 160.0f;
871 }
872 if (Density::getEmuDensity()) {
873 // if "qemu.sf.lcd_density" is specified, it overrides everything
874 xdpi = ydpi = density = Density::getEmuDensity();
875 density /= 160.0f;
876 }
877 info.density = density;
878
879 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700880 const auto display = getDefaultDisplayDeviceLocked();
881 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700882
883 // This is for screenrecord
884 const Rect viewport = display->getViewport();
885 if (viewport.isValid()) {
886 info.viewportW = uint32_t(viewport.getWidth());
887 info.viewportH = uint32_t(viewport.getHeight());
888 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 } else {
890 // TODO: where should this value come from?
891 static const int TV_DENSITY = 213;
892 info.density = TV_DENSITY / 160.0f;
893 info.orientation = 0;
894 }
895
Dan Stoza7f7da322014-05-02 15:26:25 -0700896 info.xdpi = xdpi;
897 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800898 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700899 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
900 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
901 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800902
Andy McFadden91b2ca82014-06-13 14:04:23 -0700903 // This is how far in advance a buffer must be queued for
904 // presentation at a given time. If you want a buffer to appear
905 // on the screen at time N, you must submit the buffer before
906 // (N - presentationDeadline).
907 //
908 // Normally it's one full refresh period (to give SF a chance to
909 // latch the buffer), but this can be reduced by configuring a
910 // DispSync offset. Any additional delays introduced by the hardware
911 // composer or panel must be accounted for here.
912 //
913 // We add an additional 1ms to allow for processing time and
914 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700915 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700916
917 // All non-virtual displays are currently considered secure.
918 info.secure = true;
919
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800920 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700921 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800922 std::swap(info.w, info.h);
923 }
924
Michael Wright28f24d02016-07-12 13:30:53 -0700925 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700926 }
927
Dan Stoza7f7da322014-05-02 15:26:25 -0700928 return NO_ERROR;
929}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700930
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700931status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
932 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700933 return BAD_VALUE;
934 }
935
Ana Krulecc2870422019-01-29 19:00:58 -0800936 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return NO_ERROR;
938}
939
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700940int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
941 const auto display = getDisplayDevice(displayToken);
942 if (!display) {
943 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800944 return BAD_VALUE;
945 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700948}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700949
Ady Abraham03b02dd2019-03-21 15:40:11 -0700950void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800952
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800954 // config twice. However event generation config might have changed so we need to update it
955 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800956 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700957 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
958 mDesiredActiveConfig = info;
959 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960
961 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 // This will trigger HWC refresh without resetting the idle timer.
963 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700964 // Start receiving vsync samples now, so that we can detect a period
965 // switch.
966 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700967 // As we called to set period, we will call to onRefreshRateChangeCompleted once
968 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700969 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700970 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700971 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 mDesiredActiveConfigChanged = true;
974 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700975
976 if (mRefreshRateOverlay) {
977 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979}
980
981status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
982 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800983
984 std::vector<int32_t> allowedConfig;
985 allowedConfig.push_back(mode);
986
987 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988}
989
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990void SurfaceFlinger::setActiveConfigInternal() {
991 ATRACE_CALL();
992
Dominik Laskowski22488f62019-03-28 09:53:04 -0700993 const auto display = getDefaultDisplayDeviceLocked();
994 if (!display) {
995 return;
996 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997
Dominik Laskowski22488f62019-03-28 09:53:04 -0700998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
1000
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001001 display->setActiveConfig(mUpcomingActiveConfig.configId);
1002
Alec Mouri754c98a2019-03-18 18:53:42 -07001003 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001004 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
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);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001021 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001022}
1023
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001025 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001027 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001029 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 return true;
1031 }
1032
1033 // We received the present fence from the HWC, so we assume it successfully updated
1034 // the config, hence we update SF.
1035 mCheckPendingFence = false;
1036 setActiveConfigInternal();
1037 }
1038
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001039 // Store the local variable to release the lock.
1040 ActiveConfigInfo desiredActiveConfig;
1041 {
1042 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 if (!mDesiredActiveConfigChanged) {
1044 return false;
1045 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001046 desiredActiveConfig = mDesiredActiveConfig;
1047 }
1048
Dominik Laskowski22488f62019-03-28 09:53:04 -07001049 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1051 // display is not valid or we are already in the requested mode
1052 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001053 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001055 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056
Ady Abraham838de062019-02-04 10:24:03 -08001057 // Desired active config was set, it is different than the config currently in use, however
1058 // allowed configs might have change by the time we process the refresh.
1059 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001060 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001061 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001062 return false;
1063 }
Alec Mouri7f015182019-07-11 13:56:22 -07001064
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065 mUpcomingActiveConfig = desiredActiveConfig;
1066 const auto displayId = display->getId();
1067 LOG_ALWAYS_FATAL_IF(!displayId);
1068
1069 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1070 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1071
1072 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001073 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001074 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001075 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001076}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1079 Vector<ColorMode>* outColorModes) {
1080 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001081 return BAD_VALUE;
1082 }
1083
Peiyong Lina52f0292018-03-14 17:26:31 -07001084 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001085 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001086 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001087 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1088
1089 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1090 if (!displayId) {
1091 return NAME_NOT_FOUND;
1092 }
1093
Dominik Laskowski075d3172018-05-24 15:50:06 -07001094 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001095 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001096 }
Michael Wright28f24d02016-07-12 13:30:53 -07001097 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001098
1099 // If it's built-in display and the configuration claims it's not wide color capable,
1100 // filter out all wide color modes. The typical reason why this happens is that the
1101 // hardware is not good enough to support GPU composition of wide color, and thus the
1102 // OEMs choose to disable this capability.
1103 if (isInternalDisplay && !hasWideColorDisplay) {
1104 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1105 isWideColorMode);
1106 } else {
1107 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1108 }
Michael Wright28f24d02016-07-12 13:30:53 -07001109
1110 return NO_ERROR;
1111}
1112
Daniel Solomon42d04562019-01-20 21:03:19 -08001113status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1114 ui::DisplayPrimaries &primaries) {
1115 if (!displayToken) {
1116 return BAD_VALUE;
1117 }
1118
1119 // Currently we only support this API for a single internal display.
1120 if (getInternalDisplayToken() != displayToken) {
1121 return BAD_VALUE;
1122 }
1123
1124 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1125 return NO_ERROR;
1126}
1127
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1129 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001130 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001131 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001132 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001133}
1134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001136 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 Vector<ColorMode> modes;
1138 getDisplayColorModes(displayToken, &modes);
1139 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1140 if (mode < ColorMode::NATIVE || !exists) {
1141 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1142 decodeColorMode(mode).c_str(), mode, displayToken.get());
1143 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001144 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001145 const auto display = getDisplayDevice(displayToken);
1146 if (!display) {
1147 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1148 decodeColorMode(mode).c_str(), mode, displayToken.get());
1149 } else if (display->isVirtual()) {
1150 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1151 decodeColorMode(mode).c_str(), mode);
1152 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001153 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1154 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155 }
1156 }));
1157
Michael Wright28f24d02016-07-12 13:30:53 -07001158 return NO_ERROR;
1159}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001160
Svetoslavd85084b2014-03-20 10:28:31 -07001161status_t SurfaceFlinger::clearAnimationFrameStats() {
1162 Mutex::Autolock _l(mStateLock);
1163 mAnimFrameTracker.clearStats();
1164 return NO_ERROR;
1165}
1166
1167status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1168 Mutex::Autolock _l(mStateLock);
1169 mAnimFrameTracker.getStats(outStats);
1170 return NO_ERROR;
1171}
1172
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1174 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001175 Mutex::Autolock _l(mStateLock);
1176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001177 const auto display = getDisplayDeviceLocked(displayToken);
1178 if (!display) {
1179 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001180 return BAD_VALUE;
1181 }
1182
Peiyong Linfb069302018-04-25 14:34:31 -07001183 // At this point the DisplayDeivce should already be set up,
1184 // meaning the luminance information is already queried from
1185 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001186 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001187 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1188 capabilities.getDesiredMaxLuminance(),
1189 capabilities.getDesiredMaxAverageLuminance(),
1190 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001191
1192 return NO_ERROR;
1193}
1194
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001195status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1196 ui::PixelFormat* outFormat,
1197 ui::Dataspace* outDataspace,
1198 uint8_t* outComponentMask) const {
1199 if (!outFormat || !outDataspace || !outComponentMask) {
1200 return BAD_VALUE;
1201 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001202 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001203 if (!display || !display->getId()) {
1204 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1205 return BAD_VALUE;
1206 }
1207 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1208 outDataspace, outComponentMask);
1209}
1210
Kevin DuBois74e53772018-11-19 10:52:38 -08001211status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1212 bool enable, uint8_t componentMask,
1213 uint64_t maxFrames) const {
1214 const auto display = getDisplayDevice(displayToken);
1215 if (!display || !display->getId()) {
1216 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1217 return BAD_VALUE;
1218 }
1219
1220 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1221 componentMask, maxFrames);
1222}
1223
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001224status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1225 uint64_t maxFrames, uint64_t timestamp,
1226 DisplayedFrameStats* outStats) const {
1227 const auto display = getDisplayDevice(displayToken);
1228 if (!display || !display->getId()) {
1229 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1230 return BAD_VALUE;
1231 }
1232
1233 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1234 outStats);
1235}
1236
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001237status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1238 if (!outSupported) {
1239 return BAD_VALUE;
1240 }
1241 *outSupported = getRenderEngine().supportsProtectedContent();
1242 return NO_ERROR;
1243}
1244
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001245status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1246 bool* outIsWideColorDisplay) const {
1247 if (!displayToken || !outIsWideColorDisplay) {
1248 return BAD_VALUE;
1249 }
1250 Mutex::Autolock _l(mStateLock);
1251 const auto display = getDisplayDeviceLocked(displayToken);
1252 if (!display) {
1253 return BAD_VALUE;
1254 }
Peiyong Linff84a152019-05-17 18:36:19 -07001255
1256 // Use hasWideColorDisplay to override built-in display.
1257 const auto displayId = display->getId();
1258 if (displayId && displayId == getInternalDisplayIdLocked()) {
1259 *outIsWideColorDisplay = hasWideColorDisplay;
1260 return NO_ERROR;
1261 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001262 *outIsWideColorDisplay = display->hasWideColorGamut();
1263 return NO_ERROR;
1264}
1265
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001266status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001267 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001268 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001269
Chia-I Wu90f669f2017-10-05 14:24:41 -07001270 if (mInjectVSyncs == enable) {
1271 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001272 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273
Ana Krulecc2870422019-01-29 19:00:58 -08001274 auto resyncCallback =
1275 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001276
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001277 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001278 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001279 if (enable) {
1280 ALOGV("VSync Injections enabled");
1281 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001282 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001283 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001284 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001285 impl::EventThread::InterceptVSyncsCallback(),
1286 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001287 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001288 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001289 } else {
1290 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001291 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1292 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001293 }
1294
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001295 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001296 }));
1297
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001298 return NO_ERROR;
1299}
1300
1301status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001302 Mutex::Autolock _l(mStateLock);
1303
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001304 if (!mInjectVSyncs) {
1305 ALOGE("VSync Injections not enabled");
1306 return BAD_VALUE;
1307 }
1308 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1309 ALOGV("Injecting VSync inside SurfaceFlinger");
1310 mVSyncInjector->onInjectSyncEvent(when);
1311 }
1312 return NO_ERROR;
1313}
1314
Lloyd Pique755e3192018-01-31 16:46:15 -08001315status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1316 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001317 // Try to acquire a lock for 1s, fail gracefully
1318 const status_t err = mStateLock.timedLock(s2ns(1));
1319 const bool locked = (err == NO_ERROR);
1320 if (!locked) {
1321 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1322 return TIMED_OUT;
1323 }
1324
1325 outLayers->clear();
1326 mCurrentState.traverseInZOrder([&](Layer* layer) {
1327 outLayers->push_back(layer->getLayerDebugInfo());
1328 });
1329
1330 mStateLock.unlock();
1331 return NO_ERROR;
1332}
1333
Peiyong Linc6780972018-10-28 15:24:08 -07001334status_t SurfaceFlinger::getCompositionPreference(
1335 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1336 Dataspace* outWideColorGamutDataspace,
1337 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001338 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001339 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001340 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001341 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001342 return NO_ERROR;
1343}
1344
Dan Stozaec460082018-12-17 15:35:09 -08001345status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1346 const sp<IBinder>& stopLayerHandle,
1347 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001348 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001349 return BAD_VALUE;
1350 }
1351 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001352 return NO_ERROR;
1353}
1354
Dan Stozaec460082018-12-17 15:35:09 -08001355status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001356 if (!listener) {
1357 return BAD_VALUE;
1358 }
Dan Stozaec460082018-12-17 15:35:09 -08001359 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001360 return NO_ERROR;
1361}
Dan Gittik57e63c52019-01-18 16:37:54 +00001362
1363status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1364 bool* outSupport) const {
1365 if (!displayToken || !outSupport) {
1366 return BAD_VALUE;
1367 }
1368 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1369 if (!displayId) {
1370 return NAME_NOT_FOUND;
1371 }
1372 *outSupport =
1373 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1374 return NO_ERROR;
1375}
1376
1377status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1378 float brightness) const {
1379 if (!displayToken) {
1380 return BAD_VALUE;
1381 }
1382 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1383 if (!displayId) {
1384 return NAME_NOT_FOUND;
1385 }
1386 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1387}
1388
Ady Abraham8532d012019-05-08 14:50:56 -07001389status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1390 PowerHint powerHint = static_cast<PowerHint>(hintId);
1391
1392 if (powerHint == PowerHint::INTERACTION) {
1393 mScheduler->notifyTouchEvent();
1394 }
1395
1396 return NO_ERROR;
1397}
1398
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001399// ----------------------------------------------------------------------------
1400
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001401sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001402 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001403 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001404 Mutex::Autolock lock(mStateLock);
1405 return getVsyncPeriod();
1406 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001407
Ana Krulecc2870422019-01-29 19:00:58 -08001408 const auto& handle =
1409 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001410
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001411 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1412 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001413}
1414
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001415// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001416
1417void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001418 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001419}
1420
1421void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001422 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001423 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001424}
1425
1426void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001427 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001428 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001429}
1430
1431void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001432 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001433 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001434}
1435
1436status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001437 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001438 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001439}
1440
1441status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001442 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001443 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001444 if (res == NO_ERROR) {
1445 msg->wait();
1446 }
1447 return res;
1448}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001449
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001450void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001451 do {
1452 waitForEvent();
1453 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001454}
1455
Dominik Laskowski83b88212018-12-11 13:34:06 -08001456nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001457 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001458 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1459 return 0;
1460 }
1461
1462 const auto config = getHwComposer().getActiveConfig(*displayId);
1463 return config ? config->getVsyncPeriod() : 0;
1464}
1465
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001466void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1467 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001468 ATRACE_NAME("SF onVsync");
1469
Steven Thomas3cfac282017-02-06 12:29:30 -08001470 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
1474 }
1475
Dominik Laskowski075d3172018-05-24 15:50:06 -07001476 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001481 // For now, we don't do anything with external display vsyncs.
1482 return;
1483 }
1484
Alec Mourif8e689c2019-05-20 18:32:22 -07001485 bool periodFlushed = false;
1486 mScheduler->addResyncSample(timestamp, &periodFlushed);
1487 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001488 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001489 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001490}
1491
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001492void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001493 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1494 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001495}
1496
Ady Abraham261614e2019-07-10 17:53:12 -07001497bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001498 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001499}
1500
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001501void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001502 const auto display = getDefaultDisplayDeviceLocked();
1503 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001504 return;
1505 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001506 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001507
Ana Krulec7d1d6832018-12-27 11:10:09 -08001508 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001509 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001510 if (!refreshRateConfig) {
1511 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001512 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001513 }
Ady Abraham1902d072019-03-01 17:18:59 -08001514
Alec Mouri0a1cc962019-03-14 12:33:02 -07001515 const int desiredConfigId = refreshRateConfig->configId;
1516
Dominik Laskowski22488f62019-03-28 09:53:04 -07001517 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001518 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1519 return;
1520 }
1521
Dominik Laskowski22488f62019-03-28 09:53:04 -07001522 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001523}
1524
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001525void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001526 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001527 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001528 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529
Lloyd Piqueba04e622017-12-14 17:11:26 -08001530 // Ignore events that do not have the right sequenceId.
1531 if (sequenceId != getBE().mComposerSequenceId) {
1532 return;
1533 }
1534
Steven Thomasb02664d2017-07-26 18:48:28 -07001535 // Only lock if we're not on the main thread. This function is normally
1536 // called on a hwbinder thread, but for the primary display it's called on
1537 // the main thread with the state lock already held, so don't attempt to
1538 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001539 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001540
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001541 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001542
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001543 if (std::this_thread::get_id() == mMainThreadId) {
1544 // Process all pending hot plug events immediately if we are on the main thread.
1545 processDisplayHotplugEventsLocked();
1546 }
1547
Lloyd Piqueba04e622017-12-14 17:11:26 -08001548 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001549}
1550
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001551void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001552 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001553 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001555 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001556 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001557}
1558
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001559void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001560 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001561
1562 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1563 // display power state.
1564 postMessageAsync(new LambdaMessage(
1565 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1566}
1567
1568void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1569 ATRACE_CALL();
1570
Ady Abraham27c70212019-06-11 10:52:26 -07001571 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1572
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001573 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001574 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1575 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001576 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001577 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001578 }
Mathias Agopian86303202012-07-24 22:46:10 -07001579}
1580
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001581// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001582void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001583 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001584 // Clear the drawing state so that the logic inside of
1585 // handleTransactionLocked will fire. It will determine the delta between
1586 // mCurrentState and mDrawingState and re-apply all changes when we make the
1587 // transition.
1588 mDrawingState.displays.clear();
1589 mDisplays.clear();
1590}
1591
Steven Thomas050b2c82017-03-06 11:45:16 -08001592void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001593 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001594 if (!mVrFlinger)
1595 return;
1596 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001597 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001598 return;
1599 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001600
Lloyd Pique441d5042018-10-18 16:49:51 -07001601 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001602 ALOGE("Vr flinger is only supported for remote hardware composer"
1603 " service connections. Ignoring request to transition to vr"
1604 " flinger.");
1605 mVrFlingerRequestsDisplay = false;
1606 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001607 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001608
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001610
Steven Thomas0123ac62018-07-12 11:32:34 -07001611 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001612 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001613
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001614 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001615
1616 // Clear out all the output layers from the composition engine for all
1617 // displays before destroying the hardware composer interface. This ensures
1618 // any HWC layers are destroyed through that interface before it becomes
1619 // invalid.
1620 for (const auto& [token, displayDevice] : mDisplays) {
1621 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1622 compositionengine::Output::OutputLayers());
1623 }
1624
Steven Thomas0123ac62018-07-12 11:32:34 -07001625 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1626 // called below. Clear the reference now so we don't accidentally use it
1627 // later.
1628 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001629
Steven Thomasb02664d2017-07-26 18:48:28 -07001630 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001632 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001633
Steven Thomasb02664d2017-07-26 18:48:28 -07001634 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001635 // Delete the current instance before creating the new one
1636 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1637 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1638 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1639 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001640
Lloyd Pique441d5042018-10-18 16:49:51 -07001641 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001642 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001643
1644 if (vrFlingerRequestsDisplay) {
1645 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001646 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001647
1648 mVisibleRegionsDirty = true;
1649 invalidateHwcGeometry();
1650
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001651 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001652 display = getDefaultDisplayDeviceLocked();
1653 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001654 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001655
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001657 const nsecs_t vsyncPeriod = getVsyncPeriod();
1658 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001659
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001660 // The present fences returned from vr_hwc are not an accurate
1661 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001662 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001663
Steven Thomasb02664d2017-07-26 18:48:28 -07001664 // Use phase of 0 since phase is not known.
1665 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001666 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001667 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001668
Ana Krulecc2870422019-01-29 19:00:58 -08001669 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001670
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001671 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001672 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001673}
1674
Ady Abrahambe0f9482019-04-24 15:41:53 -07001675bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1676 // We are storing the last 2 present fences. If sf's phase offset is to be
1677 // woken up before the actual vsync but targeting the next vsync, we need to check
1678 // fence N-2
1679 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001680 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001681 ? mPreviousPresentFences[0]
1682 : mPreviousPresentFences[1];
1683
1684 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1685}
1686
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001687void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001688 DisplayStatInfo stats;
1689 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001690 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001691 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001692 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001693 mPhaseOffsets->getOffsetThresholdForNextVsync()
1694 ? presentTime
1695 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001696}
1697
Dominik Laskowski22488f62019-03-28 09:53:04 -07001698void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001699 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001700 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001701 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001702 // calculate the expected present time once and use the cached
1703 // value throughout this frame to make sure all layers are
1704 // seeing this same value.
1705 populateExpectedPresentTime();
1706
Ady Abrahambe0f9482019-04-24 15:41:53 -07001707 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001708 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1709 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1710 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1711 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1712 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1713 if (frameMissed) {
1714 mFrameMissedCount++;
1715 mTimeStats->incrementMissedFrames();
1716 }
1717
Alec Mouri40189b02019-03-05 15:07:54 -08001718 if (hwcFrameMissed) {
1719 mHwcFrameMissedCount++;
1720 }
1721
1722 if (gpuFrameMissed) {
1723 mGpuFrameMissedCount++;
1724 }
1725
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001726 if (mUseSmart90ForVideo) {
1727 // This call is made each time SF wakes up and creates a new frame. It is part
1728 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001729 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001730 }
1731
Ady Abrahamb838aed2019-02-12 15:30:16 -08001732 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001733 break;
1734 }
1735
Ady Abraham4658e112019-07-22 13:07:26 -07001736 if (frameMissed && mPropagateBackpressure) {
1737 if ((hwcFrameMissed && !gpuFrameMissed) ||
1738 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001739 signalLayerUpdate();
1740 break;
1741 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001742 }
Dan Stoza50182882016-07-08 12:02:20 -07001743
Steven Thomas050b2c82017-03-06 11:45:16 -08001744 // Now that we're going to make it to the handleMessageTransaction()
1745 // call below it's safe to call updateVrFlinger(), which will
1746 // potentially trigger a display handoff.
1747 updateVrFlinger();
1748
Dan Stoza6b9454d2014-11-07 16:00:59 -08001749 bool refreshNeeded = handleMessageTransaction();
1750 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001751
1752 updateCursorAsync();
1753 updateInputFlinger();
1754
Dan Stoza58784442014-12-02 16:58:17 -08001755 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001756 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001757 // Signal a refresh if a transaction modified the window state,
1758 // a new buffer was latched, or if HWC has requested a full
1759 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001760 signalRefresh();
1761 }
1762 break;
1763 }
1764 case MessageQueue::REFRESH: {
1765 handleMessageRefresh();
1766 break;
1767 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001768 }
1769}
1770
Dan Stoza6b9454d2014-11-07 16:00:59 -08001771bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001772 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001773 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001774
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001775 bool flushedATransaction = flushTransactionQueues();
1776
1777 bool runHandleTransaction = transactionFlags &&
1778 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1779
1780 if (runHandleTransaction) {
1781 handleTransaction(eTransactionMask);
1782 } else {
1783 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001784 }
1785
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001786 if (transactionFlushNeeded()) {
1787 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001788 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001789
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001790 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001791}
1792
Mathias Agopian4fec8732012-06-29 14:12:52 -07001793void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001794 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001795
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001796 mRefreshPending = false;
1797
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001798 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001799 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001800 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001801 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001802 for (const auto& [token, display] : mDisplays) {
1803 beginFrame(display);
1804 prepareFrame(display);
1805 doDebugFlashRegions(display, repaintEverything);
1806 doComposition(display, repaintEverything);
1807 }
1808
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001809 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001810
1811 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001812 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001813
Dan Stozabfbffeb2016-07-21 14:49:33 -07001814 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001815 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001816 for (const auto& [token, displayDevice] : mDisplays) {
1817 auto display = displayDevice->getCompositionDisplay();
1818 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001819 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001821 mHadDeviceComposition =
1822 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001823 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001824
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001825 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001826
David Sodman7e4ae112018-02-09 15:02:28 -08001827 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001828 if (mVisibleRegionsDirty) {
1829 mVisibleRegionsDirty = false;
1830 if (mTracingEnabled) {
1831 mTracing.notify("visibleRegionsDirty");
1832 }
1833 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836
1837bool SurfaceFlinger::handleMessageInvalidate() {
1838 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001839 bool refreshNeeded = handlePageFlip();
1840
Vishnu Nair4351ad52019-02-11 14:13:02 -08001841 if (mVisibleRegionsDirty) {
1842 computeLayerBounds();
1843 }
1844
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001845 for (auto& layer : mLayersPendingRefresh) {
1846 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001847 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001848 invalidateLayerStack(layer, visibleReg);
1849 }
1850 mLayersPendingRefresh.clear();
1851 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001852}
1853
David Sodman79bba0e2018-08-05 18:07:49 -07001854void SurfaceFlinger::calculateWorkingSet() {
1855 ATRACE_CALL();
1856 ALOGV(__FUNCTION__);
1857
David Sodman79bba0e2018-08-05 18:07:49 -07001858 // build the h/w work list
1859 if (CC_UNLIKELY(mGeometryInvalid)) {
1860 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001861 for (const auto& [token, displayDevice] : mDisplays) {
1862 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001863
Lloyd Piquea83776c2019-01-29 18:42:32 -08001864 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001865
Lloyd Piquea83776c2019-01-29 18:42:32 -08001866 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1867 auto& compositionState = layer->editState();
1868 compositionState.forceClientComposition = false;
1869 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1870 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001871 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001872
Lloyd Piquea83776c2019-01-29 18:42:32 -08001873 // The output Z order is set here based on a simple counter.
1874 compositionState.z = zOrder++;
1875
1876 // Update the display independent composition state. This goes
1877 // to the general composition layer state structure.
1878 // TODO: Do this once per compositionengine::CompositionLayer.
1879 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1880 true);
1881
1882 // Recalculate the geometry state of the output layer.
1883 layer->updateCompositionState(true);
1884
1885 // Write the updated geometry state to the HWC
1886 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001887 }
1888 }
1889 }
1890
1891 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001892 for (const auto& [token, displayDevice] : mDisplays) {
1893 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001894 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001895 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001896 continue;
1897 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001898 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001899
1900 if (mDrawingState.colorMatrixChanged) {
1901 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001902 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001903 Dataspace targetDataspace = Dataspace::UNKNOWN;
1904 if (useColorManagement) {
1905 ColorMode colorMode;
1906 RenderIntent renderIntent;
1907 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1908 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001909
1910 if (isHdrColorMode(colorMode)) {
1911 targetDataspace = Dataspace::UNKNOWN;
1912 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1913 targetDataspace = mColorSpaceAgnosticDataspace;
1914 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001915 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001916
Lloyd Pique32cbe282018-10-19 13:09:22 -07001917 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001918 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001919 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001920 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1921 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001922 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001923 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001924 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1925 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001926 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001927 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001928 }
1929
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001930 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001931 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001932 }
1933
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001934 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001935 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001936 layer->setCompositionType(displayDevice,
1937 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001938 continue;
1939 }
1940
Lloyd Pique32cbe282018-10-19 13:09:22 -07001941 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001942 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001943 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001944 }
1945 }
1946
1947 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001948
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001949 for (const auto& [token, displayDevice] : mDisplays) {
1950 auto display = displayDevice->getCompositionDisplay();
1951 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001952 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1953 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1954 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001955 }
1956 }
David Sodman79bba0e2018-08-05 18:07:49 -07001957}
1958
Lloyd Pique32cbe282018-10-19 13:09:22 -07001959void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1960 bool repaintEverything) {
1961 auto display = displayDevice->getCompositionDisplay();
1962 const auto& displayState = display->getState();
1963
Mathias Agopiancd60f992012-08-16 16:28:27 -07001964 // is debugging enabled
1965 if (CC_LIKELY(!mDebugRegion))
1966 return;
1967
Lloyd Pique32cbe282018-10-19 13:09:22 -07001968 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001969 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001970 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001971 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001972 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001973 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001974 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001975
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001976 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001977 }
1978 }
1979
Lloyd Pique32cbe282018-10-19 13:09:22 -07001980 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001981
1982 if (mDebugRegion > 1) {
1983 usleep(mDebugRegion * 1000);
1984 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001985
Lloyd Pique32cbe282018-10-19 13:09:22 -07001986 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001987}
1988
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001989void SurfaceFlinger::logLayerStats() {
1990 ATRACE_CALL();
1991 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001992 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001993 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001994 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001995 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001996 }
1997 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001998
1999 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002000 }
2001}
2002
David Sodman2b406362017-12-15 13:33:47 -08002003void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002005 ATRACE_CALL();
2006 ALOGV("preComposition");
2007
David Sodman2b406362017-12-15 13:33:47 -08002008 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2009
Mathias Agopiancd60f992012-08-16 16:28:27 -07002010 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002011 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002012 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013 needExtraInvalidate = true;
2014 }
Robert Carr2047fae2016-11-28 14:09:09 -08002015 });
2016
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017 if (needExtraInvalidate) {
2018 signalLayerUpdate();
2019 }
2020}
2021
Ana Krulece588e312018-09-18 12:32:24 -07002022void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2023 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002024 // Update queue of past composite+present times and determine the
2025 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002026 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002027 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002028 while (!getBE().mCompositePresentTimes.empty()) {
2029 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030 // Cached values should have been updated before calling this method,
2031 // which helps avoid duplicate syscalls.
2032 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2033 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2034 break;
2035 }
2036 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002037 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002038 }
2039
2040 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002041 while (getBE().mCompositePresentTimes.size() > 16) {
2042 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043 }
2044
Ana Krulece588e312018-09-18 12:32:24 -07002045 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002046}
2047
Ana Krulece588e312018-09-18 12:32:24 -07002048void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2049 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 // Integer division and modulo round toward 0 not -inf, so we need to
2051 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002052 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2053 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2054 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055
Ana Krulec757f63a2019-01-25 10:46:18 -08002056 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002057 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002058 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002059 }
2060
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061 // Snap the latency to a value that removes scheduling jitter from the
2062 // composition and present times, which often have >1ms of jitter.
2063 // Reducing jitter is important if an app attempts to extrapolate
2064 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002065 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002067 nsecs_t bias = stats.vsyncPeriod / 2;
2068 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2069 nsecs_t snappedCompositeToPresentLatency =
2070 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002071
David Sodman99974d22017-11-28 12:04:33 -08002072 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002073 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2074 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002075 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076}
2077
David Sodman2b406362017-12-15 13:33:47 -08002078void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002079{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002080 ATRACE_CALL();
2081 ALOGV("postComposition");
2082
Brian Anderson3546a3f2016-07-14 11:51:14 -07002083 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002084 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002085 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002086 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002087 }
2088
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002089 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002090 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002091
David Sodman73beded2017-11-15 11:56:06 -08002092 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002093 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002094 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002095 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002096 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2097 ->getRenderSurface()
2098 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002099 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002100 } else {
2101 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2102 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002103
David Sodman73beded2017-11-15 11:56:06 -08002104 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002105 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2106 mPreviousPresentFences[0] = displayDevice
2107 ? getHwComposer().getPresentFence(*displayDevice->getId())
2108 : Fence::NO_FENCE;
2109 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002110 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002111
Ana Krulece588e312018-09-18 12:32:24 -07002112 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002113 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002114
David Sodman2b406362017-12-15 13:33:47 -08002115 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002116 // when we started doing work for this frame, but that should be okay
2117 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002118 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002119 CompositorTiming compositorTiming;
2120 {
David Sodman99974d22017-11-28 12:04:33 -08002121 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2122 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002123 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002124
Robert Carr2047fae2016-11-28 14:09:09 -08002125 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002126 bool frameLatched =
2127 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2128 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002129 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002130 recordBufferingStats(layer->getName().string(),
2131 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002132 }
Robert Carr2047fae2016-11-28 14:09:09 -08002133 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002134
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002135 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002136 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002137 }
2138
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002139 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2141 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002142 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002143 }
2144 }
2145
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002146 if (mAnimCompositionPending) {
2147 mAnimCompositionPending = false;
2148
Brian Anderson4e606e32017-03-16 15:34:57 -07002149 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002150 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002151 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002152 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002153 // The HWC doesn't support present fences, so use the refresh
2154 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002155 const nsecs_t presentTime =
2156 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002157 mAnimFrameTracker.setActualPresentTime(presentTime);
2158 }
2159 mAnimFrameTracker.advanceFrame();
2160 }
Dan Stozab90cf072015-03-05 11:05:59 -08002161
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002162 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002163 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002164 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002165 }
2166
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002167 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002168
Lloyd Pique32cbe282018-10-19 13:09:22 -07002169 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2170 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002171 return;
2172 }
2173
2174 nsecs_t currentTime = systemTime();
2175 if (mHasPoweredOff) {
2176 mHasPoweredOff = false;
2177 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002178 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002179 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002180 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2181 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002182 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002183 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002184 }
David Sodman4a36e932017-11-07 14:29:47 -08002185 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002186 }
David Sodman4a36e932017-11-07 14:29:47 -08002187 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002188
2189 {
2190 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002191 if (mTexturePool.size() < mTexturePoolSize) {
2192 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002193 const size_t offset = mTexturePool.size();
2194 mTexturePool.resize(mTexturePoolSize);
2195 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2196 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002197 } else if (mTexturePool.size() > mTexturePoolSize) {
2198 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2199 const size_t offset = mTexturePoolSize;
2200 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2201 mTexturePool.resize(mTexturePoolSize);
2202 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002203 }
2204 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002205
Ady Abrahambe0f9482019-04-24 15:41:53 -07002206 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002207 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002208
Kevin DuBois413287f2019-02-25 08:46:47 -08002209 if (mLumaSampling && mRegionSamplingThread) {
2210 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002211 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002212
2213 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2214 // side-effect of getTotalSize(), so we check that again here
2215 if (ATRACE_ENABLED()) {
2216 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2217 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218}
2219
Vishnu Nair4351ad52019-02-11 14:13:02 -08002220void SurfaceFlinger::computeLayerBounds() {
2221 for (const auto& pair : mDisplays) {
2222 const auto& displayDevice = pair.second;
2223 const auto display = displayDevice->getCompositionDisplay();
2224 for (const auto& layer : mDrawingState.layersSortedByZ) {
2225 // only consider the layers on the given layer stack
2226 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002227 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002228 }
2229
2230 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2231 }
2232 }
2233}
2234
Mathias Agopiancd60f992012-08-16 16:28:27 -07002235void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 ATRACE_CALL();
2237 ALOGV("rebuildLayerStacks");
2238
Mathias Agopiancd60f992012-08-16 16:28:27 -07002239 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002240 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002241 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002242 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002243
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002244 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002245 const auto& displayDevice = pair.second;
2246 auto display = displayDevice->getCompositionDisplay();
2247 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002248 Region opaqueRegion;
2249 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002250 compositionengine::Output::OutputLayers layersSortedByZ;
2251 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002252 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002253 const ui::Transform& tr = displayState.transform;
2254 const Rect bounds = displayState.bounds;
2255 if (displayState.isEnabled) {
2256 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002257
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002259 auto compositionLayer = layer->getCompositionLayer();
2260 if (compositionLayer == nullptr) {
2261 return;
2262 }
2263
Lloyd Pique32cbe282018-10-19 13:09:22 -07002264 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002265 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2266 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2267
Lloyd Pique07e33212018-12-18 16:33:37 -08002268 bool needsOutputLayer = false;
2269
Lloyd Piqueef36b002019-01-23 17:52:04 -08002270 if (display->belongsInOutput(layer->getLayerStack(),
2271 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002272 Region drawRegion(tr.transform(
2273 layer->visibleNonTransparentRegion));
2274 drawRegion.andSelf(bounds);
2275 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002276 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002277 }
Chia-I Wu83806892017-11-16 10:50:20 -08002278 }
2279
Lloyd Pique07e33212018-12-18 16:33:37 -08002280 if (needsOutputLayer) {
2281 layersSortedByZ.emplace_back(
2282 display->getOrCreateOutputLayer(displayId, compositionLayer,
2283 layerFE));
2284 deprecated_layersSortedByZ.add(layer);
2285
2286 auto& outputLayerState = layersSortedByZ.back()->editState();
2287 outputLayerState.visibleRegion =
2288 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2289 } else if (displayId) {
2290 // For layers that are being removed from a HWC display,
2291 // and that have queued frames, add them to a a list of
2292 // released layers so we can properly set a fence.
2293 bool hasExistingOutputLayer =
2294 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2295 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2296 mLayersWithQueuedFrames.cend(),
2297 layer) != mLayersWithQueuedFrames.cend();
2298
2299 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002300 layersNeedingFences.add(layer);
2301 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002302 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002303 });
2304 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002305
2306 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2307
2308 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002309 displayDevice->setLayersNeedingFences(layersNeedingFences);
2310
2311 Region undefinedRegion{bounds};
2312 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2313
2314 display->editState().undefinedRegion = undefinedRegion;
2315 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002316 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002317 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002318}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002319
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002322// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002324// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325// The returned HDR data space is one of
2326// - Dataspace::UNKNOWN
2327// - Dataspace::BT2020_HLG
2328// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002329Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2330 Dataspace* outHdrDataSpace,
2331 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002332 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002333 *outHdrDataSpace = Dataspace::UNKNOWN;
2334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002336 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337 case Dataspace::V0_SCRGB:
2338 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002339 case Dataspace::BT2020:
2340 case Dataspace::BT2020_ITU:
2341 case Dataspace::BT2020_LINEAR:
2342 case Dataspace::DISPLAY_BT2020:
2343 bestDataSpace = Dataspace::DISPLAY_BT2020;
2344 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002345 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002346 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002347 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348 case Dataspace::BT2020_PQ:
2349 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002350 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002352 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002353 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002354 case Dataspace::BT2020_HLG:
2355 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002356 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 // When there's mixed PQ content and HLG content, we set the HDR
2358 // data space to be BT2020_PQ and convert HLG to PQ.
2359 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2360 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002361 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362 break;
2363 default:
2364 break;
2365 }
Romain Guy54f154a2017-10-24 21:40:32 +01002366 }
2367
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002368 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002369}
2370
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2373 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002374 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2375 *outMode = ColorMode::NATIVE;
2376 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002379 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002380
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002382 bool isHdrClientComposition = false;
2383 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002385 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2386
Peiyong Lina3ea5592019-02-10 14:45:00 -08002387 switch (mForceColorMode) {
2388 case ColorMode::SRGB:
2389 bestDataSpace = Dataspace::V0_SRGB;
2390 break;
2391 case ColorMode::DISPLAY_P3:
2392 bestDataSpace = Dataspace::DISPLAY_P3;
2393 break;
2394 default:
2395 break;
2396 }
2397
Peiyong Lindfde5112018-06-05 10:58:41 -07002398 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002399 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2400 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002401 if (isHdr) {
2402 bestDataSpace = hdrDataSpace;
2403 }
2404
Chia-I Wu0d711262018-05-21 15:19:35 -07002405 RenderIntent intent;
2406 switch (mDisplayColorSetting) {
2407 case DisplayColorSetting::MANAGED:
2408 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002409 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002410 break;
2411 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002412 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002413 break;
2414 default: // vendor display color setting
2415 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2416 break;
2417 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002418
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002419 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002420}
2421
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2423 auto display = displayDevice->getCompositionDisplay();
2424 const auto& displayState = display->getState();
2425
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002426 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002427 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2428 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002429
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430 // If nothing has changed (!dirty), don't recompose.
2431 // If something changed, but we don't currently have any visible layers,
2432 // and didn't when we last did a composition, then skip it this time.
2433 // The second rule does two things:
2434 // - When all layers are removed from a display, we'll emit one black
2435 // frame, then nothing more until we get new layers.
2436 // - When a display is created with a private layer stack, we won't
2437 // emit any black frames until a layer is added to the layer stack.
2438 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002439
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 const char flagPrefix[] = {'-', '+'};
2441 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2443 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2444 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2445 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002446
Lloyd Pique31cb2942018-10-19 17:23:03 -07002447 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002448
David Sodmanfa9b2af2017-12-24 13:28:59 -08002449 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002451 }
2452}
2453
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2455 auto display = displayDevice->getCompositionDisplay();
2456 const auto& displayState = display->getState();
2457
2458 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459 return;
David Sodman2b406362017-12-15 13:33:47 -08002460 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002461
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002462 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002464 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002465}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002468 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 ALOGV("doComposition");
2470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 auto display = displayDevice->getCompositionDisplay();
2472 const auto& displayState = display->getState();
2473
2474 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002476 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002477
David Sodmanfa9b2af2017-12-24 13:28:59 -08002478 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002482 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002483 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002484 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002485}
2486
David Sodmanfa9b2af2017-12-24 13:28:59 -08002487void SurfaceFlinger::postFrame()
2488{
2489 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 const auto display = getDefaultDisplayDeviceLocked();
2491 if (display && getHwComposer().isConnected(*display->getId())) {
2492 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002493 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2494 logFrameStats();
2495 }
2496 }
2497}
2498
Lloyd Pique32cbe282018-10-19 13:09:22 -07002499void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002500 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002502
Lloyd Pique32cbe282018-10-19 13:09:22 -07002503 auto display = displayDevice->getCompositionDisplay();
2504 const auto& displayState = display->getState();
2505 const auto displayId = display->getId();
2506
Lloyd Pique32cbe282018-10-19 13:09:22 -07002507 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 if (displayId) {
2509 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002510 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002511 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002512 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002513 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002514 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002515
Chia-I Wu7b549592017-11-15 09:14:57 -08002516 // The layer buffer from the previous frame (if any) is released
2517 // by HWC only when the release fence from this frame (if any) is
2518 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002519 if (layer->getState().hwc) {
2520 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002521 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002522 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2523 usedClientComposition =
2524 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002525 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002526
2527 // If the layer was client composited in the previous frame, we
2528 // need to merge with the previous client target acquire fence.
2529 // Since we do not track that, always merge with the current
2530 // client target acquire fence when it is available, even though
2531 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002532 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002533 releaseFence =
2534 Fence::merge("LayerRelease", releaseFence,
2535 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002536 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002537
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002538 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002539 }
Chia-I Wu83806892017-11-16 10:50:20 -08002540
2541 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002543 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002544 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002546 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002547 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002548 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002549 }
2550 }
2551
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 if (displayId) {
2553 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002554 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556}
2557
Mathias Agopian87baae12012-07-31 12:38:26 -07002558void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559{
Mathias Agopian841cde52012-03-01 15:44:37 -08002560 ATRACE_CALL();
2561
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002562 // here we keep a copy of the drawing state (that is the state that's
2563 // going to be overwritten by handleTransactionLocked()) outside of
2564 // mStateLock so that the side-effects of the State assignment
2565 // don't happen with mStateLock held (which can cause deadlocks).
2566 State drawingState(mDrawingState);
2567
Mathias Agopianca4d3602011-05-19 15:38:14 -07002568 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002569 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570
Mathias Agopianca4d3602011-05-19 15:38:14 -07002571 // Here we're guaranteed that some transaction flags are set
2572 // so we can call handleTransactionLocked() unconditionally.
2573 // We call getTransactionFlags(), which will also clear the flags,
2574 // with mStateLock held to guarantee that mCurrentState won't change
2575 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002576
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002577 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002578 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002579 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002580
Mathias Agopianca4d3602011-05-19 15:38:14 -07002581 mDebugInTransaction = 0;
2582 invalidateHwcGeometry();
2583 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002584}
2585
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2587 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 const std::optional<DisplayIdentificationInfo> info =
2589 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002592 continue;
2593 }
2594
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002597 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 mPhysicalDisplayTokens[info->id] = new BBinder();
2599 DisplayDeviceState state;
2600 state.displayId = info->id;
2601 state.isSecure = true; // All physical displays are currently considered secure.
2602 state.displayName = info->name;
2603 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2604 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002605 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002607 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002608
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2610 if (index >= 0) {
2611 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2612 mInterceptor->saveDisplayDeletion(state.sequenceId);
2613 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002614 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002616 }
2617
2618 processDisplayChangesLocked();
2619 }
2620
2621 mPendingHotplugEvents.clear();
2622}
2623
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002624void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002625 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2626 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002627}
2628
Lloyd Pique99d3da52018-01-22 17:48:03 -08002629sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002631 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 const sp<IGraphicBufferProducer>& producer) {
2633 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002634 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002636 creationArgs.isSecure = state.isSecure;
2637 creationArgs.displaySurface = dispSurface;
2638 creationArgs.hasWideColorGamut = false;
2639 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002640
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002641 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 creationArgs.isPrimary = isInternalDisplay;
2643
2644 if (useColorManagement && displayId) {
2645 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002647 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002648 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002650
Dominik Laskowski7e045462018-05-30 13:02:02 -07002651 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002653 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654 }
tangrobin6753a022018-08-10 10:58:54 +08002655 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656
Dominik Laskowski075d3172018-05-24 15:50:06 -07002657 if (displayId) {
2658 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002659 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002660 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002661 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662
Lloyd Pique90c115d2018-09-18 21:39:42 -07002663 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002665 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 // Make sure that composition can never be stalled by a virtual display
2668 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002669 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002670 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2672 }
2673
Dominik Laskowski075d3172018-05-24 15:50:06 -07002674 creationArgs.displayInstallOrientation =
2675 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002676
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002678 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679
Lloyd Pique90c115d2018-09-18 21:39:42 -07002680 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002681
2682 if (maxFrameBufferAcquiredBuffers >= 3) {
2683 nativeWindowSurface->preallocateBuffers();
2684 }
2685
2686 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002687 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002688 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002690 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002691 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002692 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2693 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 if (!state.isVirtual()) {
2695 LOG_ALWAYS_FATAL_IF(!displayId);
2696 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002697 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002699 display->setLayerStack(state.layerStack);
2700 display->setProjection(state.orientation, state.viewport, state.frame);
2701 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002704}
2705
Lloyd Pique347200f2017-12-14 17:00:15 -08002706void SurfaceFlinger::processDisplayChangesLocked() {
2707 // here we take advantage of Vector's copy-on-write semantics to
2708 // improve performance by skipping the transaction entirely when
2709 // know that the lists are identical
2710 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2711 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2712 if (!curr.isIdenticalTo(draw)) {
2713 mVisibleRegionsDirty = true;
2714 const size_t cc = curr.size();
2715 size_t dc = draw.size();
2716
2717 // find the displays that were removed
2718 // (ie: in drawing state but not in current state)
2719 // also handle displays that changed
2720 // (ie: displays that are in both lists)
2721 for (size_t i = 0; i < dc;) {
2722 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2723 if (j < 0) {
2724 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002726 // Save display ID before disconnecting.
2727 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002728 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002729
2730 if (!display->isVirtual()) {
2731 LOG_ALWAYS_FATAL_IF(!displayId);
2732 dispatchDisplayHotplugEvent(displayId->value, false);
2733 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002735
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002736 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 } else {
2738 // this display is in both lists. see if something changed.
2739 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002740 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2742 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2743 if (state_binder != draw_binder) {
2744 // changing the surface is like destroying and
2745 // recreating the DisplayDevice, so we just remove it
2746 // from the drawing state, so that it get re-added
2747 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002748 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002749 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002751 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 mDrawingState.displays.removeItemsAt(i);
2753 dc--;
2754 // at this point we must loop to the next item
2755 continue;
2756 }
2757
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002758 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 }
2762 if ((state.orientation != draw[i].orientation) ||
2763 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 }
2766 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 }
2769 }
2770 }
2771 ++i;
2772 }
2773
2774 // find displays that were added
2775 // (ie: in current state but not in drawing state)
2776 for (size_t i = 0; i < cc; i++) {
2777 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2778 const DisplayDeviceState& state(curr[i]);
2779
Lloyd Pique542307f2018-10-19 13:24:08 -07002780 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 sp<IGraphicBufferProducer> producer;
2782 sp<IGraphicBufferProducer> bqProducer;
2783 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002784 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002785
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002787 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 // Virtual displays without a surface are dormant:
2789 // they have external state (layer stack, projection,
2790 // etc.) but no internal state (i.e. a DisplayDevice).
2791 if (state.surface != nullptr) {
2792 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002793 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 int width = 0;
2795 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2796 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2797 int height = 0;
2798 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2799 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2800 int intFormat = 0;
2801 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2802 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002803 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002804
Dominik Laskowski075d3172018-05-24 15:50:06 -07002805 displayId =
2806 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 }
2808
2809 // TODO: Plumb requested format back up to consumer
2810
2811 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002812 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002813 bqProducer, bqConsumer,
2814 state.displayName);
2815
2816 dispSurface = vds;
2817 producer = vds;
2818 }
2819 } else {
2820 ALOGE_IF(state.surface != nullptr,
2821 "adding a supported display, but rendering "
2822 "surface is provided (%p), ignoring it",
2823 state.surface.get());
2824
Dominik Laskowski075d3172018-05-24 15:50:06 -07002825 displayId = state.displayId;
2826 LOG_ALWAYS_FATAL_IF(!displayId);
2827 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002828 producer = bqProducer;
2829 }
2830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002833 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002834 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002836 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002838 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002839 }
2840 }
2841 }
2842 }
2843 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002844
2845 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002846}
2847
Mathias Agopian87baae12012-07-31 12:38:26 -07002848void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002849{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002850 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2851
Dan Stoza7dde5992015-05-22 09:51:44 -07002852 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002853 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2854 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002855 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002857 /*
2858 * Traversal of the children
2859 * (perform the transaction for each of them if needed)
2860 */
2861
Marissa Wall06255332019-03-27 13:48:27 -07002862 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002863 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002865 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002866
2867 const uint32_t flags = layer->doTransaction(0);
2868 if (flags & Layer::eVisibleRegion)
2869 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002870
2871 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002872 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002873 }
Robert Carr2047fae2016-11-28 14:09:09 -08002874 });
Marissa Wall06255332019-03-27 13:48:27 -07002875 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 }
2877
2878 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002879 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880 */
2881
Mathias Agopiane57f2922012-08-09 16:29:12 -07002882 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002883 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002884 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002886
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002887 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002888 // The transform hint might have changed for some layers
2889 // (either because a display has changed, or because a layer
2890 // as changed).
2891 //
2892 // Walk through all the layers in currentLayers,
2893 // and update their transform hint.
2894 //
2895 // If a layer is visible only on a single display, then that
2896 // display is used to calculate the hint, otherwise we use the
2897 // default display.
2898 //
2899 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2900 // the hint is set before we acquire a buffer from the surface texture.
2901 //
2902 // NOTE: layer transactions have taken place already, so we use their
2903 // drawing state. However, SurfaceFlinger's own transaction has not
2904 // happened yet, so we must use the current state layer list
2905 // (soon to become the drawing state list).
2906 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002907 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002908 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002909 bool first = true;
2910 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002911 // NOTE: we rely on the fact that layers are sorted by
2912 // layerStack first (so we don't have to traverse the list
2913 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002915 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002916 currentlayerStack = layerStack;
2917 // figure out if this layerstack is mirrored
2918 // (more than one display) if so, pick the default display,
2919 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002920 hintDisplay = nullptr;
2921 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002922 if (display->getCompositionDisplay()
2923 ->belongsInOutput(layer->getLayerStack(),
2924 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 if (hintDisplay) {
2926 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002927 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002929 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002930 }
2931 }
2932 }
2933 }
Chet Haase91d25932013-04-11 15:24:55 -07002934
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002935 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002936 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2937 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002938
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002939 // could be null when this layer is using a layerStack
2940 // that is not visible on any display. Also can occur at
2941 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002943 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002944
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002945 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002946 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002947 if (hintDisplay) {
2948 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002949 }
Robert Carr2047fae2016-11-28 14:09:09 -08002950
2951 first = false;
2952 });
Mathias Agopian84300952012-11-21 16:02:13 -08002953 }
2954
2955
Mathias Agopian3559b072012-08-15 13:46:03 -07002956 /*
2957 * Perform our own transaction if needed
2958 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002959
2960 if (mLayersAdded) {
2961 mLayersAdded = false;
2962 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002963 mVisibleRegionsDirty = true;
2964 }
2965
2966 // some layers might have been removed, so
2967 // we need to update the regions they're exposing.
2968 if (mLayersRemoved) {
2969 mLayersRemoved = false;
2970 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002971 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002972 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002973 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002974 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002975 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002976 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002977 }
Robert Carr2047fae2016-11-28 14:09:09 -08002978 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979 }
2980
Vishnu Nairec0ab382019-02-13 15:32:56 -08002981 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002983}
2984
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002985void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002986 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002987 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002988 return;
2989 }
2990
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002991 if (mVisibleRegionsDirty || mInputInfoChanged) {
2992 mInputInfoChanged = false;
2993 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002994 } else if (mInputWindowCommands.syncInputWindows) {
2995 // If the caller requested to sync input windows, but there are no
2996 // changes to input windows, notify immediately.
2997 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002998 }
2999
3000 executeInputWindowCommands();
3001}
3002
3003void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003004 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003005
3006 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3007 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003008 // When calculating the screen bounds we ignore the transparent region since it may
3009 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003010 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003011 }
3012 });
chaviw291d88a2019-02-14 10:33:58 -08003013
3014 mInputFlinger->setInputWindows(inputHandles,
3015 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3016 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003017}
3018
Vishnu Nairec0ab382019-02-13 15:32:56 -08003019void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003020 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003021 mPendingInputWindowCommands.clear();
3022}
3023
chaviwfbe5d9c2018-12-26 12:23:37 -08003024void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003025 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3026 if (transferTouchFocusCommand.fromToken != nullptr &&
3027 transferTouchFocusCommand.toToken != nullptr &&
3028 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3029 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3030 transferTouchFocusCommand.toToken);
3031 }
3032 }
3033
3034 mInputWindowCommands.clear();
3035}
3036
Riley Andrews03414a12014-07-01 14:22:59 -07003037void SurfaceFlinger::updateCursorAsync()
3038{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003039 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003040 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003041 continue;
3042 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003044 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3045 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003046 }
3047 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003048}
3049
chaviw61626f22018-11-15 16:26:27 -08003050void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3051 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003052 bool ignored = false;
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003053 layer->latchBuffer(ignored, systemTime(), 0 /* expectedPresentTime */);
chaviw61626f22018-11-15 16:26:27 -08003054 }
3055 layer->releasePendingBuffer(systemTime());
3056}
3057
Mathias Agopian4fec8732012-06-29 14:12:52 -07003058void SurfaceFlinger::commitTransaction()
3059{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003060 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003061 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003062 for (const auto& l : mLayersPendingRemoval) {
3063 recordBufferingStats(l->getName().string(),
3064 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003065
Lloyd Pique07e33212018-12-18 16:33:37 -08003066 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003067 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003068 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003069 }
chaviw74d90ad2019-04-26 14:45:26 -07003070
3071 // If the layer has been removed and has no parent, then it will not be reachable
3072 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3073 // ensure we can copy its current to drawing state.
3074 if (!l->getParent()) {
3075 mOffscreenLayers.emplace(l.get());
3076 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 }
3078 mLayersPendingRemoval.clear();
3079 }
3080
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003081 // If this transaction is part of a window animation then the next frame
3082 // we composite should be considered an animation as well.
3083 mAnimCompositionPending = mAnimTransactionPending;
3084
Nataniel Borges2b796da2019-02-15 13:32:18 -08003085 withTracingLock([&]() {
3086 mDrawingState = mCurrentState;
3087 // clear the "changed" flags in current state
3088 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003089
chaviw74d90ad2019-04-26 14:45:26 -07003090 mDrawingState.traverseInZOrder([&](Layer* layer) {
3091 layer->commitChildList();
3092
3093 // If the layer can be reached when traversing mDrawingState, then the layer is no
3094 // longer offscreen. Remove the layer from the offscreenLayer set.
3095 if (mOffscreenLayers.count(layer)) {
3096 mOffscreenLayers.erase(layer);
3097 }
3098 });
3099
3100 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003101 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003102
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003103 mTransactionPending = false;
3104 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003106}
3107
Nataniel Borges2b796da2019-02-15 13:32:18 -08003108void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3109 if (mTracingEnabledChanged) {
3110 mTracingEnabled = mTracing.isEnabled();
3111 mTracingEnabledChanged = false;
3112 }
3113
3114 // Synchronize with Tracing thread
3115 std::unique_lock<std::mutex> lock;
3116 if (mTracingEnabled) {
3117 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3118 }
3119
3120 lockedOperation();
3121
3122 // Synchronize with Tracing thread
3123 if (mTracingEnabled) {
3124 lock.unlock();
3125 }
3126}
3127
chaviw74d90ad2019-04-26 14:45:26 -07003128void SurfaceFlinger::commitOffscreenLayers() {
3129 for (Layer* offscreenLayer : mOffscreenLayers) {
3130 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3131 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3132 if (!trFlags) return;
3133
3134 layer->doTransaction(0);
3135 layer->commitChildList();
3136 });
3137 }
3138}
3139
Lloyd Pique32cbe282018-10-19 13:09:22 -07003140void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003141 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003142 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003143 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003144
Lloyd Pique32cbe282018-10-19 13:09:22 -07003145 auto display = displayDevice->getCompositionDisplay();
3146
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147 Region aboveOpaqueLayers;
3148 Region aboveCoveredLayers;
3149 Region dirty;
3150
Mathias Agopian87baae12012-07-31 12:38:26 -07003151 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152
Robert Carr2047fae2016-11-28 14:09:09 -08003153 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003154 // start with the whole surface at its current location
3155 const Layer::State& s(layer->getDrawingState());
3156
Jesse Hall01e29052013-02-19 16:13:35 -08003157 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003158 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003159 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003160 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003161
Mathias Agopianab028732010-03-16 16:41:46 -07003162 /*
3163 * opaqueRegion: area of a surface that is fully opaque.
3164 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003165 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003166
3167 /*
3168 * visibleRegion: area of a surface that is visible on screen
3169 * and not fully transparent. This is essentially the layer's
3170 * footprint minus the opaque regions above it.
3171 * Areas covered by a translucent surface are considered visible.
3172 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003174
3175 /*
3176 * coveredRegion: area of a surface that is covered by all
3177 * visible regions above it (which includes the translucent areas).
3178 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003179 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003180
Jesse Halla8026d22012-09-25 13:25:04 -07003181 /*
3182 * transparentRegion: area of a surface that is hinted to be completely
3183 * transparent. This is only used to tell when the layer has no visible
3184 * non-transparent regions and can be removed from the layer list. It
3185 * does not affect the visibleRegion of this layer or any layers
3186 * beneath it. The hint may not be correct if apps don't respect the
3187 * SurfaceView restrictions (which, sadly, some don't).
3188 */
3189 Region transparentRegion;
3190
Mathias Agopianab028732010-03-16 16:41:46 -07003191
3192 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003193 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003194 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003195 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003196
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003198 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003199 if (!visibleRegion.isEmpty()) {
3200 // Remove the transparent area from the visible region
3201 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003202 if (tr.preserveRects()) {
3203 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003204 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003205 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003206 // transformation too complex, can't do the
3207 // transparent region optimization.
3208 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003209 }
Mathias Agopianab028732010-03-16 16:41:46 -07003210 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211
Mathias Agopianab028732010-03-16 16:41:46 -07003212 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003213 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003214 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003215 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003216 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003217 // the opaque region is the layer's footprint
3218 opaqueRegion = visibleRegion;
3219 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 }
3221 }
3222
Robert Carre5f4f692018-01-12 13:12:28 -08003223 if (visibleRegion.isEmpty()) {
3224 layer->clearVisibilityRegions();
3225 return;
3226 }
3227
Mathias Agopianab028732010-03-16 16:41:46 -07003228 // Clip the covered region to the visible region
3229 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3230
3231 // Update aboveCoveredLayers for next (lower) layer
3232 aboveCoveredLayers.orSelf(visibleRegion);
3233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234 // subtract the opaque region covered by the layers above us
3235 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236
3237 // compute this layer's dirty region
3238 if (layer->contentDirty) {
3239 // we need to invalidate the whole region
3240 dirty = visibleRegion;
3241 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003242 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243 layer->contentDirty = false;
3244 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003245 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003246 * the exposed region consists of two components:
3247 * 1) what's VISIBLE now and was COVERED before
3248 * 2) what's EXPOSED now less what was EXPOSED before
3249 *
3250 * note that (1) is conservative, we start with the whole
3251 * visible region but only keep what used to be covered by
3252 * something -- which mean it may have been exposed.
3253 *
3254 * (2) handles areas that were not covered by anything but got
3255 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003256 */
Mathias Agopianab028732010-03-16 16:41:46 -07003257 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003258 const Region oldVisibleRegion = layer->visibleRegion;
3259 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003260 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3261 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 }
3263 dirty.subtractSelf(aboveOpaqueLayers);
3264
3265 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003266 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267
Mathias Agopianab028732010-03-16 16:41:46 -07003268 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003270
Jesse Halla8026d22012-09-25 13:25:04 -07003271 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272 layer->setVisibleRegion(visibleRegion);
3273 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003274 layer->setVisibleNonTransparentRegion(
3275 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003276 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277
Mathias Agopian87baae12012-07-31 12:38:26 -07003278 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279}
3280
Chia-I Wuab0c3192017-08-01 11:29:00 -07003281void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003282 for (const auto& [token, displayDevice] : mDisplays) {
3283 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003284 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003285 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003286 }
3287 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003288}
3289
Dan Stoza6b9454d2014-11-07 16:00:59 -08003290bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291{
Ady Abraham09bd3922019-04-08 10:44:56 -07003292 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003293 ALOGV("handlePageFlip");
3294
Brian Andersond6927fb2016-07-23 23:37:30 -07003295 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296
Mathias Agopian4fec8732012-06-29 14:12:52 -07003297 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003298 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003299 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003300
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003301 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3302
Eric Penner51c59cd2014-07-28 19:51:58 -07003303 // Store the set of layers that need updates. This set must not change as
3304 // buffers are being latched, as this could result in a deadlock.
3305 // Example: Two producers share the same command stream and:
3306 // 1.) Layer 0 is latched
3307 // 2.) Layer 0 gets a new frame
3308 // 2.) Layer 1 gets a new frame
3309 // 3.) Layer 1 is latched.
3310 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3311 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003312 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003313 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003314 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003315 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003316 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003317 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003318 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003319 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003320 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003321 } else {
3322 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003323 }
Robert Carr2047fae2016-11-28 14:09:09 -08003324 });
3325
Lloyd Piquef2c79392018-12-20 16:23:33 -08003326 if (!mLayersWithQueuedFrames.empty()) {
3327 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3328 // writes to Layer current state. See also b/119481871
3329 Mutex::Autolock lock(mStateLock);
3330
3331 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003332 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003333 mLayersPendingRefresh.push_back(layer);
3334 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003335 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003336 if (layer->isBufferLatched()) {
3337 newDataLatched = true;
3338 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003339 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003340 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003341
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003342 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003343
3344 // If we will need to wake up at some time in the future to deal with a
3345 // queued frame that shouldn't be displayed during this vsync period, wake
3346 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003347 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003348 signalLayerUpdate();
3349 }
3350
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003351 // enter boot animation on first buffer latch
3352 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3353 ALOGI("Enter boot animation");
3354 mBootStage = BootStage::BOOTANIMATION;
3355 }
3356
Dan Stoza6b9454d2014-11-07 16:00:59 -08003357 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003358 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359}
3360
Mathias Agopianad456f92011-01-13 17:53:01 -08003361void SurfaceFlinger::invalidateHwcGeometry()
3362{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003363 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003364}
3365
Lloyd Pique32cbe282018-10-19 13:09:22 -07003366void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003367 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003368 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003369 // We only need to actually compose the display if:
3370 // 1) It is being handled by hardware composer, which may need this to
3371 // keep its virtual display state machine in sync, or
3372 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003373 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003374 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003375 return;
3376 }
3377
Dan Stoza9e56aa02015-11-02 13:00:03 -08003378 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003379 base::unique_fd readyFence;
3380 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003381
3382 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003384}
3385
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003386bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3387 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003388 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003389 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003390
Lloyd Pique32cbe282018-10-19 13:09:22 -07003391 auto display = displayDevice->getCompositionDisplay();
3392 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003393 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003394 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003395 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003396
3397 const Region bounds(displayState.bounds);
3398 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003399 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003400 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003401
Chia-I Wu8e50e692018-05-04 10:12:37 -07003402 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003403
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404 renderengine::DisplaySettings clientCompositionDisplay;
3405 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3406 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003407 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003408
Dan Stoza9e56aa02015-11-02 13:00:03 -08003409 if (hasClientComposition) {
3410 ALOGV("hasClientComposition");
3411
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003412 if (displayDevice->isPrimary() && supportProtectedContent) {
3413 bool needsProtected = false;
3414 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3415 // If the layer is a protected layer, mark protected context is needed.
3416 if (layer->isProtected()) {
3417 needsProtected = true;
3418 break;
3419 }
3420 }
Peiyong Lin52010312019-05-02 14:22:16 -07003421 if (needsProtected != renderEngine.isProtected()) {
3422 renderEngine.useProtectedContext(needsProtected);
3423 }
3424 if (needsProtected != display->getRenderSurface()->isProtected() &&
3425 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003426 display->getRenderSurface()->setProtected(needsProtected);
3427 }
3428 }
3429
Alec Mouri6338c9d2019-02-07 16:57:51 -08003430 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003431
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003432 if (buf == nullptr) {
3433 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3434 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003435 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003436 return false;
3437 }
3438
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003439 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3440 clientCompositionDisplay.clip = displayState.scissor;
3441 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003442 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003443 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003444
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003445 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003446 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003447 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003448 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003449 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003450 clientCompositionDisplay.outputDataspace = outputDataspace;
3451 clientCompositionDisplay.maxLuminance =
3452 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003453
Lloyd Pique441d5042018-10-18 16:49:51 -07003454 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003455 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003456 getHwComposer()
3457 .hasDisplayCapability(displayId,
3458 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003459
Peiyong Lind3788632018-09-18 16:01:31 -07003460 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003461 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3462 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003463 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003464 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003465 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003466
Mathias Agopian85d751c2012-08-29 16:59:24 -07003467 /*
3468 * and then, render the layers targeted at the framebuffer
3469 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003470
Dan Stoza9e56aa02015-11-02 13:00:03 -08003471 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003472 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003473 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003474 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003475 const Region viewportRegion(displayState.viewport);
3476 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003477 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003478 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003479 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003480 switch (layer->getCompositionType(displayDevice)) {
3481 case Hwc2::IComposerClient::Composition::CURSOR:
3482 case Hwc2::IComposerClient::Composition::DEVICE:
3483 case Hwc2::IComposerClient::Composition::SIDEBAND:
3484 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003485 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003486 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003487 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003488 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003489 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003490 // never clear the very first layer since we're
3491 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003492 renderengine::LayerSettings layerSettings;
3493 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003494 bool prepared =
3495 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3496 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003497
3498 if (prepared) {
3499 layerSettings.source.buffer.buffer = nullptr;
3500 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3501 layerSettings.alpha = half(0.0);
3502 layerSettings.disableBlending = true;
3503 clientCompositionLayers.push_back(layerSettings);
3504 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003505 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003506 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003507 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003508 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003509 renderengine::LayerSettings layerSettings;
3510 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003511 layer->prepareClientLayer(renderArea, clip, clearRegion,
3512 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003513 if (prepared) {
3514 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003515 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003516 break;
3517 }
3518 default:
3519 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003520 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003521 } else {
3522 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003523 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003524 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003525 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003526
Alec Mouri820c7402019-01-23 13:02:39 -08003527 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003528 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003529 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003530
3531 // We boost GPU frequency here because there will be color spaces conversion
3532 // and it's expensive. We boost the GPU frequency so that GPU composition can
3533 // finish in time. We must reset GPU frequency afterwards, because high frequency
3534 // consumes extra battery.
3535 const bool expensiveRenderingExpected =
3536 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3537 if (expensiveRenderingExpected && displayId) {
3538 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3539 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003540 if (!debugRegion.isEmpty()) {
3541 Region::const_iterator it = debugRegion.begin();
3542 Region::const_iterator end = debugRegion.end();
3543 while (it != end) {
3544 const Rect& rect = *it++;
3545 renderengine::LayerSettings layerSettings;
3546 layerSettings.source.buffer.buffer = nullptr;
3547 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3548 layerSettings.geometry.boundaries = rect.toFloatRect();
3549 layerSettings.alpha = half(1.0);
3550 clientCompositionLayers.push_back(layerSettings);
3551 }
3552 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003553 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003554 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3555 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003556 } else if (displayId) {
3557 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003558 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003559 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560}
3561
Robert Carrc0df3122019-04-11 13:18:21 -07003562status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3563 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3564 const sp<IBinder>& parentHandle,
3565 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003566 // add this layer to the current state list
3567 {
3568 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003569 sp<Layer> parent;
3570 if (parentHandle != nullptr) {
3571 parent = fromHandle(parentHandle);
3572 if (parent == nullptr) {
3573 return NAME_NOT_FOUND;
3574 }
3575 } else {
3576 parent = parentLayer;
3577 }
3578
Robert Carr1f0a16a2016-10-24 16:27:39 -07003579 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003580 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3581 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003582 return NO_MEMORY;
3583 }
Robert Carrc0df3122019-04-11 13:18:21 -07003584
3585 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3586
Robert Carrb89ea9d2018-12-10 13:01:14 -08003587 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003588 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003589 } else if (parent == nullptr) {
3590 lbc->onRemovedFromCurrentState();
3591 } else if (parent->isRemovedFromCurrentState()) {
3592 parent->addChild(lbc);
3593 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003594 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003595 parent->addChild(lbc);
3596 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003597
Yiwei Zhang243b3782018-05-15 17:40:04 -07003598 if (gbc != nullptr) {
3599 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3600 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3601 mMaxGraphicBufferProducerListSize,
3602 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3603 mGraphicBufferProducerList.size(),
3604 mMaxGraphicBufferProducerListSize, mNumLayers);
3605 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003606 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003607 }
3608
Mathias Agopian96f08192010-06-02 23:28:45 -07003609 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003610 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003611
Dan Stoza7d89d062015-04-30 13:29:25 -07003612 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003613}
3614
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003615uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003616 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003617}
3618
Mathias Agopian3f844832013-08-07 21:24:32 -07003619uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003620 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003621}
3622
Mathias Agopian3f844832013-08-07 21:24:32 -07003623uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003624 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003625}
3626
3627uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003628 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003629 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003630 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003632 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633 }
3634 return old;
3635}
3636
Marissa Wall713b63f2018-10-17 15:42:43 -07003637bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003638 // to prevent onHandleDestroyed from being called while the lock is held,
3639 // we must keep a copy of the transactions (specifically the composer
3640 // states) around outside the scope of the lock
3641 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003642 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003643 {
3644 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003645
Valerie Haufce31b82019-04-30 16:41:14 -07003646 auto it = mTransactionQueues.begin();
3647 while (it != mTransactionQueues.end()) {
3648 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003649
Valerie Haufce31b82019-04-30 16:41:14 -07003650 while (!transactionQueue.empty()) {
3651 const auto& transaction = transactionQueue.front();
3652 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003653 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003654 transaction.states)) {
3655 setTransactionFlags(eTransactionFlushNeeded);
3656 break;
3657 }
3658 transactions.push_back(transaction);
3659 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3660 mPendingInputWindowCommands, transaction.desiredPresentTime,
3661 transaction.buffer, transaction.callback,
3662 transaction.postTime, transaction.privileged,
3663 /*isMainThread*/ true);
3664 transactionQueue.pop();
3665 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003666 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003667
Valerie Haufce31b82019-04-30 16:41:14 -07003668 if (transactionQueue.empty()) {
3669 it = mTransactionQueues.erase(it);
3670 mTransactionCV.broadcast();
3671 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003672 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003673 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003674 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003675 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003676 return flushedATransaction;
3677}
3678
3679bool SurfaceFlinger::transactionFlushNeeded() {
3680 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003681}
3682
chaviwca27f252018-02-06 16:46:39 -08003683bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3684 for (const ComposerState& state : states) {
3685 // Here we need to check that the interface we're given is indeed
3686 // one of our own. A malicious client could give us a nullptr
3687 // IInterface, or one of its own or even one of our own but a
3688 // different type. All these situations would cause us to crash.
3689 if (state.client == nullptr) {
3690 return true;
3691 }
3692
3693 sp<IBinder> binder = IInterface::asBinder(state.client);
3694 if (binder == nullptr) {
3695 return true;
3696 }
3697
3698 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3699 return true;
3700 }
3701 }
3702 return false;
3703}
3704
Marissa Wall17b4e452018-12-26 16:32:34 -08003705bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003706 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003707 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003708 if (!useCachedExpectedPresentTime)
3709 populateExpectedPresentTime();
3710
3711 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003712 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3713 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3714 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3715 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3716 return false;
3717 }
3718
Marissa Wall713b63f2018-10-17 15:42:43 -07003719 for (const ComposerState& state : states) {
3720 const layer_state_t& s = state.state;
3721 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3722 continue;
3723 }
3724 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003725 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003726 }
3727 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003728 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003729}
3730
3731void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3732 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003733 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003734 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003735 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003736 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003737 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003738 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003739
Valerie Haubc6ddb12019-03-08 11:10:15 -08003740 const int64_t postTime = systemTime();
3741
Robert Carr14167e02019-02-13 13:50:55 -08003742 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3743
Mathias Agopian698c0872011-06-28 19:09:31 -07003744 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003745
chaviwca27f252018-02-06 16:46:39 -08003746 if (containsAnyInvalidClientState(states)) {
3747 return;
3748 }
3749
Marissa Wall713b63f2018-10-17 15:42:43 -07003750 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003751 auto itr = mTransactionQueues.find(applyToken);
3752 // if this is an animation frame, wait until prior animation frame has
3753 // been applied by SF
3754 if (flags & eAnimation) {
3755 while (itr != mTransactionQueues.end()) {
3756 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3757 if (CC_UNLIKELY(err != NO_ERROR)) {
3758 ALOGW_IF(err == TIMED_OUT,
3759 "setTransactionState timed out "
3760 "waiting for animation frame to apply");
3761 break;
3762 }
3763 itr = mTransactionQueues.find(applyToken);
3764 }
3765 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003766
3767 // Expected present time is computed and cached on invalidate, so it may be stale.
3768 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3769 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003770 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003771 uncacheBuffer, listenerCallbacks, postTime,
3772 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003773 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003774 return;
3775 }
3776
Valerie Haubc6ddb12019-03-08 11:10:15 -08003777 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003778 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003779}
3780
3781void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003782 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003783 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003784 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003785 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003786 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003787 const int64_t postTime, bool privileged,
3788 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003789 uint32_t transactionFlags = 0;
3790
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003791 if (flags & eAnimation) {
3792 // For window updates that are part of an animation we must wait for
3793 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003794 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003795 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003796 if (CC_UNLIKELY(err != NO_ERROR)) {
3797 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003798 // caller after a few seconds.
3799 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3800 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003801 mAnimTransactionPending = false;
3802 break;
3803 }
3804 }
3805 }
3806
chaviwca27f252018-02-06 16:46:39 -08003807 for (const DisplayState& display : displays) {
3808 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003809 }
3810
Marissa Walld600d572019-03-26 15:38:50 -07003811 // In case the client has sent a Transaction that should receive callbacks but without any
3812 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3813 // to the callback thread so it can send an empty callback
3814 if (!listenerCallbacks.empty()) {
3815 mTransactionCompletedThread.run();
3816 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003817 for (const auto& listenerCallback : listenerCallbacks) {
3818 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003819 }
3820
Marissa Walle2ffb422018-10-12 11:33:52 -07003821 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003822 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003823 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3824 postTime, privileged);
3825 }
3826
Marissa Wallefb71af2019-06-27 14:45:53 -07003827 for (const auto& listenerCallback : listenerCallbacks) {
3828 mTransactionCompletedThread.endRegistration(listenerCallback);
3829 }
3830
Marissa Walle2ffb422018-10-12 11:33:52 -07003831 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003832 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003833 mTransactionCompletedThread.sendCallbacks();
3834 }
3835 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003836
chaviw273171b2018-12-26 11:46:30 -08003837 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3838
Marissa Wall947d34e2019-03-29 14:03:53 -07003839 if (uncacheBuffer.isValid()) {
3840 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003841 }
3842
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003843 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3844 // anyway. This can be used as a flush mechanism for previous async transactions.
3845 // Empty animation transaction can be used to simulate back-pressure, so also force a
3846 // transaction for empty animation transactions.
3847 if (transactionFlags == 0 &&
3848 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003849 transactionFlags = eTransactionNeeded;
3850 }
3851
Marissa Wall06255332019-03-27 13:48:27 -07003852 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3853 // so we don't have to wake up again next frame to preform an uneeded traversal.
3854 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3855 transactionFlags = transactionFlags & (~eTraversalNeeded);
3856 mTraversalNeededMainThread = true;
3857 }
3858
Mathias Agopian386aa982011-11-07 21:58:03 -08003859 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003860 if (mInterceptor->isEnabled()) {
3861 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003862 }
Irvel468051e2016-06-13 16:44:44 -07003863
Mathias Agopian386aa982011-11-07 21:58:03 -08003864 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003865 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3866 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003867 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003868
3869 // if this is a synchronous transaction, wait for it to take effect
3870 // before returning.
3871 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003872 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003873 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003874 if (flags & eAnimation) {
3875 mAnimTransactionPending = true;
3876 }
chaviw4fe36852019-04-15 16:25:49 -07003877 if (mPendingInputWindowCommands.syncInputWindows) {
3878 mPendingSyncInputWindows = true;
3879 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003880
3881 // applyTransactionState can be called by either the main SF thread or by
3882 // another process through setTransactionState. While a given process may wish
3883 // to wait on synchronous transactions, the main SF thread should never
3884 // be blocked. Therefore, we only wait if isMainThread is false.
3885 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003886 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3887 if (CC_UNLIKELY(err != NO_ERROR)) {
3888 // just in case something goes wrong in SF, return to the
3889 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003890 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3891 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003892 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003893 break;
3894 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003895 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 }
3897}
3898
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003899uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3900 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3901 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003902
Mathias Agopiane57f2922012-08-09 16:29:12 -07003903 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003904 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3905
3906 const uint32_t what = s.what;
3907 if (what & DisplayState::eSurfaceChanged) {
3908 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3909 state.surface = s.surface;
3910 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003911 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003912 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003913 if (what & DisplayState::eLayerStackChanged) {
3914 if (state.layerStack != s.layerStack) {
3915 state.layerStack = s.layerStack;
3916 flags |= eDisplayTransactionNeeded;
3917 }
3918 }
3919 if (what & DisplayState::eDisplayProjectionChanged) {
3920 if (state.orientation != s.orientation) {
3921 state.orientation = s.orientation;
3922 flags |= eDisplayTransactionNeeded;
3923 }
3924 if (state.frame != s.frame) {
3925 state.frame = s.frame;
3926 flags |= eDisplayTransactionNeeded;
3927 }
3928 if (state.viewport != s.viewport) {
3929 state.viewport = s.viewport;
3930 flags |= eDisplayTransactionNeeded;
3931 }
3932 }
3933 if (what & DisplayState::eDisplaySizeChanged) {
3934 if (state.width != s.width) {
3935 state.width = s.width;
3936 flags |= eDisplayTransactionNeeded;
3937 }
3938 if (state.height != s.height) {
3939 state.height = s.height;
3940 flags |= eDisplayTransactionNeeded;
3941 }
3942 }
3943
Mathias Agopiane57f2922012-08-09 16:29:12 -07003944 return flags;
3945}
3946
Robert Carr14167e02019-02-13 13:50:55 -08003947bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003948 IPCThreadState* ipc = IPCThreadState::self();
3949 const int pid = ipc->getCallingPid();
3950 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003951 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003952 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003953 return false;
3954 }
3955 return true;
3956}
3957
Marissa Wall3dad52d2019-03-22 14:03:19 -07003958uint32_t SurfaceFlinger::setClientStateLocked(
3959 const ComposerState& composerState, int64_t desiredPresentTime,
3960 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3961 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003962 const layer_state_t& s = composerState.state;
3963 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3964
Mathias Agopian13127d82013-03-05 17:47:11 -08003965 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003966 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003967 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003968 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003969 new CallbackHandle(listenerCallback.transactionCompletedListener,
3970 listenerCallback.callbackIds, s.surface));
3971 }
chaviw8b3871a2017-11-01 17:41:01 -07003972 return 0;
3973 }
3974
chaviw8b3871a2017-11-01 17:41:01 -07003975 uint32_t flags = 0;
3976
Garfield Tan8a3083e2018-12-03 13:21:07 -08003977 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003978 bool geometryAppliesWithResize =
3979 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003980
3981 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3982 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003983 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003984 layer->pushPendingState();
3985 }
3986
chaviw8b3871a2017-11-01 17:41:01 -07003987 if (what & layer_state_t::ePositionChanged) {
3988 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3989 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003990 }
chaviw8b3871a2017-11-01 17:41:01 -07003991 }
3992 if (what & layer_state_t::eLayerChanged) {
3993 // NOTE: index needs to be calculated before we update the state
3994 const auto& p = layer->getParent();
3995 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003996 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003997 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003998 mCurrentState.layersSortedByZ.removeAt(idx);
3999 mCurrentState.layersSortedByZ.add(layer);
4000 // we need traversal (state changed)
4001 // AND transaction (list changed)
4002 flags |= eTransactionNeeded|eTraversalNeeded;
4003 }
chaviw8b3871a2017-11-01 17:41:01 -07004004 } else {
4005 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004006 flags |= eTransactionNeeded|eTraversalNeeded;
4007 }
4008 }
chaviw8b3871a2017-11-01 17:41:01 -07004009 }
4010 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004011 // NOTE: index needs to be calculated before we update the state
4012 const auto& p = layer->getParent();
4013 if (p == nullptr) {
4014 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4015 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4016 mCurrentState.layersSortedByZ.removeAt(idx);
4017 mCurrentState.layersSortedByZ.add(layer);
4018 // we need traversal (state changed)
4019 // AND transaction (list changed)
4020 flags |= eTransactionNeeded|eTraversalNeeded;
4021 }
4022 } else {
4023 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4024 flags |= eTransactionNeeded|eTraversalNeeded;
4025 }
chaviw8b3871a2017-11-01 17:41:01 -07004026 }
4027 }
4028 if (what & layer_state_t::eSizeChanged) {
4029 if (layer->setSize(s.w, s.h)) {
4030 flags |= eTraversalNeeded;
4031 }
4032 }
4033 if (what & layer_state_t::eAlphaChanged) {
4034 if (layer->setAlpha(s.alpha))
4035 flags |= eTraversalNeeded;
4036 }
4037 if (what & layer_state_t::eColorChanged) {
4038 if (layer->setColor(s.color))
4039 flags |= eTraversalNeeded;
4040 }
Peiyong Lind3788632018-09-18 16:01:31 -07004041 if (what & layer_state_t::eColorTransformChanged) {
4042 if (layer->setColorTransform(s.colorTransform)) {
4043 flags |= eTraversalNeeded;
4044 }
4045 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004046 if (what & layer_state_t::eBackgroundColorChanged) {
4047 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4048 flags |= eTraversalNeeded;
4049 }
4050 }
chaviw8b3871a2017-11-01 17:41:01 -07004051 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004052 // TODO: b/109894387
4053 //
4054 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4055 // rotation. To see the problem observe that if we have a square parent, and a child
4056 // of the same size, then we rotate the child 45 degrees around it's center, the child
4057 // must now be cropped to a non rectangular 8 sided region.
4058 //
4059 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4060 // private API, and the WindowManager only uses rotation in one case, which is on a top
4061 // level layer in which cropping is not an issue.
4062 //
4063 // However given that abuse of rotation matrices could lead to surfaces extending outside
4064 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4065 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4066 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004067 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004068 flags |= eTraversalNeeded;
4069 }
4070 if (what & layer_state_t::eTransparentRegionChanged) {
4071 if (layer->setTransparentRegionHint(s.transparentRegion))
4072 flags |= eTraversalNeeded;
4073 }
4074 if (what & layer_state_t::eFlagsChanged) {
4075 if (layer->setFlags(s.flags, s.mask))
4076 flags |= eTraversalNeeded;
4077 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004078 if (what & layer_state_t::eCropChanged_legacy) {
4079 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004080 flags |= eTraversalNeeded;
4081 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004082 if (what & layer_state_t::eCornerRadiusChanged) {
4083 if (layer->setCornerRadius(s.cornerRadius))
4084 flags |= eTraversalNeeded;
4085 }
chaviw8b3871a2017-11-01 17:41:01 -07004086 if (what & layer_state_t::eLayerStackChanged) {
4087 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4088 // We only allow setting layer stacks for top level layers,
4089 // everything else inherits layer stack from its parent.
4090 if (layer->hasParent()) {
4091 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4092 layer->getName().string());
4093 } else if (idx < 0) {
4094 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4095 "that also does not appear in the top level layer list. Something"
4096 " has gone wrong.", layer->getName().string());
4097 } else if (layer->setLayerStack(s.layerStack)) {
4098 mCurrentState.layersSortedByZ.removeAt(idx);
4099 mCurrentState.layersSortedByZ.add(layer);
4100 // we need traversal (state changed)
4101 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004102 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004103 }
4104 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004105 if (what & layer_state_t::eDeferTransaction_legacy) {
4106 if (s.barrierHandle_legacy != nullptr) {
4107 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4108 } else if (s.barrierGbp_legacy != nullptr) {
4109 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004110 if (authenticateSurfaceTextureLocked(gbp)) {
4111 const auto& otherLayer =
4112 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004113 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004114 } else {
4115 ALOGE("Attempt to defer transaction to to an"
4116 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004117 }
4118 }
chaviw8b3871a2017-11-01 17:41:01 -07004119 // We don't trigger a traversal here because if no other state is
4120 // changed, we don't want this to cause any more work
4121 }
4122 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004123 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004124 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004125 if (!hadParent) {
4126 mCurrentState.layersSortedByZ.remove(layer);
4127 }
chaviw8b3871a2017-11-01 17:41:01 -07004128 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004129 }
chaviw8b3871a2017-11-01 17:41:01 -07004130 }
4131 if (what & layer_state_t::eReparentChildren) {
4132 if (layer->reparentChildren(s.reparentHandle)) {
4133 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004134 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004135 }
chaviw8b3871a2017-11-01 17:41:01 -07004136 if (what & layer_state_t::eDetachChildren) {
4137 layer->detachChildren();
4138 }
4139 if (what & layer_state_t::eOverrideScalingModeChanged) {
4140 layer->setOverrideScalingMode(s.overrideScalingMode);
4141 // We don't trigger a traversal here because if no other state is
4142 // changed, we don't want this to cause any more work
4143 }
Marissa Wall61c58622018-07-18 10:12:20 -07004144 if (what & layer_state_t::eTransformChanged) {
4145 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4146 }
4147 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4148 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4149 flags |= eTraversalNeeded;
4150 }
4151 if (what & layer_state_t::eCropChanged) {
4152 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4153 }
Marissa Wall861616d2018-10-22 12:52:23 -07004154 if (what & layer_state_t::eFrameChanged) {
4155 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4156 }
Marissa Wall61c58622018-07-18 10:12:20 -07004157 if (what & layer_state_t::eAcquireFenceChanged) {
4158 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4159 }
4160 if (what & layer_state_t::eDataspaceChanged) {
4161 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4162 }
4163 if (what & layer_state_t::eHdrMetadataChanged) {
4164 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4165 }
4166 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4167 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4168 }
4169 if (what & layer_state_t::eApiChanged) {
4170 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4171 }
4172 if (what & layer_state_t::eSidebandStreamChanged) {
4173 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4174 }
Robert Carr720e5062018-07-30 17:45:14 -07004175 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004176 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004177 layer->setInputInfo(s.inputInfo);
4178 flags |= eTraversalNeeded;
4179 } else {
4180 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4181 }
Robert Carr720e5062018-07-30 17:45:14 -07004182 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004183 if (what & layer_state_t::eMetadataChanged) {
4184 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4185 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004186 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4187 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4188 flags |= eTraversalNeeded;
4189 }
4190 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004191 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004192 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004193 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004194 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4195 }
4196 }
Marissa Wall78b72202019-03-15 14:58:34 -07004197 bool bufferChanged = what & layer_state_t::eBufferChanged;
4198 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4199 sp<GraphicBuffer> buffer;
4200 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004201 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri1c8d7202019-06-01 18:51:35 -07004202 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4203 wp<ClientCache::ErasedRecipient>(layer));
4204 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004205 buffer = s.buffer;
4206 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004207 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004208 } else if (bufferChanged) {
4209 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004210 }
Marissa Wall78b72202019-03-15 14:58:34 -07004211 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004212 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004213 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004214 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004215 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004216 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4217 // Do not put anything that updates layer state or modifies flags after
4218 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004219 return flags;
4220}
4221
chaviw273171b2018-12-26 11:46:30 -08004222uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4223 uint32_t flags = 0;
4224 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4225 flags |= eTraversalNeeded;
4226 }
4227
chaviwa911b102019-02-14 10:18:33 -08004228 if (inputWindowCommands.syncInputWindows) {
4229 flags |= eTraversalNeeded;
4230 }
4231
Vishnu Nairec0ab382019-02-13 15:32:56 -08004232 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004233 return flags;
4234}
4235
Marissa Wall2d814fb2019-04-09 18:52:57 +00004236status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4237 uint32_t h, PixelFormat format, uint32_t flags,
4238 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004239 sp<IGraphicBufferProducer>* gbp,
4240 const sp<IBinder>& parentHandle,
4241 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004242 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004243 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004244 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004245 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004246 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004247
Robert Carrc0df3122019-04-11 13:18:21 -07004248 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4249 "Expected only one of parentLayer or parentHandle to be non-null. "
4250 "Programmer error?");
4251
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004252 status_t result = NO_ERROR;
4253
4254 sp<Layer> layer;
4255
Cody Northropbc755282017-03-31 12:00:08 -06004256 String8 uniqueName = getUniqueLayerName(name);
4257
Evan Roskya1f1e152019-01-24 16:17:46 -08004258 bool primaryDisplayOnly = false;
4259
4260 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4261 // TODO b/64227542
4262 if (metadata.has(METADATA_WINDOW_TYPE)) {
4263 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4264 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004265 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004266 primaryDisplayOnly = true;
4267 }
4268 }
4269
Mathias Agopian3165cc22012-08-08 19:42:09 -07004270 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004271 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004272 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4273 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004274
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004275 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004276 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004277 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4278 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004279 break;
chaviw13fdc492017-06-27 12:40:18 -07004280 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004281 // check if buffer size is set for color layer.
4282 if (w > 0 || h > 0) {
4283 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4284 int(w), int(h));
4285 return BAD_VALUE;
4286 }
4287
Evan Roskya1f1e152019-01-24 16:17:46 -08004288 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4289 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004290 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004291 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004292 // check if buffer size is set for container layer.
4293 if (w > 0 || h > 0) {
4294 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4295 int(w), int(h));
4296 return BAD_VALUE;
4297 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004298 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4299 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004300 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004301 default:
4302 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 break;
4304 }
4305
Dan Stoza7d89d062015-04-30 13:29:25 -07004306 if (result != NO_ERROR) {
4307 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004308 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004309
Evan Roskya1f1e152019-01-24 16:17:46 -08004310 if (primaryDisplayOnly) {
4311 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004312 }
4313
Robert Carrb89ea9d2018-12-10 13:01:14 -08004314 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004315 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4316 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004317 if (result != NO_ERROR) {
4318 return result;
4319 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004320 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004321
4322 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004323 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004324}
4325
Cody Northropbc755282017-03-31 12:00:08 -06004326String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4327{
4328 bool matchFound = true;
4329 uint32_t dupeCounter = 0;
4330
4331 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4332 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4333
Dan Stoza436ccf32018-06-21 12:10:12 -07004334 // Grab the state lock since we're accessing mCurrentState
4335 Mutex::Autolock lock(mStateLock);
4336
Cody Northropbc755282017-03-31 12:00:08 -06004337 // Loop over layers until we're sure there is no matching name
4338 while (matchFound) {
4339 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004340 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004341 if (layer->getName() == uniqueName) {
4342 matchFound = true;
4343 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4344 }
4345 });
4346 }
4347
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004348 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4349 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004350
4351 return uniqueName;
4352}
4353
Marissa Wallfd668622018-05-10 10:21:13 -07004354status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4355 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004356 LayerMetadata metadata, PixelFormat& format,
4357 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004358 sp<IGraphicBufferProducer>* gbp,
4359 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004361 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 case PIXEL_FORMAT_TRANSPARENT:
4363 case PIXEL_FORMAT_TRANSLUCENT:
4364 format = PIXEL_FORMAT_RGBA_8888;
4365 break;
4366 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004367 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368 break;
4369 }
4370
Evan Roskya1f1e152019-01-24 16:17:46 -08004371 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4372 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004373 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004374 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004375 *handle = layer->getHandle();
4376 *gbp = layer->getProducer();
4377 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004379
Marissa Wallfd668622018-05-10 10:21:13 -07004380 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004381 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004382}
4383
Marissa Wall61c58622018-07-18 10:12:20 -07004384status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4385 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004386 LayerMetadata metadata, sp<IBinder>* handle,
4387 sp<Layer>* outLayer) {
4388 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4389 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004390 *handle = layer->getHandle();
4391 *outLayer = layer;
4392
4393 return NO_ERROR;
4394}
4395
Evan Roskya1f1e152019-01-24 16:17:46 -08004396status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4397 uint32_t h, uint32_t flags, LayerMetadata metadata,
4398 sp<IBinder>* handle, sp<Layer>* outLayer) {
4399 *outLayer = getFactory().createColorLayer(
4400 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004401 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004402 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004403}
4404
Evan Roskya1f1e152019-01-24 16:17:46 -08004405status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4406 uint32_t w, uint32_t h, uint32_t flags,
4407 LayerMetadata metadata, sp<IBinder>* handle,
4408 sp<Layer>* outLayer) {
4409 *outLayer = getFactory().createContainerLayer(
4410 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004411 *handle = (*outLayer)->getHandle();
4412 return NO_ERROR;
4413}
4414
4415
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004416void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004417 mLayersPendingRemoval.add(layer);
4418 mLayersRemoved = true;
4419 setTransactionFlags(eTransactionNeeded);
4420}
4421
Robert Carr695d5282018-12-18 15:27:58 -08004422void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004423{
Robert Carr2e102c92018-10-23 12:11:15 -07004424 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004425 // If a layer has a parent, we allow it to out-live it's handle
4426 // with the idea that the parent holds a reference and will eventually
4427 // be cleaned up. However no one cleans up the top-level so we do so
4428 // here.
4429 if (layer->getParent() == nullptr) {
4430 mCurrentState.layersSortedByZ.remove(layer);
4431 }
4432 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004433
4434 auto it = mLayersByLocalBinderToken.begin();
4435 while (it != mLayersByLocalBinderToken.end()) {
4436 if (it->second == layer) {
4437 it = mLayersByLocalBinderToken.erase(it);
4438 } else {
4439 it++;
4440 }
4441 }
4442
Robert Carr695d5282018-12-18 15:27:58 -08004443 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004444}
4445
Mathias Agopianb60314a2012-04-10 22:09:54 -07004446// ---------------------------------------------------------------------------
4447
Andy McFadden13a082e2012-08-24 10:16:42 -07004448void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004449 const auto display = getDefaultDisplayDeviceLocked();
4450 if (!display) return;
4451
4452 const sp<IBinder> token = display->getDisplayToken().promote();
4453 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004454
Jesse Hall01e29052013-02-19 16:13:35 -08004455 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004456 Vector<ComposerState> state;
4457 Vector<DisplayState> displays;
4458 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004459 d.what = DisplayState::eDisplayProjectionChanged |
4460 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004461 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004462 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004463 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004464 d.frame.makeInvalid();
4465 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004466 d.width = 0;
4467 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004468 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004469 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004470
Dominik Laskowskie9774092018-12-11 10:04:24 -08004471 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004472
Dominik Laskowski83b88212018-12-11 13:34:06 -08004473 const nsecs_t vsyncPeriod = getVsyncPeriod();
4474 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004475
Brian Andersond0010582017-03-07 13:20:31 -08004476 // Use phase of 0 since phase is not known.
4477 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004478 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004479 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004480}
4481
4482void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004483 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004484 postMessageAsync(
4485 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004486}
4487
Ady Abraham27c70212019-06-11 10:52:26 -07004488void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4489 if (mHWCVsyncState != enabled) {
4490 getHwComposer().setVsyncEnabled(displayId, enabled);
4491 mHWCVsyncState = enabled;
4492 }
4493}
4494
Dominik Laskowskie9774092018-12-11 10:04:24 -08004495void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004496 if (display->isVirtual()) {
4497 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004498 return;
4499 }
4500
Dominik Laskowski075d3172018-05-24 15:50:06 -07004501 const auto displayId = display->getId();
4502 LOG_ALWAYS_FATAL_IF(!displayId);
4503
Dominik Laskowski34157762018-10-31 13:07:19 -07004504 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004505
4506 int currentMode = display->getPowerMode();
4507 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004508 return;
4509 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004510
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004511 display->setPowerMode(mode);
4512
Lloyd Pique4dccc412018-01-22 17:21:36 -08004513 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004514 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004515 }
4516
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004517 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004518 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004519 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004520 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004521 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004522 mScheduler->onScreenAcquired(mAppConnectionHandle);
4523 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004524 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004526 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004527 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004528 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004529
4530 struct sched_param param = {0};
4531 param.sched_priority = 1;
4532 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4533 ALOGW("Couldn't set SCHED_FIFO on display on");
4534 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004535 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004536 // Turn off the display
4537 struct sched_param param = {0};
4538 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4539 ALOGW("Couldn't set SCHED_OTHER on display off");
4540 }
4541
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004542 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004543 mScheduler->disableHardwareVsync(true);
4544 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004545 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004546
Ady Abraham27c70212019-06-11 10:52:26 -07004547 // Make sure HWVsync is disabled before turning off the display
4548 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4549
Dominik Laskowski075d3172018-05-24 15:50:06 -07004550 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004551 mVisibleRegionsDirty = true;
4552 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004553 } else if (mode == HWC_POWER_MODE_DOZE ||
4554 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004555 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004556 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004557 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004558 mScheduler->onScreenAcquired(mAppConnectionHandle);
4559 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004560 }
4561 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4562 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004563 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004564 mScheduler->disableHardwareVsync(true);
4565 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004566 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004567 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004568 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004569 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004570 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004571 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004572
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004573 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004574 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004575 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004576 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004577 }
4578
Dominik Laskowski34157762018-10-31 13:07:19 -07004579 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004580}
4581
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004582void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004583 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004584 const auto display = getDisplayDevice(displayToken);
4585 if (!display) {
4586 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4587 displayToken.get());
4588 } else if (display->isVirtual()) {
4589 ALOGW("Attempt to set power mode %d for virtual display", mode);
4590 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004591 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004592 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004593 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004594}
4595
4596// ---------------------------------------------------------------------------
4597
Dominik Laskowskic2867142019-01-21 11:33:38 -08004598status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4599 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004600 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004601
Mathias Agopianbd115332013-04-18 16:41:04 -07004602 IPCThreadState* ipc = IPCThreadState::self();
4603 const int pid = ipc->getCallingPid();
4604 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004605
Mathias Agopianbd115332013-04-18 16:41:04 -07004606 if ((uid != AID_SHELL) &&
4607 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004608 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4609 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004610 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004611 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004612 // (this would indicate SF is stuck, but we want to be able to
4613 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004614 status_t err = mStateLock.timedLock(s2ns(1));
4615 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004616 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 StringAppendF(&result,
4618 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4619 "(no locks held)\n",
4620 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004621 }
4622
Dominik Laskowskic2867142019-01-21 11:33:38 -08004623 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004624
Dominik Laskowskic2867142019-01-21 11:33:38 -08004625 static const std::unordered_map<std::string, Dumper> dumpers = {
4626 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4627 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4628 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004629 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004630 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004631 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004632 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4633 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004634 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4635 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4636 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4637 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4638 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4639 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004640 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004641 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4642 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004643
Dominik Laskowskic2867142019-01-21 11:33:38 -08004644 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004645
Dominik Laskowskic2867142019-01-21 11:33:38 -08004646 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4647 (it->second)(args, asProto, result);
4648 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004649 if (asProto) {
4650 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4651 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4652 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004653 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004654 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004655 }
4656
Mathias Agopian9795c422009-08-26 16:36:26 -07004657 if (locked) {
4658 mStateLock.unlock();
4659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004660 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004661 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 return NO_ERROR;
4663}
4664
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004665status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4666 if (asProto && mTracing.isEnabled()) {
4667 mTracing.writeToFileAsync();
4668 }
4669
4670 return doDump(fd, DumpArgs(), asProto);
4671}
4672
Dominik Laskowskic2867142019-01-21 11:33:38 -08004673void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004674 mCurrentState.traverseInZOrder(
4675 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004676}
4677
Dominik Laskowskic2867142019-01-21 11:33:38 -08004678void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004679 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004680
Dominik Laskowskic2867142019-01-21 11:33:38 -08004681 if (args.size() > 1) {
4682 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004683 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004684 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004685 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004686 }
Robert Carr2047fae2016-11-28 14:09:09 -08004687 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004688 } else {
4689 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690 }
4691}
4692
Dominik Laskowskic2867142019-01-21 11:33:38 -08004693void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004694 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004695 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004696 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004697 }
Robert Carr2047fae2016-11-28 14:09:09 -08004698 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004699
Svetoslavd85084b2014-03-20 10:28:31 -07004700 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004701}
4702
Dominik Laskowskic2867142019-01-21 11:33:38 -08004703void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4704 mTimeStats->parseArgs(asProto, args, result);
4705}
4706
Jamie Gennis6547ff42013-07-16 20:12:42 -07004707// This should only be called from the main thread. Otherwise it would need
4708// the lock and should use mCurrentState rather than mDrawingState.
4709void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004710 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004711 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004712 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004713
4714 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4715}
4716
Yiwei Zhang5434a782018-12-05 18:06:32 -08004717void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004718 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004719
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004720 if (isLayerTripleBufferingDisabled())
4721 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004722
Yiwei Zhang5434a782018-12-05 18:06:32 -08004723 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4724 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4725 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4726 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4727 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4728 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004729 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004730}
4731
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004732void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004733 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004734 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004735 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004736 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004737
Ady Abraham97d04232019-03-05 19:48:12 -08004738 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004739 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4740 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004741 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham261614e2019-07-10 17:53:12 -07004742 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4743 if (refresh.second && isDisplayConfigAllowed(refresh.second->configId)) {
4744 StringAppendF(&result, "%dHz, ", refresh.second->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004745 }
4746 }
4747 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4748 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004749 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004750}
4751
Yiwei Zhang5434a782018-12-05 18:06:32 -08004752void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4753 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004754 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4755 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004756 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004757 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004759 }
David Sodman4a36e932017-11-07 14:29:47 -08004760 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004761 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004762 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004763 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4764 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004765}
4766
Dan Stozae77c7662016-05-13 11:37:28 -07004767void SurfaceFlinger::recordBufferingStats(const char* layerName,
4768 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004769 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4770 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004771 for (const auto& segment : history) {
4772 if (!segment.usedThirdBuffer) {
4773 stats.twoBufferTime += segment.totalTime;
4774 }
4775 if (segment.occupancyAverage < 1.0f) {
4776 stats.doubleBufferedTime += segment.totalTime;
4777 } else if (segment.occupancyAverage < 2.0f) {
4778 stats.tripleBufferedTime += segment.totalTime;
4779 }
4780 ++stats.numSegments;
4781 stats.totalTime += segment.totalTime;
4782 }
4783}
4784
Yiwei Zhang5434a782018-12-05 18:06:32 -08004785void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4786 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004787
4788 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4789 const size_t count = currentLayers.size();
4790 for (size_t i=0 ; i<count ; i++) {
4791 currentLayers[i]->dumpFrameEvents(result);
4792 }
4793}
4794
Yiwei Zhang5434a782018-12-05 18:06:32 -08004795void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004796 result.append("Buffering stats:\n");
4797 result.append(" [Layer name] <Active time> <Two buffer> "
4798 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004799 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004800 typedef std::tuple<std::string, float, float, float> BufferTuple;
4801 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004802 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004803 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004804 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004805 if (stats.numSegments == 0) {
4806 continue;
4807 }
4808 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4809 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4810 stats.totalTime;
4811 float doubleBufferRatio = static_cast<float>(
4812 stats.doubleBufferedTime) / stats.totalTime;
4813 float tripleBufferRatio = static_cast<float>(
4814 stats.tripleBufferedTime) / stats.totalTime;
4815 sorted.insert({activeTime, {name, twoBufferRatio,
4816 doubleBufferRatio, tripleBufferRatio}});
4817 }
4818 for (const auto& sortedPair : sorted) {
4819 float activeTime = sortedPair.first;
4820 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004821 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4822 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004823 }
4824 result.append("\n");
4825}
4826
Yiwei Zhang5434a782018-12-05 18:06:32 -08004827void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004828 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004829 const auto displayId = display->getId();
4830 if (!displayId) {
4831 continue;
4832 }
4833 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004834 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004835 continue;
4836 }
4837
Yiwei Zhang5434a782018-12-05 18:06:32 -08004838 StringAppendF(&result,
4839 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4840 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004841 uint8_t port;
4842 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004843 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004844 result.append("no identification data\n");
4845 continue;
4846 }
4847
4848 if (!isEdid(data)) {
4849 result.append("unknown identification data: ");
4850 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004851 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004852 }
4853 result.append("\n");
4854 continue;
4855 }
4856
4857 const auto edid = parseEdid(data);
4858 if (!edid) {
4859 result.append("invalid EDID: ");
4860 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004862 }
4863 result.append("\n");
4864 continue;
4865 }
4866
Yiwei Zhang5434a782018-12-05 18:06:32 -08004867 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004868 result.append(edid->displayName.data(), edid->displayName.length());
4869 result.append("\"\n");
4870 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004871}
4872
Yiwei Zhang5434a782018-12-05 18:06:32 -08004873void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004874 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004875 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4876 StringAppendF(&result, "DisplayColorSetting: %s\n",
4877 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004878
4879 // TODO: print out if wide-color mode is active or not
4880
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004881 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004882 const auto displayId = display->getId();
4883 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004884 continue;
4885 }
4886
Yiwei Zhang5434a782018-12-05 18:06:32 -08004887 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004888 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004889 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004890 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004891 }
4892
Lloyd Pique32cbe282018-10-19 13:09:22 -07004893 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, " Current color mode: %s (%d)\n",
4895 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004896 }
4897 result.append("\n");
4898}
4899
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004900LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4901 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004902 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004903 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4904 const State& state = useDrawing ? mDrawingState : mCurrentState;
4905 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004906 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004907 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004908 });
4909
4910 return layersProto;
4911}
4912
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004913LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4914 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004915 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004916
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004917 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004918 resolution->set_w(displayDevice->getWidth());
4919 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004920
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004921 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004922 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004923
Lloyd Pique32cbe282018-10-19 13:09:22 -07004924 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4925 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4926 layersProto.set_global_transform(displayState.orientation);
4927
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004928 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004929 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004931 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004932 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004933 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004934 }
4935 });
4936
4937 return layersProto;
4938}
4939
Dominik Laskowskic2867142019-01-21 11:33:38 -08004940void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4941 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004942 Colorizer colorizer(colorize);
4943
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004944 // figure out if we're stuck somewhere
4945 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004946 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004947 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4948
4949 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004950 * Dump library configuration.
4951 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004952
4953 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004954 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004955 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004956 appendSfConfigString(result);
4957 appendUiConfigString(result);
4958 appendGuiConfigString(result);
4959 result.append("\n");
4960
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004961 result.append("\nDisplay identification data:\n");
4962 dumpDisplayIdentificationData(result);
4963
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004964 result.append("\nWide-Color information:\n");
4965 dumpWideColorInfo(result);
4966
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004967 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004968 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004969 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004970 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004971 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004972
Andy McFadden41d67d72014-04-25 16:58:34 -07004973 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004974 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004975 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004976 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004977 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004978
Dan Stozab90cf072015-03-05 11:05:59 -08004979 dumpStaticScreenStats(result);
4980 result.append("\n");
4981
Alec Mouri40189b02019-03-05 15:07:54 -08004982 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4983 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4984 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004985
Dan Stozae77c7662016-05-13 11:37:28 -07004986 dumpBufferingStats(result);
4987
Andy McFadden4803b742012-09-24 19:07:20 -07004988 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004989 * Dump the visible layer list
4990 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004991 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004992 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4993 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4994 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004995 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004996
Chia-I Wu2f884132018-09-13 15:17:58 -07004997 {
4998 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4999 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005000 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07005001 result.append("\n");
5002 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005003
Lloyd Pique207def92019-02-28 16:09:52 -08005004 {
5005 StringAppendF(&result, "Composition layers\n");
5006 mDrawingState.traverseInZOrder([&](Layer* layer) {
5007 auto compositionLayer = layer->getCompositionLayer();
5008 if (compositionLayer) compositionLayer->dump(result);
5009 });
5010 }
5011
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005012 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005013 * Dump Display state
5014 */
5015
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005016 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005017 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005018 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005019 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005021 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005022 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005023
5024 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005025 * Dump SurfaceFlinger global state
5026 */
5027
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005028 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005029 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005030 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005031
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005032 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005033
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005034 DebugEGLImageTracker::getInstance()->dump(result);
5035
Dominik Laskowski075d3172018-05-24 15:50:06 -07005036 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005037 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5038 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005039 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5040 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005041 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005042 StringAppendF(&result,
5043 " transaction-flags : %08x\n"
5044 " gpu_to_cpu_unsupported : %d\n",
5045 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005046
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005047 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005048 displayId && getHwComposer().isConnected(*displayId)) {
5049 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005050 StringAppendF(&result,
5051 " refresh-rate : %f fps\n"
5052 " x-dpi : %f\n"
5053 " y-dpi : %f\n",
5054 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5055 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005056 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005057
Yiwei Zhang5434a782018-12-05 18:06:32 -08005058 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005059
Dan Stozae22aec72016-08-01 13:20:59 -07005060 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005061 * Tracing state
5062 */
5063 mTracing.dump(result);
5064 result.append("\n");
5065
5066 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005067 * HWC layer minidump
5068 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005069 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005070 const auto displayId = display->getId();
5071 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005072 continue;
5073 }
5074
Yiwei Zhang5434a782018-12-05 18:06:32 -08005075 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005076 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005077 const sp<DisplayDevice> displayDevice = display;
5078 mCurrentState.traverseInZOrder(
5079 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005080 result.append("\n");
5081 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005082
5083 /*
5084 * Dump HWComposer state
5085 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005086 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005087 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005088 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005089 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005090 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005091 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005092
5093 /*
5094 * Dump gralloc state
5095 */
5096 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5097 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005098
5099 /*
5100 * Dump VrFlinger state if in use.
5101 */
5102 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5103 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005104 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005105 result.append("\n");
5106 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005107
5108 /**
5109 * Scheduler dump state.
5110 */
Ana Krulecc2870422019-01-29 19:00:58 -08005111 result.append("\nScheduler state:\n");
5112 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005113 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005114 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005115
5116 result.append(mTimeStats->miniDump());
5117 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005118}
5119
Dominik Laskowski075d3172018-05-24 15:50:06 -07005120const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005121 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005122 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005123 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005124 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005125 }
5126 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005127
Dominik Laskowski34157762018-10-31 13:07:19 -07005128 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005129 static const Vector<sp<Layer>> empty;
5130 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005131}
5132
Chia-I Wu28f320b2018-05-03 11:02:56 -07005133void SurfaceFlinger::updateColorMatrixLocked() {
5134 mat4 colorMatrix;
5135 if (mGlobalSaturationFactor != 1.0f) {
5136 // Rec.709 luma coefficients
5137 float3 luminance{0.213f, 0.715f, 0.072f};
5138 luminance *= 1.0f - mGlobalSaturationFactor;
5139 mat4 saturationMatrix = mat4(
5140 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5141 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5142 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5143 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5144 );
5145 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5146 } else {
5147 colorMatrix = mClientColorMatrix * mDaltonizer();
5148 }
5149
5150 if (mCurrentState.colorMatrix != colorMatrix) {
5151 mCurrentState.colorMatrix = colorMatrix;
5152 mCurrentState.colorMatrixChanged = true;
5153 setTransactionFlags(eTransactionNeeded);
5154 }
5155}
5156
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005157status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005158#pragma clang diagnostic push
5159#pragma clang diagnostic error "-Wswitch-enum"
5160 switch (static_cast<ISurfaceComposerTag>(code)) {
5161 // These methods should at minimum make sure that the client requested
5162 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005163 case BOOT_FINISHED:
5164 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005165 case CREATE_DISPLAY:
5166 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005167 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005168 case GET_ANIMATION_FRAME_STATS:
5169 case GET_HDR_CAPABILITIES:
5170 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005171 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005172 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005173 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005174 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005175 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005176 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005177 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005178 case GET_DISPLAYED_CONTENT_SAMPLE:
5179 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005180 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5181 IPCThreadState* ipc = IPCThreadState::self();
5182 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5183 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005184 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005185 }
Robert Carr1db73f62016-12-21 12:58:51 -08005186 return OK;
5187 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005188 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005189 IPCThreadState* ipc = IPCThreadState::self();
5190 const int pid = ipc->getCallingPid();
5191 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005192 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5193 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005194 return PERMISSION_DENIED;
5195 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005196 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005197 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005198 // Used by apps to hook Choreographer to SurfaceFlinger.
5199 case CREATE_DISPLAY_EVENT_CONNECTION:
5200 // The following calls are currently used by clients that do not
5201 // request necessary permissions. However, they do not expose any secret
5202 // information, so it is OK to pass them.
5203 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005204 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005205 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005206 case GET_PHYSICAL_DISPLAY_IDS:
5207 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005208 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005209 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005210 case GET_DISPLAY_CONFIGS:
5211 case GET_DISPLAY_STATS:
5212 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5213 // Calling setTransactionState is safe, because you need to have been
5214 // granted a reference to Client* and Handle* to do anything with it.
5215 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005216 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005217 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005218 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005219 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005220 case IS_WIDE_COLOR_DISPLAY:
5221 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5222 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005223 return OK;
5224 }
Chong Zhangda6c1592019-07-16 13:45:06 -07005225 case CAPTURE_LAYERS: {
5226 IPCThreadState* ipc = IPCThreadState::self();
5227 const int pid = ipc->getCallingPid();
5228 const int uid = ipc->getCallingUid();
5229 // allow media to capture layer for video thumbnails
5230 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
5231 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5232 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
5233 return PERMISSION_DENIED;
5234 }
5235 return OK;
5236 }
Dan Stoza84ab9372018-12-17 15:27:57 -08005237 case CAPTURE_SCREEN:
5238 case ADD_REGION_SAMPLING_LISTENER:
5239 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005240 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005241 IPCThreadState* ipc = IPCThreadState::self();
5242 const int pid = ipc->getCallingPid();
5243 const int uid = ipc->getCallingUid();
5244 if ((uid != AID_GRAPHICS) &&
5245 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5246 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5247 return PERMISSION_DENIED;
5248 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005249 return OK;
5250 }
5251 // The following codes are deprecated and should never be allowed to access SF.
5252 case CONNECT_DISPLAY_UNUSED:
5253 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5254 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5255 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005256 }
chaviw93df2ea2019-04-30 16:45:12 -07005257 case CAPTURE_SCREEN_BY_ID: {
5258 IPCThreadState* ipc = IPCThreadState::self();
5259 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005260 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005261 return OK;
5262 }
5263 return PERMISSION_DENIED;
5264 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005265 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005266
5267 // These codes are used for the IBinder protocol to either interrogate the recipient
5268 // side of the transaction for its canonical interface descriptor or to dump its state.
5269 // We let them pass by default.
5270 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5271 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5272 code == IBinder::SYSPROPS_TRANSACTION) {
5273 return OK;
5274 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005275 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005276 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005277 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005278 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5279 return OK;
5280 }
5281 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5282 return PERMISSION_DENIED;
5283#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005284}
5285
Ana Krulec13be8ad2018-08-21 02:43:56 +00005286status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5287 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005288 status_t credentialCheck = CheckTransactCodeCredentials(code);
5289 if (credentialCheck != OK) {
5290 return credentialCheck;
5291 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005292
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005293 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5294 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005295 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005296 IPCThreadState* ipc = IPCThreadState::self();
5297 const int uid = ipc->getCallingUid();
5298 if (CC_UNLIKELY(uid != AID_SYSTEM
5299 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005300 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005301 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005302 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005303 return PERMISSION_DENIED;
5304 }
5305 int n;
5306 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005307 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005308 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005309 return NO_ERROR;
5310 case 1002: // SHOW_UPDATES
5311 n = data.readInt32();
5312 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005313 invalidateHwcGeometry();
5314 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005315 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005316 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005317 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005318 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005319 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005320 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005321 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005322 setTransactionFlags(
5323 eTransactionNeeded|
5324 eDisplayTransactionNeeded|
5325 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005326 return NO_ERROR;
5327 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005328 case 1006:{ // send empty update
5329 signalRefresh();
5330 return NO_ERROR;
5331 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005332 case 1008: // toggle use of hw composer
5333 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005334 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005335 invalidateHwcGeometry();
5336 repaintEverything();
5337 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005338 case 1009: // toggle use of transform hint
5339 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005340 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005341 invalidateHwcGeometry();
5342 repaintEverything();
5343 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005344 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005345 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005346 reply->writeInt32(0);
5347 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005348 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005349 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005350 return NO_ERROR;
5351 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005352 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005353 if (!display) {
5354 return NAME_NOT_FOUND;
5355 }
5356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005357 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005358 return NO_ERROR;
5359 }
5360 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005361 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005362 // daltonize
5363 n = data.readInt32();
5364 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005365 case 1:
5366 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5367 break;
5368 case 2:
5369 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5370 break;
5371 case 3:
5372 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5373 break;
5374 default:
5375 mDaltonizer.setType(ColorBlindnessType::None);
5376 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005377 }
5378 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005379 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005380 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005381 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005382 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005383
5384 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005385 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005386 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005387 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005388 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005389 // apply a color matrix
5390 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005391 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005392 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005393 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005394 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005395 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005396 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005397 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005398 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005399 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005400 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005401
5402 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5403 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005404 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005405 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5406 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5407 }
5408
Chia-I Wu28f320b2018-05-03 11:02:56 -07005409 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005410 return NO_ERROR;
5411 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005412 // This is an experimental interface
5413 // Needs to be shifted to proper binder interface when we productize
5414 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005415 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005416 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005417 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005418 return NO_ERROR;
5419 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005420 case 1017: {
5421 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005422 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005423 return NO_ERROR;
5424 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005425 case 1018: { // Modify Choreographer's phase offset
5426 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005427 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005428 return NO_ERROR;
5429 }
5430 case 1019: { // Modify SurfaceFlinger's phase offset
5431 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005432 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005433 return NO_ERROR;
5434 }
Irvel468051e2016-06-13 16:44:44 -07005435 case 1020: { // Layer updates interceptor
5436 n = data.readInt32();
5437 if (n) {
5438 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005439 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005440 }
5441 else{
5442 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005443 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005444 }
5445 return NO_ERROR;
5446 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005447 case 1021: { // Disable HWC virtual displays
5448 n = data.readInt32();
5449 mUseHwcVirtualDisplays = !n;
5450 return NO_ERROR;
5451 }
Romain Guy0147a172017-06-01 13:53:56 -07005452 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005453 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005454 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005455
Chia-I Wu28f320b2018-05-03 11:02:56 -07005456 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005457 return NO_ERROR;
5458 }
Romain Guy54f154a2017-10-24 21:40:32 +01005459 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005460 int32_t colorMode;
5461
Chia-I Wu0d711262018-05-21 15:19:35 -07005462 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005463 if (data.readInt32(&colorMode) == NO_ERROR) {
5464 mForceColorMode = static_cast<ColorMode>(colorMode);
5465 }
Romain Guy54f154a2017-10-24 21:40:32 +01005466 invalidateHwcGeometry();
5467 repaintEverything();
5468 return NO_ERROR;
5469 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005470 // Deprecate, use 1030 to check whether the device is color managed.
5471 case 1024: {
5472 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005473 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005474 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005475 n = data.readInt32();
5476 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005477 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005478 Mutex::Autolock lock(mStateLock);
5479 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005480 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005481 reply->writeInt32(NO_ERROR);
5482 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005483 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005484 bool writeFile = false;
5485 {
5486 Mutex::Autolock lock(mStateLock);
5487 mTracingEnabledChanged = true;
5488 writeFile = mTracing.disable();
5489 }
5490
5491 if (writeFile) {
5492 reply->writeInt32(mTracing.writeToFile());
5493 } else {
5494 reply->writeInt32(NO_ERROR);
5495 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005496 }
5497 return NO_ERROR;
5498 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005499 case 1026: { // Get layer tracing status
5500 reply->writeBool(mTracing.isEnabled());
5501 return NO_ERROR;
5502 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005503 // Is a DisplayColorSetting supported?
5504 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005505 const auto display = getDefaultDisplayDevice();
5506 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005507 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005508 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005509
5510 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5511 switch (setting) {
5512 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005513 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005514 break;
5515 case DisplayColorSetting::UNMANAGED:
5516 reply->writeBool(true);
5517 break;
5518 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005519 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005520 break;
5521 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005522 reply->writeBool(
5523 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005524 break;
5525 }
5526 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005527 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005528 // Is VrFlinger active?
5529 case 1028: {
5530 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005531 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005532 return NO_ERROR;
5533 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005534 // Set buffer size for SF tracing (value in KB)
5535 case 1029: {
5536 n = data.readInt32();
5537 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5538 ALOGW("Invalid buffer size: %d KB", n);
5539 reply->writeInt32(BAD_VALUE);
5540 return BAD_VALUE;
5541 }
5542
5543 ALOGD("Updating trace buffer to %d KB", n);
5544 mTracing.setBufferSize(n * 1024);
5545 reply->writeInt32(NO_ERROR);
5546 return NO_ERROR;
5547 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005548 // Is device color managed?
5549 case 1030: {
5550 reply->writeBool(useColorManagement);
5551 return NO_ERROR;
5552 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005553 // Override default composition data space
5554 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5555 // && adb shell stop zygote && adb shell start zygote
5556 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5557 // adb shell stop zygote && adb shell start zygote
5558 case 1031: {
5559 Mutex::Autolock _l(mStateLock);
5560 n = data.readInt32();
5561 if (n) {
5562 n = data.readInt32();
5563 if (n) {
5564 Dataspace dataspace = static_cast<Dataspace>(n);
5565 if (!validateCompositionDataspace(dataspace)) {
5566 return BAD_VALUE;
5567 }
5568 mDefaultCompositionDataspace = dataspace;
5569 }
5570 n = data.readInt32();
5571 if (n) {
5572 Dataspace dataspace = static_cast<Dataspace>(n);
5573 if (!validateCompositionDataspace(dataspace)) {
5574 return BAD_VALUE;
5575 }
5576 mWideColorGamutCompositionDataspace = dataspace;
5577 }
5578 } else {
5579 // restore composition data space.
5580 mDefaultCompositionDataspace = defaultCompositionDataspace;
5581 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5582 }
5583 return NO_ERROR;
5584 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005585 // Set trace flags
5586 case 1033: {
5587 n = data.readUint32();
5588 ALOGD("Updating trace flags to 0x%x", n);
5589 mTracing.setTraceFlags(n);
5590 reply->writeInt32(NO_ERROR);
5591 return NO_ERROR;
5592 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005593 case 1034: {
5594 // TODO(b/129297325): expose this via developer menu option
5595 n = data.readInt32();
5596 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005597 RefreshRateType type;
5598 {
5599 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5600 type = mDesiredActiveConfig.type;
5601 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005602 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005603 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005604 } else if (!n) {
5605 mRefreshRateOverlay.reset();
5606 }
5607 return NO_ERROR;
5608 }
Ady Abraham34392f72019-04-10 11:29:27 -07005609 case 1035: {
5610 n = data.readInt32();
5611 mDebugDisplayConfigSetByBackdoor = false;
5612 if (n >= 0) {
5613 const auto displayToken = getInternalDisplayToken();
5614 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5615 if (result != NO_ERROR) {
5616 return result;
5617 }
5618 mDebugDisplayConfigSetByBackdoor = true;
5619 }
5620 return NO_ERROR;
5621 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005622 }
5623 }
5624 return err;
5625}
5626
Steven Thomas6d8110b2017-08-31 18:24:21 -07005627void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005628 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005629 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005630}
5631
Ana Krulec7d1d6832018-12-27 11:10:09 -08005632void SurfaceFlinger::repaintEverythingForHWC() {
5633 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005634 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005635}
5636
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005637// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5638class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005639public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005640 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5641 ~WindowDisconnector() {
5642 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005643 }
5644
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005645private:
5646 ANativeWindow* mWindow;
5647 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005648};
5649
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005650status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005651 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5652 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005653 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005654 uint32_t reqWidth, uint32_t reqHeight,
5655 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005656 ISurfaceComposer::Rotation rotation,
5657 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005658 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005659
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005660 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005661
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005662 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5663
Chia-I Wu20261cb2018-08-23 12:55:44 -07005664 sp<DisplayDevice> display;
5665 {
5666 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005667
Chia-I Wu20261cb2018-08-23 12:55:44 -07005668 display = getDisplayDeviceLocked(displayToken);
5669 if (!display) return BAD_VALUE;
5670
Chia-I Wucb023152018-08-28 12:57:23 -07005671 // set the requested width/height to the logical display viewport size
5672 // by default
5673 if (reqWidth == 0 || reqHeight == 0) {
5674 reqWidth = uint32_t(display->getViewport().width());
5675 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005676 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005677 }
5678
Peiyong Lin0e003c92018-09-17 11:09:51 -07005679 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005680 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005681
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005682 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5683 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005684 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005685 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005686}
5687
chaviw93df2ea2019-04-30 16:45:12 -07005688static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5689 switch (colorMode) {
5690 case ColorMode::DISPLAY_P3:
5691 case ColorMode::BT2100_PQ:
5692 case ColorMode::BT2100_HLG:
5693 case ColorMode::DISPLAY_BT2020:
5694 return Dataspace::DISPLAY_P3;
5695 default:
5696 return Dataspace::V0_SRGB;
5697 }
5698}
5699
5700const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5701 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5702 if (displayToken) {
5703 return getDisplayDeviceLocked(displayToken);
5704 }
5705 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5706 // may not have a displayId.
5707 for (const auto& [token, display] : mDisplays) {
5708 if (display->getLayerStack() == displayOrLayerStack) {
5709 return display;
5710 }
5711 }
5712 return nullptr;
5713}
5714
5715status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5716 sp<GraphicBuffer>* outBuffer) {
5717 sp<DisplayDevice> display;
5718 uint32_t width;
5719 uint32_t height;
5720 ui::Transform::orientation_flags captureOrientation;
5721 {
5722 Mutex::Autolock _l(mStateLock);
5723 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5724 if (!display) {
5725 return BAD_VALUE;
5726 }
5727
5728 width = uint32_t(display->getViewport().width());
5729 height = uint32_t(display->getViewport().height());
5730
5731 captureOrientation = fromSurfaceComposerRotation(
5732 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005733 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5734 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5735 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5736 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5737 }
chaviw93df2ea2019-04-30 16:45:12 -07005738 *outDataspace =
5739 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5740 }
5741
5742 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5743 false /* captureSecureLayers */);
5744
5745 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5746 std::placeholders::_1);
5747 bool ignored = false;
5748 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5749 false /* useIdentityTransform */,
5750 ignored /* outCapturedSecureLayers */);
5751}
5752
Robert Carr866455f2019-04-02 16:28:26 -07005753status_t SurfaceFlinger::captureLayers(
5754 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5755 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5756 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5757 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005758 ATRACE_CALL();
5759
5760 class LayerRenderArea : public RenderArea {
5761 public:
Robert Carr578038f2018-03-09 12:25:24 -08005762 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005763 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5764 bool childrenOnly)
5765 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005766 mLayer(layer),
5767 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005768 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005769 mFlinger(flinger),
5770 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005771 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005772 Rect getBounds() const override {
5773 const Layer::State& layerState(mLayer->getDrawingState());
5774 return mLayer->getBufferSize(layerState);
5775 }
Marissa Wall61c58622018-07-18 10:12:20 -07005776 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005777 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005778 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005779 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005780 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005781 }
chaviwa76b2712017-09-20 12:02:26 -07005782 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005783 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005784 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005785 Rect getSourceCrop() const override {
5786 if (mCrop.isEmpty()) {
5787 return getBounds();
5788 } else {
5789 return mCrop;
5790 }
5791 }
Robert Carr578038f2018-03-09 12:25:24 -08005792 class ReparentForDrawing {
5793 public:
5794 const sp<Layer>& oldParent;
5795 const sp<Layer>& newParent;
5796
Vishnu Nair4351ad52019-02-11 14:13:02 -08005797 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5798 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005799 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005800 // Compute and cache the bounds for the new parent layer.
5801 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005802 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005803 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005804 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005805 };
5806
5807 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005808 const Rect sourceCrop = getSourceCrop();
5809 // no need to check rotation because there is none
5810 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5811 sourceCrop.height() != getReqHeight();
5812
Robert Carr578038f2018-03-09 12:25:24 -08005813 if (!mChildrenOnly) {
5814 mTransform = mLayer->getTransform().inverse();
5815 drawLayers();
5816 } else {
5817 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005818 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005819 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005820 bounds.getWidth(), bounds.getHeight(), 0,
5821 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005822
Vishnu Nair4351ad52019-02-11 14:13:02 -08005823 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005824 drawLayers();
5825 }
5826 }
chaviwa76b2712017-09-20 12:02:26 -07005827
chaviwa76b2712017-09-20 12:02:26 -07005828 private:
chaviw7206d492017-11-10 16:16:12 -08005829 const sp<Layer> mLayer;
5830 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005831
5832 // In the "childrenOnly" case we reparent the children to a screenshot
5833 // layer which has no properties set and which does not draw.
5834 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005835 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005836 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005837
5838 SurfaceFlinger* mFlinger;
5839 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005840 };
5841
Robert Carrc0df3122019-04-11 13:18:21 -07005842 int reqWidth = 0;
5843 int reqHeight = 0;
5844 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005845 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005846 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005847
Robert Carrc0df3122019-04-11 13:18:21 -07005848 {
5849 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005850
Robert Carrc0df3122019-04-11 13:18:21 -07005851 parent = fromHandle(layerHandleBinder);
5852 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5853 ALOGE("captureLayers called with an invalid or removed parent");
5854 return NAME_NOT_FOUND;
5855 }
5856
5857 const int uid = IPCThreadState::self()->getCallingUid();
5858 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5859 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5860 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5861 return PERMISSION_DENIED;
5862 }
5863
5864 if (sourceCrop.width() <= 0) {
5865 crop.left = 0;
5866 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5867 }
5868
5869 if (sourceCrop.height() <= 0) {
5870 crop.top = 0;
5871 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5872 }
5873 reqWidth = crop.width() * frameScale;
5874 reqHeight = crop.height() * frameScale;
5875
5876 for (const auto& handle : excludeHandles) {
5877 sp<Layer> excludeLayer = fromHandle(handle);
5878 if (excludeLayer != nullptr) {
5879 excludeLayers.emplace(excludeLayer);
5880 } else {
5881 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5882 return NAME_NOT_FOUND;
5883 }
5884 }
5885 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005886
Chia-I Wu20261cb2018-08-23 12:55:44 -07005887 // really small crop or frameScale
5888 if (reqWidth <= 0) {
5889 reqWidth = 1;
5890 }
5891 if (reqHeight <= 0) {
5892 reqHeight = 1;
5893 }
5894
Robert Carr866455f2019-04-02 16:28:26 -07005895 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5896 auto traverseLayers = [parent, childrenOnly,
5897 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005898 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5899 if (!layer->isVisible()) {
5900 return;
Robert Carr578038f2018-03-09 12:25:24 -08005901 } else if (childrenOnly && layer == parent.get()) {
5902 return;
chaviwa76b2712017-09-20 12:02:26 -07005903 }
Robert Carr866455f2019-04-02 16:28:26 -07005904
5905 sp<Layer> p = layer;
5906 while (p != nullptr) {
5907 if (excludeLayers.count(p) != 0) {
5908 return;
5909 }
5910 p = p->getParent();
5911 }
5912
chaviwa76b2712017-09-20 12:02:26 -07005913 visitor(layer);
5914 });
5915 };
Robert Carr108b2c72019-04-02 16:32:58 -07005916
5917 bool outCapturedSecureLayers = false;
5918 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5919 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005920}
5921
5922status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5923 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005924 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005925 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005926 bool useIdentityTransform,
5927 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005928 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005929
Peiyong Lin0e003c92018-09-17 11:09:51 -07005930 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005931 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5932 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005933 *outBuffer =
5934 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5935 static_cast<android_pixel_format>(reqPixelFormat), 1,
5936 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005937
Robert Carr108b2c72019-04-02 16:32:58 -07005938 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5939 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005940}
5941
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005942status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5943 TraverseLayersFunction traverseLayers,
5944 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005945 bool useIdentityTransform,
5946 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005947 // This mutex protects syncFd and captureResult for communication of the return values from the
5948 // main thread back to this Binder thread
5949 std::mutex captureMutex;
5950 std::condition_variable captureCondition;
5951 std::unique_lock<std::mutex> captureLock(captureMutex);
5952 int syncFd = -1;
5953 std::optional<status_t> captureResult;
5954
Robert Carr03480e22018-01-04 16:02:06 -08005955 const int uid = IPCThreadState::self()->getCallingUid();
5956 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5957
Dominik Laskowski8c001672018-05-30 16:52:06 -07005958 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005959 // If there is a refresh pending, bug out early and tell the binder thread to try again
5960 // after the refresh.
5961 if (mRefreshPending) {
5962 ATRACE_NAME("Skipping screenshot for now");
5963 std::unique_lock<std::mutex> captureLock(captureMutex);
5964 captureResult = std::make_optional<status_t>(EAGAIN);
5965 captureCondition.notify_one();
5966 return;
5967 }
5968
5969 status_t result = NO_ERROR;
5970 int fd = -1;
5971 {
5972 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005973 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005974 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005975 useIdentityTransform, forSystem, &fd,
5976 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005977 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005978 }
5979
5980 {
5981 std::unique_lock<std::mutex> captureLock(captureMutex);
5982 syncFd = fd;
5983 captureResult = std::make_optional<status_t>(result);
5984 captureCondition.notify_one();
5985 }
5986 });
5987
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005988 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005989 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005990 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005991 while (*captureResult == EAGAIN) {
5992 captureResult.reset();
5993 result = postMessageAsync(message);
5994 if (result != NO_ERROR) {
5995 return result;
5996 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005997 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005998 }
5999 result = *captureResult;
6000 }
6001
6002 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006003 sync_wait(syncFd, -1);
6004 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006005 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006006
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006007 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006008}
6009
chaviwa76b2712017-09-20 12:02:26 -07006010void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006011 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006012 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6013 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006014 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006015
chaviwa76b2712017-09-20 12:02:26 -07006016 const auto reqWidth = renderArea.getReqWidth();
6017 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006018 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006019 const auto transform = renderArea.getTransform();
6020 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006021
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006022 renderengine::DisplaySettings clientCompositionDisplay;
6023 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006024
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006025 // assume that bounds are never offset, and that they are the same as the
6026 // buffer bounds.
6027 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006028 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006029 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006030
6031 // Now take into account the rotation flag. We append a transform that
6032 // rotates the layer stack about the origin, then translate by buffer
6033 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006034 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006035 int displacementX = 0;
6036 int displacementY = 0;
6037 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6038 switch (rotation) {
6039 case ui::Transform::ROT_90:
6040 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006041 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006042 break;
6043 case ui::Transform::ROT_180:
6044 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006045 displacementY = renderArea.getBounds().getWidth();
6046 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006047 break;
6048 case ui::Transform::ROT_270:
6049 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006050 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006051 break;
6052 default:
6053 break;
6054 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006055
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006056 // We need to transform the clipping window into the right spot.
6057 // First, rotate the clipping rectangle by the rotation hint to get the
6058 // right orientation
6059 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6060 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6061 const vec4 rotClipTL = rotMatrix * clipTL;
6062 const vec4 rotClipBR = rotMatrix * clipBR;
6063 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6064 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6065 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6066 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6067
6068 // Now reposition the clipping rectangle with the displacement vector
6069 // computed above.
6070 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006071 clientCompositionDisplay.clip =
6072 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6073 newClipRight + displacementX, newClipBottom + displacementY);
6074
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006075 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006076 clientCompositionDisplay.globalTransform =
6077 clipTransform * clientCompositionDisplay.globalTransform;
6078
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006079 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6080 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006081
chaviw50da5042018-04-09 13:49:37 -07006082 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006083
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006084 renderengine::LayerSettings fillLayer;
6085 fillLayer.source.buffer.buffer = nullptr;
6086 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6087 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6088 fillLayer.alpha = half(alpha);
6089 clientCompositionLayers.push_back(fillLayer);
6090
6091 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006092 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006093 renderengine::LayerSettings layerSettings;
6094 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006095 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006096 if (prepared) {
6097 clientCompositionLayers.push_back(layerSettings);
6098 }
chaviwa76b2712017-09-20 12:02:26 -07006099 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006100
6101 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006102 // Use an empty fence for the buffer fence, since we just created the buffer so
6103 // there is no need for synchronization with the GPU.
6104 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006105 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006106 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006107 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006108 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006109
6110 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006111}
6112
chaviwa76b2712017-09-20 12:02:26 -07006113status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6114 TraverseLayersFunction traverseLayers,
6115 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006116 bool useIdentityTransform, bool forSystem,
6117 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006118 ATRACE_CALL();
6119
chaviwa76b2712017-09-20 12:02:26 -07006120 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006121 outCapturedSecureLayers =
6122 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006123 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006124
Robert Carr03480e22018-01-04 16:02:06 -08006125 // We allow the system server to take screenshots of secure layers for
6126 // use in situations like the Screen-rotation animation and place
6127 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006128 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006129 ALOGW("FB is protected: PERMISSION_DENIED");
6130 return PERMISSION_DENIED;
6131 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006132 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006133 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006134}
6135
chaviw95ef3c42019-02-14 10:55:09 -08006136void SurfaceFlinger::setInputWindowsFinished() {
6137 Mutex::Autolock _l(mStateLock);
6138
6139 mPendingSyncInputWindows = false;
6140 mTransactionCV.broadcast();
6141}
chaviw5f21a5e2019-02-14 10:00:34 -08006142
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006143// ---------------------------------------------------------------------------
6144
Dan Stoza412903f2017-04-27 13:42:17 -07006145void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6146 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006147}
6148
Dan Stoza412903f2017-04-27 13:42:17 -07006149void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6150 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006151}
6152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006153void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006154 const LayerVector::Visitor& visitor) {
6155 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006156 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006157 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006158 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006159 continue;
6160 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006161 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006162 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006163 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006164 return;
6165 }
chaviwa76b2712017-09-20 12:02:26 -07006166 if (!layer->isVisible()) {
6167 return;
6168 }
6169 visitor(layer);
6170 });
6171 }
6172}
6173
Dominik Laskowski22488f62019-03-28 09:53:04 -07006174void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6175 const std::vector<int32_t>& allowedConfigs) {
6176 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006177 return;
6178 }
6179
6180 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006181 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006182
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006183 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006184 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006185 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006186 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006187 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006188 setDesiredActiveConfig(
6189 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006190 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006191 }
6192 }
Ady Abraham838de062019-02-04 10:24:03 -08006193}
6194
Dominik Laskowski22488f62019-03-28 09:53:04 -07006195status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006196 const std::vector<int32_t>& allowedConfigs) {
6197 ATRACE_CALL();
6198
Dominik Laskowski22488f62019-03-28 09:53:04 -07006199 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006200 return BAD_VALUE;
6201 }
6202
Ady Abraham34392f72019-04-10 11:29:27 -07006203 if (mDebugDisplayConfigSetByBackdoor) {
6204 // ignore this request as config is overridden by backdoor
6205 return NO_ERROR;
6206 }
6207
Ady Abraham838de062019-02-04 10:24:03 -08006208 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006209 const auto display = getDisplayDeviceLocked(displayToken);
6210 if (!display) {
6211 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6212 displayToken.get());
6213 } else if (display->isVirtual()) {
6214 ALOGW("Attempt to set allowed display configs for virtual display");
6215 } else {
6216 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6217 }
Ady Abraham838de062019-02-04 10:24:03 -08006218 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006219
Ady Abraham838de062019-02-04 10:24:03 -08006220 return NO_ERROR;
6221}
6222
Dominik Laskowski22488f62019-03-28 09:53:04 -07006223status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006224 std::vector<int32_t>* outAllowedConfigs) {
6225 ATRACE_CALL();
6226
Dominik Laskowski22488f62019-03-28 09:53:04 -07006227 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006228 return BAD_VALUE;
6229 }
6230
Dominik Laskowski22488f62019-03-28 09:53:04 -07006231 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006232
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006233 const auto display = getDisplayDeviceLocked(displayToken);
6234 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006235 return NAME_NOT_FOUND;
6236 }
6237
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006238 if (display->isPrimary()) {
6239 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6240 }
6241
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006242 return NO_ERROR;
6243}
6244
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006245void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006246 mFlinger->setInputWindowsFinished();
6247}
6248
Robert Carrc0df3122019-04-11 13:18:21 -07006249sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6250 BBinder *b = handle->localBinder();
6251 if (b == nullptr) {
6252 return nullptr;
6253 }
6254 auto it = mLayersByLocalBinderToken.find(b);
6255 if (it != mLayersByLocalBinderToken.end()) {
6256 return it->second.promote();
6257 }
6258 return nullptr;
6259}
6260
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006261} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006262
Mathias Agopian3f844832013-08-07 21:24:32 -07006263#if defined(__gl_h_)
6264#error "don't include gl/gl.h in this file"
6265#endif
6266
6267#if defined(__gl2_h_)
6268#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006269#endif