blob: 210a28ad4d7dc10a4dce4e236891af9f8c2d99a6 [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),
279 mPhaseOffsets(mFactory.createPhaseOffsets()),
280 mInterceptor(mFactory.createSurfaceInterceptor(this)),
281 mTimeStats(mFactory.createTimeStats()),
282 mEventQueue(mFactory.createMessageQueue()),
283 mCompositionEngine(mFactory.createCompositionEngine()) {}
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
Ana Krulec757f63a2019-01-25 10:46:18 -0800389 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700390 mVsyncModulator.setPhaseOffsets(early, gl, late,
391 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700392
Romain Guy11d63f42017-07-20 12:47:14 -0700393 // We should be reading 'persist.sys.sf.color_saturation' here
394 // but since /data may be encrypted, we need to wait until after vold
395 // comes online to attempt to read the property. The property is
396 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800397
398 if (useTrebleTestingOverride()) {
399 // Without the override SurfaceFlinger cannot connect to HIDL
400 // services that are not listed in the manifests. Considered
401 // deriving the setting from the set service name, but it
402 // would be brittle if the name that's not 'default' is used
403 // for production purposes later on.
404 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
405 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406}
407
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408void SurfaceFlinger::onFirstRef()
409{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800410 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700413SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
418
Andy McFadden13a082e2012-08-24 10:16:42 -0700419 // restore initial conditions (default device unblank, etc)
420 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421
422 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700423 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
Robert Carr1db73f62016-12-21 12:58:51 -0800426static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700427 status_t err = client->initCheck();
428 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return nullptr;
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
435 return initClient(new Client(this));
436}
437
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700438sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
439 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440{
441 class DisplayToken : public BBinder {
442 sp<SurfaceFlinger> flinger;
443 virtual ~DisplayToken() {
444 // no more references, this display must be terminated
445 Mutex::Autolock _l(flinger->mStateLock);
446 flinger->mCurrentState.displays.removeItem(this);
447 flinger->setTransactionFlags(eDisplayTransactionNeeded);
448 }
449 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700450 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 : flinger(flinger) {
452 }
453 };
454
455 sp<BBinder> token = new DisplayToken(this);
456
457 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 // Display ID is assigned when virtual display is allocated by HWC.
459 DisplayDeviceState state;
460 state.isSecure = secure;
461 state.displayName = displayName;
462 mCurrentState.displays.add(token, state);
463 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 return token;
465}
466
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700467void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700468 Mutex::Autolock _l(mStateLock);
469
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
471 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700472 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 return;
474 }
475
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
477 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 ALOGE("destroyDisplay called for non-virtual display");
479 return;
480 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 mInterceptor->saveDisplayDeletion(state.sequenceId);
482 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 setTransactionFlags(eDisplayTransactionNeeded);
484}
485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
487 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800489 const auto internalDisplayId = getInternalDisplayIdLocked();
490 if (!internalDisplayId) {
491 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 }
493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800494 std::vector<PhysicalDisplayId> displayIds;
495 displayIds.reserve(mPhysicalDisplayTokens.size());
496 displayIds.push_back(internalDisplayId->value);
497
498 for (const auto& [id, token] : mPhysicalDisplayTokens) {
499 if (id != *internalDisplayId) {
500 displayIds.push_back(id.value);
501 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504 return displayIds;
505}
506
507sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
508 Mutex::Autolock lock(mStateLock);
509 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510}
511
Ady Abraham37965d42018-11-01 13:43:32 -0700512status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
513 if (!outGetColorManagement) {
514 return BAD_VALUE;
515 }
516 *outGetColorManagement = useColorManagement;
517 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700518}
519
Lloyd Pique441d5042018-10-18 16:49:51 -0700520HWComposer& SurfaceFlinger::getHwComposer() const {
521 return mCompositionEngine->getHwComposer();
522}
523
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700524renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
525 return mCompositionEngine->getRenderEngine();
526}
527
Lloyd Pique70d91362018-10-18 16:02:55 -0700528compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
529 return *mCompositionEngine.get();
530}
531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532void SurfaceFlinger::bootFinished()
533{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534 if (mStartPropertySetThread->join() != NO_ERROR) {
535 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const nsecs_t now = systemTime();
538 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000539 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
541 // wait patiently for the window manager death
542 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700543 mWindowManager = defaultServiceManager()->getService(name);
544 if (mWindowManager != 0) {
545 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 readPersistentProperties();
570 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571
Ady Abraham97d04232019-03-05 19:48:12 -0800572 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700573 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700574 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800575
Dominik Laskowski22488f62019-03-28 09:53:04 -0700576 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800577 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800578 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800579 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800580 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800581 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800582}
583
Dan Stoza436ccf32018-06-21 12:10:12 -0700584uint32_t SurfaceFlinger::getNewTexture() {
585 {
586 std::lock_guard lock(mTexturePoolMutex);
587 if (!mTexturePool.empty()) {
588 uint32_t name = mTexturePool.back();
589 mTexturePool.pop_back();
590 ATRACE_INT("TexturePoolSize", mTexturePool.size());
591 return name;
592 }
593
594 // The pool was too small, so increase it for the future
595 ++mTexturePoolSize;
596 }
597
598 // The pool was empty, so we need to get a new texture name directly using a
599 // blocking call to the main thread
600 uint32_t name = 0;
601 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
602 return name;
603}
604
Mathias Agopian3f844832013-08-07 21:24:32 -0700605void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700606 std::lock_guard lock(mTexturePoolMutex);
607 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
608 // to actually delete this or not based on mTexturePoolSize
609 mTexturePool.push_back(texture);
610 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700611}
612
Wei Wangf9b05ee2017-07-19 20:59:39 -0700613// Do not call property_set on main thread which will be blocked by init
614// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700616 ALOGI( "SurfaceFlinger's main thread ready to run. "
617 "Initializing graphics H/W...");
618
Ana Krulec757f63a2019-01-25 10:46:18 -0800619 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900620
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800623 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700624 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
625 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800626 auto resyncCallback =
627 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800628
Ana Krulecc2870422019-01-29 19:00:58 -0800629 mAppConnectionHandle =
Ady Abraham45e4e362019-06-07 18:20:51 -0700630 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
631 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800632 resyncCallback,
633 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700634 mSfConnectionHandle =
635 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
636 mPhaseOffsets->getOffsetThresholdForNextVsync(),
637 resyncCallback, [this](nsecs_t timestamp) {
638 mInterceptor->saveVSyncEvent(timestamp);
639 });
Ana Krulecc2870422019-01-29 19:00:58 -0800640
641 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
642 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
643 mSfConnectionHandle.get());
644
Kevin DuBois413287f2019-02-25 08:46:47 -0800645 mRegionSamplingThread =
646 new RegionSamplingThread(*this, *mScheduler,
647 RegionSamplingThread::EnvironmentTimingTunables());
648
Steven Thomasb02664d2017-07-26 18:48:28 -0700649 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700650 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700651 renderEngineFeature |= (useColorManagement ?
652 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700653 renderEngineFeature |= (useContextPriority ?
654 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700655 renderEngineFeature |=
656 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
657 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700658
659 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800660 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700661 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700662 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800663 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700664
665 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
666 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700667 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
668 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 const auto display = getDefaultDisplayDeviceLocked();
672 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700673 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800675
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 // This callback is called from the vr flinger dispatch thread. We
679 // need to call signalTransaction(), which requires holding
680 // mStateLock when we're not on the main thread. Acquiring
681 // mStateLock from the vr flinger dispatch thread might trigger a
682 // deadlock in surface flinger (see b/66916578), so post a message
683 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
686 mVrFlingerRequestsDisplay = requestDisplay;
687 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
691 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700692 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 .value_or(0),
694 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 if (!mVrFlinger) {
696 ALOGE("Failed to start vrflinger");
697 }
698 }
699
Mathias Agopian92a979a2012-08-02 18:32:23 -0700700 // initialize our drawing state
701 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700702
Andy McFadden13a082e2012-08-24 10:16:42 -0700703 // set initial conditions (e.g. unblank default device)
704 initializeDisplays();
705
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700706 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700707
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709
710 const bool presentFenceReliable =
711 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
712 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Alec Mouri93bc83d2019-04-17 14:47:43 -0700718 mScheduler->setChangeRefreshRateCallback(
719 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
720 Mutex::Autolock lock(mStateLock);
721 setRefreshRateTo(type, event);
722 });
Alec Mouri7f015182019-07-11 13:56:22 -0700723 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
724 Mutex::Autolock lock(mStateLock);
725 const auto display = getDefaultDisplayDeviceLocked();
726 if (!display) {
727 // If we don't have a default display the fallback to the default
728 // refresh rate type
729 return RefreshRateType::DEFAULT;
730 }
731
732 const int configId = display->getActiveConfig();
733 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
734 if (refresh && refresh->configId == configId) {
735 return type;
736 }
737 }
738 // This should never happen, but just gracefully fallback to default.
739 return RefreshRateType::DEFAULT;
740 });
Alec Mouridc28b372019-04-18 21:17:13 -0700741 mScheduler->setGetVsyncPeriodCallback([this] {
742 Mutex::Autolock lock(mStateLock);
743 return getVsyncPeriod();
744 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
747 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700763 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800764
765 property_get("persist.sys.sf.color_mode", value, "0");
766 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700767}
768
Mathias Agopiana67e4182012-06-19 17:26:12 -0700769void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800770 // Start boot animation service by setting a property mailbox
771 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700772 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700774 if (mStartPropertySetThread->join() != NO_ERROR) {
775 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800776 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700777}
778
Mathias Agopian875d8e12013-06-07 15:35:48 -0700779size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700780 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700781}
782
Mathias Agopian875d8e12013-06-07 15:35:48 -0700783size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700784 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700785}
786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800787// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800788
Jamie Gennis582270d2011-08-17 18:19:00 -0700789bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800790 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800791 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800792 return authenticateSurfaceTextureLocked(bufferProducer);
793}
794
795bool SurfaceFlinger::authenticateSurfaceTextureLocked(
796 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800797 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800798 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800799}
800
Brian Anderson6b376712017-04-04 10:51:39 -0700801status_t SurfaceFlinger::getSupportedFrameTimestamps(
802 std::vector<FrameEvent>* outSupported) const {
803 *outSupported = {
804 FrameEvent::REQUESTED_PRESENT,
805 FrameEvent::ACQUIRE,
806 FrameEvent::LATCH,
807 FrameEvent::FIRST_REFRESH_START,
808 FrameEvent::LAST_REFRESH_START,
809 FrameEvent::GPU_COMPOSITION_DONE,
810 FrameEvent::DEQUEUE_READY,
811 FrameEvent::RELEASE,
812 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700813 ConditionalLock _l(mStateLock,
814 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700815 if (!getHwComposer().hasCapability(
816 HWC2::Capability::PresentFenceIsNotReliable)) {
817 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
818 }
819 return NO_ERROR;
820}
821
Dominik Laskowski22488f62019-03-28 09:53:04 -0700822status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
823 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 return BAD_VALUE;
826 }
827
Dominik Laskowski22488f62019-03-28 09:53:04 -0700828 Mutex::Autolock lock(mStateLock);
829
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800830 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700831 if (!displayId) {
832 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 // TODO: Not sure if display density should handled by SF any longer
836 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700839 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843 return density;
844 }
845 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700846 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("ro.sf.lcd_density"); }
850 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Dominik Laskowski075d3172018-05-24 15:50:06 -0700854 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 DisplayInfo info = DisplayInfo();
856
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857 float xdpi = hwConfig->getDpiX();
858 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700859
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700860 info.w = hwConfig->getWidth();
861 info.h = hwConfig->getHeight();
862 // Default display viewport to display width and height
863 info.viewportW = info.w;
864 info.viewportH = info.h;
865
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800866 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 // The density of the device is provided by a build property
868 float density = Density::getBuildDensity() / 160.0f;
869 if (density == 0) {
870 // the build doesn't provide a density -- this is wrong!
871 // use xdpi instead
872 ALOGE("ro.sf.lcd_density must be defined as a build property");
873 density = xdpi / 160.0f;
874 }
875 if (Density::getEmuDensity()) {
876 // if "qemu.sf.lcd_density" is specified, it overrides everything
877 xdpi = ydpi = density = Density::getEmuDensity();
878 density /= 160.0f;
879 }
880 info.density = density;
881
882 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700883 const auto display = getDefaultDisplayDeviceLocked();
884 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700885
886 // This is for screenrecord
887 const Rect viewport = display->getViewport();
888 if (viewport.isValid()) {
889 info.viewportW = uint32_t(viewport.getWidth());
890 info.viewportH = uint32_t(viewport.getHeight());
891 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 } else {
893 // TODO: where should this value come from?
894 static const int TV_DENSITY = 213;
895 info.density = TV_DENSITY / 160.0f;
896 info.orientation = 0;
897 }
898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 info.xdpi = xdpi;
900 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700902 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
903 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
904 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905
Andy McFadden91b2ca82014-06-13 14:04:23 -0700906 // This is how far in advance a buffer must be queued for
907 // presentation at a given time. If you want a buffer to appear
908 // on the screen at time N, you must submit the buffer before
909 // (N - presentationDeadline).
910 //
911 // Normally it's one full refresh period (to give SF a chance to
912 // latch the buffer), but this can be reduced by configuring a
913 // DispSync offset. Any additional delays introduced by the hardware
914 // composer or panel must be accounted for here.
915 //
916 // We add an additional 1ms to allow for processing time and
917 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700918 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700919
920 // All non-virtual displays are currently considered secure.
921 info.secure = true;
922
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800923 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700924 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800925 std::swap(info.w, info.h);
926 }
927
Michael Wright28f24d02016-07-12 13:30:53 -0700928 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700929 }
930
Dan Stoza7f7da322014-05-02 15:26:25 -0700931 return NO_ERROR;
932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
935 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700936 return BAD_VALUE;
937 }
938
Ana Krulecc2870422019-01-29 19:00:58 -0800939 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700940 return NO_ERROR;
941}
942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
944 const auto display = getDisplayDevice(displayToken);
945 if (!display) {
946 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800947 return BAD_VALUE;
948 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700951}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700952
Ady Abraham03b02dd2019-03-21 15:40:11 -0700953void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800955
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800957 // config twice. However event generation config might have changed so we need to update it
958 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800959 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700960 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
961 mDesiredActiveConfig = info;
962 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963
964 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800965 // This will trigger HWC refresh without resetting the idle timer.
966 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700967 // Start receiving vsync samples now, so that we can detect a period
968 // switch.
969 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700970 // As we called to set period, we will call to onRefreshRateChangeCompleted once
971 // DispSync model is locked.
972 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700973 mPhaseOffsets->setRefreshRateType(info.type);
974 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700975 mVsyncModulator.setPhaseOffsets(early, gl, late,
976 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700979
980 if (mRefreshRateOverlay) {
981 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
982 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983}
984
985status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
986 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800987
988 std::vector<int32_t> allowedConfig;
989 allowedConfig.push_back(mode);
990
991 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992}
993
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994void SurfaceFlinger::setActiveConfigInternal() {
995 ATRACE_CALL();
996
Dominik Laskowski22488f62019-03-28 09:53:04 -0700997 const auto display = getDefaultDisplayDeviceLocked();
998 if (!display) {
999 return;
1000 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001001
Dominik Laskowski22488f62019-03-28 09:53:04 -07001002 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1003 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
1004
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005 display->setActiveConfig(mUpcomingActiveConfig.configId);
1006
Alec Mouri754c98a2019-03-18 18:53:42 -07001007 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001008 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001009 mVsyncModulator.setPhaseOffsets(early, gl, late,
1010 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001012
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001013 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001014 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1015 mUpcomingActiveConfig.configId);
1016 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017}
1018
Ady Abraham53852a52019-05-28 18:07:44 -07001019void SurfaceFlinger::desiredActiveConfigChangeDone() {
1020 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1021 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1022 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001023
1024 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1025 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1026 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001027 mVsyncModulator.setPhaseOffsets(early, gl, late,
1028 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -07001029}
1030
Dominik Laskowski22488f62019-03-28 09:53:04 -07001031bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001032 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001033 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001034 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001036 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 return true;
1038 }
1039
1040 // We received the present fence from the HWC, so we assume it successfully updated
1041 // the config, hence we update SF.
1042 mCheckPendingFence = false;
1043 setActiveConfigInternal();
1044 }
1045
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001046 // Store the local variable to release the lock.
1047 ActiveConfigInfo desiredActiveConfig;
1048 {
1049 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050 if (!mDesiredActiveConfigChanged) {
1051 return false;
1052 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001053 desiredActiveConfig = mDesiredActiveConfig;
1054 }
1055
Dominik Laskowski22488f62019-03-28 09:53:04 -07001056 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001057 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1058 // display is not valid or we are already in the requested mode
1059 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001060 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001061 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001063
Ady Abraham838de062019-02-04 10:24:03 -08001064 // Desired active config was set, it is different than the config currently in use, however
1065 // allowed configs might have change by the time we process the refresh.
1066 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001067 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001068 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001069 return false;
1070 }
Alec Mouri7f015182019-07-11 13:56:22 -07001071
Ady Abrahamb838aed2019-02-12 15:30:16 -08001072 mUpcomingActiveConfig = desiredActiveConfig;
1073 const auto displayId = display->getId();
1074 LOG_ALWAYS_FATAL_IF(!displayId);
1075
1076 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1077 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1078
1079 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001080 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001081 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001083}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1086 Vector<ColorMode>* outColorModes) {
1087 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001088 return BAD_VALUE;
1089 }
1090
Peiyong Lina52f0292018-03-14 17:26:31 -07001091 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001092 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001093 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001094 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1095
1096 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1097 if (!displayId) {
1098 return NAME_NOT_FOUND;
1099 }
1100
Dominik Laskowski075d3172018-05-24 15:50:06 -07001101 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001102 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001103 }
Michael Wright28f24d02016-07-12 13:30:53 -07001104 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001105
1106 // If it's built-in display and the configuration claims it's not wide color capable,
1107 // filter out all wide color modes. The typical reason why this happens is that the
1108 // hardware is not good enough to support GPU composition of wide color, and thus the
1109 // OEMs choose to disable this capability.
1110 if (isInternalDisplay && !hasWideColorDisplay) {
1111 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1112 isWideColorMode);
1113 } else {
1114 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1115 }
Michael Wright28f24d02016-07-12 13:30:53 -07001116
1117 return NO_ERROR;
1118}
1119
Daniel Solomon42d04562019-01-20 21:03:19 -08001120status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1121 ui::DisplayPrimaries &primaries) {
1122 if (!displayToken) {
1123 return BAD_VALUE;
1124 }
1125
1126 // Currently we only support this API for a single internal display.
1127 if (getInternalDisplayToken() != displayToken) {
1128 return BAD_VALUE;
1129 }
1130
1131 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1132 return NO_ERROR;
1133}
1134
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001135ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1136 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001137 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001138 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001139 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001140}
1141
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001142status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001143 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001144 Vector<ColorMode> modes;
1145 getDisplayColorModes(displayToken, &modes);
1146 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1147 if (mode < ColorMode::NATIVE || !exists) {
1148 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1149 decodeColorMode(mode).c_str(), mode, displayToken.get());
1150 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001151 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001152 const auto display = getDisplayDevice(displayToken);
1153 if (!display) {
1154 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1155 decodeColorMode(mode).c_str(), mode, displayToken.get());
1156 } else if (display->isVirtual()) {
1157 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1158 decodeColorMode(mode).c_str(), mode);
1159 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001160 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1161 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001162 }
1163 }));
1164
Michael Wright28f24d02016-07-12 13:30:53 -07001165 return NO_ERROR;
1166}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001167
Svetoslavd85084b2014-03-20 10:28:31 -07001168status_t SurfaceFlinger::clearAnimationFrameStats() {
1169 Mutex::Autolock _l(mStateLock);
1170 mAnimFrameTracker.clearStats();
1171 return NO_ERROR;
1172}
1173
1174status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1175 Mutex::Autolock _l(mStateLock);
1176 mAnimFrameTracker.getStats(outStats);
1177 return NO_ERROR;
1178}
1179
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001180status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1181 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001182 Mutex::Autolock _l(mStateLock);
1183
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001184 const auto display = getDisplayDeviceLocked(displayToken);
1185 if (!display) {
1186 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001187 return BAD_VALUE;
1188 }
1189
Peiyong Linfb069302018-04-25 14:34:31 -07001190 // At this point the DisplayDeivce should already be set up,
1191 // meaning the luminance information is already queried from
1192 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001193 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001194 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1195 capabilities.getDesiredMaxLuminance(),
1196 capabilities.getDesiredMaxAverageLuminance(),
1197 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001198
1199 return NO_ERROR;
1200}
1201
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001202status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1203 ui::PixelFormat* outFormat,
1204 ui::Dataspace* outDataspace,
1205 uint8_t* outComponentMask) const {
1206 if (!outFormat || !outDataspace || !outComponentMask) {
1207 return BAD_VALUE;
1208 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001209 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001210 if (!display || !display->getId()) {
1211 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1212 return BAD_VALUE;
1213 }
1214 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1215 outDataspace, outComponentMask);
1216}
1217
Kevin DuBois74e53772018-11-19 10:52:38 -08001218status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1219 bool enable, uint8_t componentMask,
1220 uint64_t maxFrames) const {
1221 const auto display = getDisplayDevice(displayToken);
1222 if (!display || !display->getId()) {
1223 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1224 return BAD_VALUE;
1225 }
1226
1227 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1228 componentMask, maxFrames);
1229}
1230
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001231status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1232 uint64_t maxFrames, uint64_t timestamp,
1233 DisplayedFrameStats* outStats) const {
1234 const auto display = getDisplayDevice(displayToken);
1235 if (!display || !display->getId()) {
1236 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1237 return BAD_VALUE;
1238 }
1239
1240 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1241 outStats);
1242}
1243
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001244status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1245 if (!outSupported) {
1246 return BAD_VALUE;
1247 }
1248 *outSupported = getRenderEngine().supportsProtectedContent();
1249 return NO_ERROR;
1250}
1251
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001252status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1253 bool* outIsWideColorDisplay) const {
1254 if (!displayToken || !outIsWideColorDisplay) {
1255 return BAD_VALUE;
1256 }
1257 Mutex::Autolock _l(mStateLock);
1258 const auto display = getDisplayDeviceLocked(displayToken);
1259 if (!display) {
1260 return BAD_VALUE;
1261 }
Peiyong Linff84a152019-05-17 18:36:19 -07001262
1263 // Use hasWideColorDisplay to override built-in display.
1264 const auto displayId = display->getId();
1265 if (displayId && displayId == getInternalDisplayIdLocked()) {
1266 *outIsWideColorDisplay = hasWideColorDisplay;
1267 return NO_ERROR;
1268 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001269 *outIsWideColorDisplay = display->hasWideColorGamut();
1270 return NO_ERROR;
1271}
1272
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001273status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001274 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001276
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277 if (mInjectVSyncs == enable) {
1278 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001279 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001280
Ana Krulecc2870422019-01-29 19:00:58 -08001281 auto resyncCallback =
1282 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001283
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001284 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001285 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001286 if (enable) {
1287 ALOGV("VSync Injections enabled");
1288 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001289 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001290 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001291 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001292 impl::EventThread::InterceptVSyncsCallback(),
1293 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001294 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001295 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001296 } else {
1297 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001298 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1299 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001300 }
1301
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001302 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001303 }));
1304
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001305 return NO_ERROR;
1306}
1307
1308status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001309 Mutex::Autolock _l(mStateLock);
1310
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001311 if (!mInjectVSyncs) {
1312 ALOGE("VSync Injections not enabled");
1313 return BAD_VALUE;
1314 }
1315 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1316 ALOGV("Injecting VSync inside SurfaceFlinger");
1317 mVSyncInjector->onInjectSyncEvent(when);
1318 }
1319 return NO_ERROR;
1320}
1321
Lloyd Pique755e3192018-01-31 16:46:15 -08001322status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1323 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001324 // Try to acquire a lock for 1s, fail gracefully
1325 const status_t err = mStateLock.timedLock(s2ns(1));
1326 const bool locked = (err == NO_ERROR);
1327 if (!locked) {
1328 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1329 return TIMED_OUT;
1330 }
1331
1332 outLayers->clear();
1333 mCurrentState.traverseInZOrder([&](Layer* layer) {
1334 outLayers->push_back(layer->getLayerDebugInfo());
1335 });
1336
1337 mStateLock.unlock();
1338 return NO_ERROR;
1339}
1340
Peiyong Linc6780972018-10-28 15:24:08 -07001341status_t SurfaceFlinger::getCompositionPreference(
1342 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1343 Dataspace* outWideColorGamutDataspace,
1344 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001345 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001346 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001347 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001348 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001349 return NO_ERROR;
1350}
1351
Dan Stozaec460082018-12-17 15:35:09 -08001352status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1353 const sp<IBinder>& stopLayerHandle,
1354 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001355 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001356 return BAD_VALUE;
1357 }
1358 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001359 return NO_ERROR;
1360}
1361
Dan Stozaec460082018-12-17 15:35:09 -08001362status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001363 if (!listener) {
1364 return BAD_VALUE;
1365 }
Dan Stozaec460082018-12-17 15:35:09 -08001366 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001367 return NO_ERROR;
1368}
Dan Gittik57e63c52019-01-18 16:37:54 +00001369
1370status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1371 bool* outSupport) const {
1372 if (!displayToken || !outSupport) {
1373 return BAD_VALUE;
1374 }
1375 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1376 if (!displayId) {
1377 return NAME_NOT_FOUND;
1378 }
1379 *outSupport =
1380 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1381 return NO_ERROR;
1382}
1383
1384status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1385 float brightness) const {
1386 if (!displayToken) {
1387 return BAD_VALUE;
1388 }
1389 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1390 if (!displayId) {
1391 return NAME_NOT_FOUND;
1392 }
1393 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1394}
1395
Ady Abraham8532d012019-05-08 14:50:56 -07001396status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1397 PowerHint powerHint = static_cast<PowerHint>(hintId);
1398
1399 if (powerHint == PowerHint::INTERACTION) {
1400 mScheduler->notifyTouchEvent();
1401 }
1402
1403 return NO_ERROR;
1404}
1405
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001406// ----------------------------------------------------------------------------
1407
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001408sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001409 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001410 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001411 Mutex::Autolock lock(mStateLock);
1412 return getVsyncPeriod();
1413 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001414
Ana Krulecc2870422019-01-29 19:00:58 -08001415 const auto& handle =
1416 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001417
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001418 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1419 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001420}
1421
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001422// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423
1424void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001425 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426}
1427
1428void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001429 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001430 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431}
1432
1433void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001434 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001435 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001436}
1437
1438void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001439 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001440 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001441}
1442
1443status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001444 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001445 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001446}
1447
1448status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001449 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001450 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001451 if (res == NO_ERROR) {
1452 msg->wait();
1453 }
1454 return res;
1455}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001456
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001457void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001458 do {
1459 waitForEvent();
1460 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461}
1462
Dominik Laskowski83b88212018-12-11 13:34:06 -08001463nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001464 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001465 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1466 return 0;
1467 }
1468
1469 const auto config = getHwComposer().getActiveConfig(*displayId);
1470 return config ? config->getVsyncPeriod() : 0;
1471}
1472
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001473void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1474 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001475 ATRACE_NAME("SF onVsync");
1476
Steven Thomas3cfac282017-02-06 12:29:30 -08001477 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001479 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 return;
1481 }
1482
Dominik Laskowski075d3172018-05-24 15:50:06 -07001483 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 return;
1485 }
1486
Dominik Laskowski075d3172018-05-24 15:50:06 -07001487 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001488 // For now, we don't do anything with external display vsyncs.
1489 return;
1490 }
1491
Alec Mourif8e689c2019-05-20 18:32:22 -07001492 bool periodFlushed = false;
1493 mScheduler->addResyncSample(timestamp, &periodFlushed);
1494 if (periodFlushed) {
1495 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001496 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001497}
1498
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001500 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1501 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001502}
1503
Ady Abraham261614e2019-07-10 17:53:12 -07001504bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001505 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001506}
1507
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001508void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001509 const auto display = getDefaultDisplayDeviceLocked();
1510 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001511 return;
1512 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001513 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001514
Ana Krulec7d1d6832018-12-27 11:10:09 -08001515 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001516 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001517 if (!refreshRateConfig) {
1518 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001519 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001520 }
Ady Abraham1902d072019-03-01 17:18:59 -08001521
Alec Mouri0a1cc962019-03-14 12:33:02 -07001522 const int desiredConfigId = refreshRateConfig->configId;
1523
Dominik Laskowski22488f62019-03-28 09:53:04 -07001524 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001525 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1526 return;
1527 }
1528
Dominik Laskowski22488f62019-03-28 09:53:04 -07001529 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001530}
1531
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001532void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001533 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001534 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001535 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536
Lloyd Piqueba04e622017-12-14 17:11:26 -08001537 // Ignore events that do not have the right sequenceId.
1538 if (sequenceId != getBE().mComposerSequenceId) {
1539 return;
1540 }
1541
Steven Thomasb02664d2017-07-26 18:48:28 -07001542 // Only lock if we're not on the main thread. This function is normally
1543 // called on a hwbinder thread, but for the primary display it's called on
1544 // the main thread with the state lock already held, so don't attempt to
1545 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001546 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001547
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001548 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001549
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001550 if (std::this_thread::get_id() == mMainThreadId) {
1551 // Process all pending hot plug events immediately if we are on the main thread.
1552 processDisplayHotplugEventsLocked();
1553 }
1554
Lloyd Piqueba04e622017-12-14 17:11:26 -08001555 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001556}
1557
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001558void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001559 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001560 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001561 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001562 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001563 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001564}
1565
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001566void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001567 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001568
1569 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1570 // display power state.
1571 postMessageAsync(new LambdaMessage(
1572 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1573}
1574
1575void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1576 ATRACE_CALL();
1577
Ady Abraham27c70212019-06-11 10:52:26 -07001578 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1579
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001580 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001581 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1582 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001583 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001584 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001585 }
Mathias Agopian86303202012-07-24 22:46:10 -07001586}
1587
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001588// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001589void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001590 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001591 // Clear the drawing state so that the logic inside of
1592 // handleTransactionLocked will fire. It will determine the delta between
1593 // mCurrentState and mDrawingState and re-apply all changes when we make the
1594 // transition.
1595 mDrawingState.displays.clear();
1596 mDisplays.clear();
1597}
1598
Steven Thomas050b2c82017-03-06 11:45:16 -08001599void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001600 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001601 if (!mVrFlinger)
1602 return;
1603 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001604 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001605 return;
1606 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001607
Lloyd Pique441d5042018-10-18 16:49:51 -07001608 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001609 ALOGE("Vr flinger is only supported for remote hardware composer"
1610 " service connections. Ignoring request to transition to vr"
1611 " flinger.");
1612 mVrFlingerRequestsDisplay = false;
1613 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001614 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001615
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001616 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001617
Steven Thomas0123ac62018-07-12 11:32:34 -07001618 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001619 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001620
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001621 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001622
1623 // Clear out all the output layers from the composition engine for all
1624 // displays before destroying the hardware composer interface. This ensures
1625 // any HWC layers are destroyed through that interface before it becomes
1626 // invalid.
1627 for (const auto& [token, displayDevice] : mDisplays) {
1628 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1629 compositionengine::Output::OutputLayers());
1630 }
1631
Steven Thomas0123ac62018-07-12 11:32:34 -07001632 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1633 // called below. Clear the reference now so we don't accidentally use it
1634 // later.
1635 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001636
Steven Thomasb02664d2017-07-26 18:48:28 -07001637 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001638 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001639 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001640
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001642 // Delete the current instance before creating the new one
1643 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1644 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1645 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1646 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001647
Lloyd Pique441d5042018-10-18 16:49:51 -07001648 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001649 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001650
1651 if (vrFlingerRequestsDisplay) {
1652 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001653 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001654
1655 mVisibleRegionsDirty = true;
1656 invalidateHwcGeometry();
1657
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001658 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001659 display = getDefaultDisplayDeviceLocked();
1660 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001661 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001662
Steven Thomasb02664d2017-07-26 18:48:28 -07001663 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001664 const nsecs_t vsyncPeriod = getVsyncPeriod();
1665 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001666
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001667 // The present fences returned from vr_hwc are not an accurate
1668 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001669 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001670
Steven Thomasb02664d2017-07-26 18:48:28 -07001671 // Use phase of 0 since phase is not known.
1672 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001673 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001674 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001675
Ana Krulecc2870422019-01-29 19:00:58 -08001676 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001677
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001678 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001679 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001680}
1681
Ady Abrahambe0f9482019-04-24 15:41:53 -07001682bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1683 // We are storing the last 2 present fences. If sf's phase offset is to be
1684 // woken up before the actual vsync but targeting the next vsync, we need to check
1685 // fence N-2
1686 const sp<Fence>& fence =
1687 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1688 ? mPreviousPresentFences[0]
1689 : mPreviousPresentFences[1];
1690
1691 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1692}
1693
Ady Abraham7c03ce62019-07-19 10:59:45 -07001694void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
Alec Mouriaa614192019-06-06 13:28:34 -07001695 DisplayStatInfo stats;
1696 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001697 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001698 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham7c03ce62019-07-19 10:59:45 -07001699 mExpectedPresentTime =
Alec Mouriaa614192019-06-06 13:28:34 -07001700 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1701 ? presentTime
1702 : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001703}
1704
Dominik Laskowski22488f62019-03-28 09:53:04 -07001705void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001706 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001707 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001708 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001709 // calculate the expected present time once and use the cached
1710 // value throughout this frame to make sure all layers are
1711 // seeing this same value.
1712 populateExpectedPresentTime();
1713
Ady Abraham50204dd2019-07-19 15:47:11 -07001714 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1715 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1716 mHadDeviceComposition && frameMissed};
1717 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1718 mHadClientComposition && frameMissed};
1719
Alec Mouricc0fc602019-02-26 21:45:19 -08001720 if (frameMissed) {
1721 mFrameMissedCount++;
1722 mTimeStats->incrementMissedFrames();
1723 }
1724
Alec Mouri40189b02019-03-05 15:07:54 -08001725 if (hwcFrameMissed) {
1726 mHwcFrameMissedCount++;
1727 }
1728
1729 if (gpuFrameMissed) {
1730 mGpuFrameMissedCount++;
1731 }
1732
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001733 if (mUseSmart90ForVideo) {
1734 // This call is made each time SF wakes up and creates a new frame. It is part
1735 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001736 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001737 }
1738
Ady Abrahamb838aed2019-02-12 15:30:16 -08001739 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001740 break;
1741 }
1742
Ady Abraham4658e112019-07-22 13:07:26 -07001743 if (frameMissed && mPropagateBackpressure) {
1744 if ((hwcFrameMissed && !gpuFrameMissed) ||
1745 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001746 signalLayerUpdate();
1747 break;
1748 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001749 }
Dan Stoza50182882016-07-08 12:02:20 -07001750
Steven Thomas050b2c82017-03-06 11:45:16 -08001751 // Now that we're going to make it to the handleMessageTransaction()
1752 // call below it's safe to call updateVrFlinger(), which will
1753 // potentially trigger a display handoff.
1754 updateVrFlinger();
1755
Dan Stoza6b9454d2014-11-07 16:00:59 -08001756 bool refreshNeeded = handleMessageTransaction();
1757 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001758
1759 updateCursorAsync();
1760 updateInputFlinger();
1761
Dan Stoza58784442014-12-02 16:58:17 -08001762 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001763 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001764 // Signal a refresh if a transaction modified the window state,
1765 // a new buffer was latched, or if HWC has requested a full
1766 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001767 signalRefresh();
1768 }
1769 break;
1770 }
1771 case MessageQueue::REFRESH: {
1772 handleMessageRefresh();
1773 break;
1774 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001775 }
1776}
1777
Dan Stoza6b9454d2014-11-07 16:00:59 -08001778bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001779 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001780 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001781
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001782 bool flushedATransaction = flushTransactionQueues();
1783
1784 bool runHandleTransaction = transactionFlags &&
1785 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1786
1787 if (runHandleTransaction) {
1788 handleTransaction(eTransactionMask);
1789 } else {
1790 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001791 }
1792
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001793 if (transactionFlushNeeded()) {
1794 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001795 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001796
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001797 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001798}
1799
Mathias Agopian4fec8732012-06-29 14:12:52 -07001800void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001801 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001802
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001803 mRefreshPending = false;
1804
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001805 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001806 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001807 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001808 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001809 for (const auto& [token, display] : mDisplays) {
1810 beginFrame(display);
1811 prepareFrame(display);
1812 doDebugFlashRegions(display, repaintEverything);
1813 doComposition(display, repaintEverything);
1814 }
1815
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001816 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001817
1818 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001819 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001820
Dan Stozabfbffeb2016-07-21 14:49:33 -07001821 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001822 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001823 for (const auto& [token, displayDevice] : mDisplays) {
1824 auto display = displayDevice->getCompositionDisplay();
1825 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001826 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001827 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001828 mHadDeviceComposition =
1829 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001830 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001831
Jorim Jaggi90535212018-05-23 23:44:06 +02001832 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001833
David Sodman7e4ae112018-02-09 15:02:28 -08001834 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001835 if (mVisibleRegionsDirty) {
1836 mVisibleRegionsDirty = false;
1837 if (mTracingEnabled) {
1838 mTracing.notify("visibleRegionsDirty");
1839 }
1840 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001841}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001842
David Sodmanfa9b2af2017-12-24 13:28:59 -08001843
1844bool SurfaceFlinger::handleMessageInvalidate() {
1845 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001846 bool refreshNeeded = handlePageFlip();
1847
Vishnu Nair4351ad52019-02-11 14:13:02 -08001848 if (mVisibleRegionsDirty) {
1849 computeLayerBounds();
1850 }
1851
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001852 for (auto& layer : mLayersPendingRefresh) {
1853 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001854 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001855 invalidateLayerStack(layer, visibleReg);
1856 }
1857 mLayersPendingRefresh.clear();
1858 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001859}
1860
David Sodman79bba0e2018-08-05 18:07:49 -07001861void SurfaceFlinger::calculateWorkingSet() {
1862 ATRACE_CALL();
1863 ALOGV(__FUNCTION__);
1864
David Sodman79bba0e2018-08-05 18:07:49 -07001865 // build the h/w work list
1866 if (CC_UNLIKELY(mGeometryInvalid)) {
1867 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001868 for (const auto& [token, displayDevice] : mDisplays) {
1869 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001870
Lloyd Piquea83776c2019-01-29 18:42:32 -08001871 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001872
Lloyd Piquea83776c2019-01-29 18:42:32 -08001873 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1874 auto& compositionState = layer->editState();
1875 compositionState.forceClientComposition = false;
1876 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1877 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001878 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001879
Lloyd Piquea83776c2019-01-29 18:42:32 -08001880 // The output Z order is set here based on a simple counter.
1881 compositionState.z = zOrder++;
1882
1883 // Update the display independent composition state. This goes
1884 // to the general composition layer state structure.
1885 // TODO: Do this once per compositionengine::CompositionLayer.
1886 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1887 true);
1888
1889 // Recalculate the geometry state of the output layer.
1890 layer->updateCompositionState(true);
1891
1892 // Write the updated geometry state to the HWC
1893 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001894 }
1895 }
1896 }
1897
1898 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001899 for (const auto& [token, displayDevice] : mDisplays) {
1900 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001901 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001902 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001903 continue;
1904 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001905 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001906
1907 if (mDrawingState.colorMatrixChanged) {
1908 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001909 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001910 Dataspace targetDataspace = Dataspace::UNKNOWN;
1911 if (useColorManagement) {
1912 ColorMode colorMode;
1913 RenderIntent renderIntent;
1914 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1915 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001916
1917 if (isHdrColorMode(colorMode)) {
1918 targetDataspace = Dataspace::UNKNOWN;
1919 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1920 targetDataspace = mColorSpaceAgnosticDataspace;
1921 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001922 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001923
Lloyd Pique32cbe282018-10-19 13:09:22 -07001924 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001925 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001926 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001927 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1928 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001929 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001930 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001931 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1932 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001933 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001934 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001935 }
1936
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001937 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001938 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001939 }
1940
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001941 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001942 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001943 layer->setCompositionType(displayDevice,
1944 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001945 continue;
1946 }
1947
Lloyd Pique32cbe282018-10-19 13:09:22 -07001948 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001949 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001950 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001951 }
1952 }
1953
1954 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001955
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001956 for (const auto& [token, displayDevice] : mDisplays) {
1957 auto display = displayDevice->getCompositionDisplay();
1958 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001959 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1960 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1961 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001962 }
1963 }
David Sodman79bba0e2018-08-05 18:07:49 -07001964}
1965
Lloyd Pique32cbe282018-10-19 13:09:22 -07001966void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1967 bool repaintEverything) {
1968 auto display = displayDevice->getCompositionDisplay();
1969 const auto& displayState = display->getState();
1970
Mathias Agopiancd60f992012-08-16 16:28:27 -07001971 // is debugging enabled
1972 if (CC_LIKELY(!mDebugRegion))
1973 return;
1974
Lloyd Pique32cbe282018-10-19 13:09:22 -07001975 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001976 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001977 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001978 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001979 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001980 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001981 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001983 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001984 }
1985 }
1986
Lloyd Pique32cbe282018-10-19 13:09:22 -07001987 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988
1989 if (mDebugRegion > 1) {
1990 usleep(mDebugRegion * 1000);
1991 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001992
Lloyd Pique32cbe282018-10-19 13:09:22 -07001993 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994}
1995
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001996void SurfaceFlinger::logLayerStats() {
1997 ATRACE_CALL();
1998 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001999 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002000 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002001 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002002 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002003 }
2004 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002005
2006 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002007 }
2008}
2009
David Sodman2b406362017-12-15 13:33:47 -08002010void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002012 ATRACE_CALL();
2013 ALOGV("preComposition");
2014
David Sodman2b406362017-12-15 13:33:47 -08002015 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2016
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002018 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002019 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002020 needExtraInvalidate = true;
2021 }
Robert Carr2047fae2016-11-28 14:09:09 -08002022 });
2023
Mathias Agopiancd60f992012-08-16 16:28:27 -07002024 if (needExtraInvalidate) {
2025 signalLayerUpdate();
2026 }
2027}
2028
Ana Krulece588e312018-09-18 12:32:24 -07002029void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2030 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031 // Update queue of past composite+present times and determine the
2032 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002033 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002034 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002035 while (!getBE().mCompositePresentTimes.empty()) {
2036 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002037 // Cached values should have been updated before calling this method,
2038 // which helps avoid duplicate syscalls.
2039 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2040 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2041 break;
2042 }
2043 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002044 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002045 }
2046
2047 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002048 while (getBE().mCompositePresentTimes.size() > 16) {
2049 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002050 }
2051
Ana Krulece588e312018-09-18 12:32:24 -07002052 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002053}
2054
Ana Krulece588e312018-09-18 12:32:24 -07002055void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2056 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002057 // Integer division and modulo round toward 0 not -inf, so we need to
2058 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002059 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2060 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2061 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062
Ana Krulec757f63a2019-01-25 10:46:18 -08002063 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002064 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002065 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002066 }
2067
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002068 // Snap the latency to a value that removes scheduling jitter from the
2069 // composition and present times, which often have >1ms of jitter.
2070 // Reducing jitter is important if an app attempts to extrapolate
2071 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002072 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002074 nsecs_t bias = stats.vsyncPeriod / 2;
2075 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2076 nsecs_t snappedCompositeToPresentLatency =
2077 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002078
David Sodman99974d22017-11-28 12:04:33 -08002079 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002080 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2081 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002082 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002083}
2084
David Sodman2b406362017-12-15 13:33:47 -08002085void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002086{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 ATRACE_CALL();
2088 ALOGV("postComposition");
2089
Brian Anderson3546a3f2016-07-14 11:51:14 -07002090 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002091 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002092 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002093 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002094 }
2095
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002096 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002097 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002098
David Sodman73beded2017-11-15 11:56:06 -08002099 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002100 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002102 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002103 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2104 ->getRenderSurface()
2105 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002106 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002107 } else {
2108 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2109 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002110
David Sodman73beded2017-11-15 11:56:06 -08002111 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002112 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2113 mPreviousPresentFences[0] = displayDevice
2114 ? getHwComposer().getPresentFence(*displayDevice->getId())
2115 : Fence::NO_FENCE;
2116 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002117 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118
Ana Krulece588e312018-09-18 12:32:24 -07002119 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002120 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002121
David Sodman2b406362017-12-15 13:33:47 -08002122 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002123 // when we started doing work for this frame, but that should be okay
2124 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002125 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002126 CompositorTiming compositorTiming;
2127 {
David Sodman99974d22017-11-28 12:04:33 -08002128 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2129 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002130 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002131
Robert Carr2047fae2016-11-28 14:09:09 -08002132 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002133 bool frameLatched =
2134 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2135 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002136 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002137 recordBufferingStats(layer->getName().string(),
2138 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002139 }
Robert Carr2047fae2016-11-28 14:09:09 -08002140 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002141
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002142 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002143 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002144 }
2145
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002146 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002147 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2148 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002149 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002150 }
2151 }
2152
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002153 if (mAnimCompositionPending) {
2154 mAnimCompositionPending = false;
2155
Brian Anderson4e606e32017-03-16 15:34:57 -07002156 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002157 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002158 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002159 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002160 // The HWC doesn't support present fences, so use the refresh
2161 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002162 const nsecs_t presentTime =
2163 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002164 mAnimFrameTracker.setActualPresentTime(presentTime);
2165 }
2166 mAnimFrameTracker.advanceFrame();
2167 }
Dan Stozab90cf072015-03-05 11:05:59 -08002168
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002169 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002170 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002171 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002172 }
2173
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002174 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002175
Lloyd Pique32cbe282018-10-19 13:09:22 -07002176 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2177 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002178 return;
2179 }
2180
2181 nsecs_t currentTime = systemTime();
2182 if (mHasPoweredOff) {
2183 mHasPoweredOff = false;
2184 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002185 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002186 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002187 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2188 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002189 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002190 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002191 }
David Sodman4a36e932017-11-07 14:29:47 -08002192 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002193 }
David Sodman4a36e932017-11-07 14:29:47 -08002194 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002195
2196 {
2197 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002198 if (mTexturePool.size() < mTexturePoolSize) {
2199 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002200 const size_t offset = mTexturePool.size();
2201 mTexturePool.resize(mTexturePoolSize);
2202 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2203 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002204 } else if (mTexturePool.size() > mTexturePoolSize) {
2205 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2206 const size_t offset = mTexturePoolSize;
2207 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2208 mTexturePool.resize(mTexturePoolSize);
2209 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002210 }
2211 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002212
Ady Abrahambe0f9482019-04-24 15:41:53 -07002213 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002214 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002215
Kevin DuBois413287f2019-02-25 08:46:47 -08002216 if (mLumaSampling && mRegionSamplingThread) {
2217 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002218 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002219
2220 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2221 // side-effect of getTotalSize(), so we check that again here
2222 if (ATRACE_ENABLED()) {
2223 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2224 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002225}
2226
Vishnu Nair4351ad52019-02-11 14:13:02 -08002227void SurfaceFlinger::computeLayerBounds() {
2228 for (const auto& pair : mDisplays) {
2229 const auto& displayDevice = pair.second;
2230 const auto display = displayDevice->getCompositionDisplay();
2231 for (const auto& layer : mDrawingState.layersSortedByZ) {
2232 // only consider the layers on the given layer stack
2233 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002234 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002235 }
2236
2237 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2238 }
2239 }
2240}
2241
Mathias Agopiancd60f992012-08-16 16:28:27 -07002242void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002243 ATRACE_CALL();
2244 ALOGV("rebuildLayerStacks");
2245
Mathias Agopiancd60f992012-08-16 16:28:27 -07002246 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002247 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002248 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002249 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002250
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002251 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002252 const auto& displayDevice = pair.second;
2253 auto display = displayDevice->getCompositionDisplay();
2254 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002255 Region opaqueRegion;
2256 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002257 compositionengine::Output::OutputLayers layersSortedByZ;
2258 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002259 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002260 const ui::Transform& tr = displayState.transform;
2261 const Rect bounds = displayState.bounds;
2262 if (displayState.isEnabled) {
2263 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002264
Jeff Sharkey76488112017-02-27 14:15:18 -07002265 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002266 auto compositionLayer = layer->getCompositionLayer();
2267 if (compositionLayer == nullptr) {
2268 return;
2269 }
2270
Lloyd Pique32cbe282018-10-19 13:09:22 -07002271 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002272 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2273 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2274
Lloyd Pique07e33212018-12-18 16:33:37 -08002275 bool needsOutputLayer = false;
2276
Lloyd Piqueef36b002019-01-23 17:52:04 -08002277 if (display->belongsInOutput(layer->getLayerStack(),
2278 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002279 Region drawRegion(tr.transform(
2280 layer->visibleNonTransparentRegion));
2281 drawRegion.andSelf(bounds);
2282 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002283 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002284 }
Chia-I Wu83806892017-11-16 10:50:20 -08002285 }
2286
Lloyd Pique07e33212018-12-18 16:33:37 -08002287 if (needsOutputLayer) {
2288 layersSortedByZ.emplace_back(
2289 display->getOrCreateOutputLayer(displayId, compositionLayer,
2290 layerFE));
2291 deprecated_layersSortedByZ.add(layer);
2292
2293 auto& outputLayerState = layersSortedByZ.back()->editState();
2294 outputLayerState.visibleRegion =
2295 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2296 } else if (displayId) {
2297 // For layers that are being removed from a HWC display,
2298 // and that have queued frames, add them to a a list of
2299 // released layers so we can properly set a fence.
2300 bool hasExistingOutputLayer =
2301 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2302 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2303 mLayersWithQueuedFrames.cend(),
2304 layer) != mLayersWithQueuedFrames.cend();
2305
2306 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002307 layersNeedingFences.add(layer);
2308 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002309 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002310 });
2311 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002312
2313 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2314
2315 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002316 displayDevice->setLayersNeedingFences(layersNeedingFences);
2317
2318 Region undefinedRegion{bounds};
2319 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2320
2321 display->editState().undefinedRegion = undefinedRegion;
2322 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002323 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002324 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002326
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002329// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002331// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002332// The returned HDR data space is one of
2333// - Dataspace::UNKNOWN
2334// - Dataspace::BT2020_HLG
2335// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002336Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2337 Dataspace* outHdrDataSpace,
2338 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002339 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002340 *outHdrDataSpace = Dataspace::UNKNOWN;
2341
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002343 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002344 case Dataspace::V0_SCRGB:
2345 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002346 case Dataspace::BT2020:
2347 case Dataspace::BT2020_ITU:
2348 case Dataspace::BT2020_LINEAR:
2349 case Dataspace::DISPLAY_BT2020:
2350 bestDataSpace = Dataspace::DISPLAY_BT2020;
2351 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002352 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002353 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355 case Dataspace::BT2020_PQ:
2356 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002357 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002358 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002359 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002360 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002361 case Dataspace::BT2020_HLG:
2362 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002363 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002364 // When there's mixed PQ content and HLG content, we set the HDR
2365 // data space to be BT2020_PQ and convert HLG to PQ.
2366 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2367 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002368 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002369 break;
2370 default:
2371 break;
2372 }
Romain Guy54f154a2017-10-24 21:40:32 +01002373 }
2374
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002375 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002376}
2377
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2380 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002381 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2382 *outMode = ColorMode::NATIVE;
2383 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002385 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002386 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002387
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002388 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002389 bool isHdrClientComposition = false;
2390 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002391
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002392 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2393
Peiyong Lina3ea5592019-02-10 14:45:00 -08002394 switch (mForceColorMode) {
2395 case ColorMode::SRGB:
2396 bestDataSpace = Dataspace::V0_SRGB;
2397 break;
2398 case ColorMode::DISPLAY_P3:
2399 bestDataSpace = Dataspace::DISPLAY_P3;
2400 break;
2401 default:
2402 break;
2403 }
2404
Peiyong Lindfde5112018-06-05 10:58:41 -07002405 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002406 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2407 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002408 if (isHdr) {
2409 bestDataSpace = hdrDataSpace;
2410 }
2411
Chia-I Wu0d711262018-05-21 15:19:35 -07002412 RenderIntent intent;
2413 switch (mDisplayColorSetting) {
2414 case DisplayColorSetting::MANAGED:
2415 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002416 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002417 break;
2418 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002419 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002420 break;
2421 default: // vendor display color setting
2422 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2423 break;
2424 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002425
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002426 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002427}
2428
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2430 auto display = displayDevice->getCompositionDisplay();
2431 const auto& displayState = display->getState();
2432
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002433 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002434 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2435 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002436
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437 // If nothing has changed (!dirty), don't recompose.
2438 // If something changed, but we don't currently have any visible layers,
2439 // and didn't when we last did a composition, then skip it this time.
2440 // The second rule does two things:
2441 // - When all layers are removed from a display, we'll emit one black
2442 // frame, then nothing more until we get new layers.
2443 // - When a display is created with a private layer stack, we won't
2444 // emit any black frames until a layer is added to the layer stack.
2445 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002446
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 const char flagPrefix[] = {'-', '+'};
2448 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2450 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2451 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2452 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002453
Lloyd Pique31cb2942018-10-19 17:23:03 -07002454 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002455
David Sodmanfa9b2af2017-12-24 13:28:59 -08002456 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002458 }
2459}
2460
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2462 auto display = displayDevice->getCompositionDisplay();
2463 const auto& displayState = display->getState();
2464
2465 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002466 return;
David Sodman2b406362017-12-15 13:33:47 -08002467 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002468
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002469 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002470 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002472}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002473
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002475 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 ALOGV("doComposition");
2477
Lloyd Pique32cbe282018-10-19 13:09:22 -07002478 auto display = displayDevice->getCompositionDisplay();
2479 const auto& displayState = display->getState();
2480
2481 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002482 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002483 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002484
David Sodmanfa9b2af2017-12-24 13:28:59 -08002485 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002486 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002487
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002489 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002490 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492}
2493
David Sodmanfa9b2af2017-12-24 13:28:59 -08002494void SurfaceFlinger::postFrame()
2495{
2496 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 const auto display = getDefaultDisplayDeviceLocked();
2498 if (display && getHwComposer().isConnected(*display->getId())) {
2499 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002500 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2501 logFrameStats();
2502 }
2503 }
2504}
2505
Lloyd Pique32cbe282018-10-19 13:09:22 -07002506void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002507 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002508 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002509
Lloyd Pique32cbe282018-10-19 13:09:22 -07002510 auto display = displayDevice->getCompositionDisplay();
2511 const auto& displayState = display->getState();
2512 const auto displayId = display->getId();
2513
Lloyd Pique32cbe282018-10-19 13:09:22 -07002514 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002515 if (displayId) {
2516 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002517 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002518 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002519 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002520 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002521 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002522
Chia-I Wu7b549592017-11-15 09:14:57 -08002523 // The layer buffer from the previous frame (if any) is released
2524 // by HWC only when the release fence from this frame (if any) is
2525 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002526 if (layer->getState().hwc) {
2527 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002528 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002529 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2530 usedClientComposition =
2531 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002532 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002533
2534 // If the layer was client composited in the previous frame, we
2535 // need to merge with the previous client target acquire fence.
2536 // Since we do not track that, always merge with the current
2537 // client target acquire fence when it is available, even though
2538 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002539 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002540 releaseFence =
2541 Fence::merge("LayerRelease", releaseFence,
2542 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002543 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002544
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002545 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002546 }
Chia-I Wu83806892017-11-16 10:50:20 -08002547
2548 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002549 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002550 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002551 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002553 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002554 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002555 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002556 }
2557 }
2558
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 if (displayId) {
2560 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002561 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563}
2564
Mathias Agopian87baae12012-07-31 12:38:26 -07002565void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002566{
Mathias Agopian841cde52012-03-01 15:44:37 -08002567 ATRACE_CALL();
2568
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002569 // here we keep a copy of the drawing state (that is the state that's
2570 // going to be overwritten by handleTransactionLocked()) outside of
2571 // mStateLock so that the side-effects of the State assignment
2572 // don't happen with mStateLock held (which can cause deadlocks).
2573 State drawingState(mDrawingState);
2574
Mathias Agopianca4d3602011-05-19 15:38:14 -07002575 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002576 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577
Mathias Agopianca4d3602011-05-19 15:38:14 -07002578 // Here we're guaranteed that some transaction flags are set
2579 // so we can call handleTransactionLocked() unconditionally.
2580 // We call getTransactionFlags(), which will also clear the flags,
2581 // with mStateLock held to guarantee that mCurrentState won't change
2582 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002583
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002584 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002585 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002586 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002587
Mathias Agopianca4d3602011-05-19 15:38:14 -07002588 mDebugInTransaction = 0;
2589 invalidateHwcGeometry();
2590 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002591}
2592
Lloyd Piqueba04e622017-12-14 17:11:26 -08002593void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2594 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 const std::optional<DisplayIdentificationInfo> info =
2596 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002597
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002599 continue;
2600 }
2601
Lloyd Piqueba04e622017-12-14 17:11:26 -08002602 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002603 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002604 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 mPhysicalDisplayTokens[info->id] = new BBinder();
2606 DisplayDeviceState state;
2607 state.displayId = info->id;
2608 state.isSecure = true; // All physical displays are currently considered secure.
2609 state.displayName = info->name;
2610 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2611 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002612 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002613 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002614 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002615
Dominik Laskowski075d3172018-05-24 15:50:06 -07002616 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2617 if (index >= 0) {
2618 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2619 mInterceptor->saveDisplayDeletion(state.sequenceId);
2620 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002621 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002623 }
2624
2625 processDisplayChangesLocked();
2626 }
2627
2628 mPendingHotplugEvents.clear();
2629}
2630
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002631void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002632 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2633 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002634}
2635
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002637 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002638 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 const sp<IGraphicBufferProducer>& producer) {
2640 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002641 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002643 creationArgs.isSecure = state.isSecure;
2644 creationArgs.displaySurface = dispSurface;
2645 creationArgs.hasWideColorGamut = false;
2646 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002647
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002648 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 creationArgs.isPrimary = isInternalDisplay;
2650
2651 if (useColorManagement && displayId) {
2652 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002653 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002654 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002655 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002657
Dominik Laskowski7e045462018-05-30 13:02:02 -07002658 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002659 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002660 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661 }
tangrobin6753a022018-08-10 10:58:54 +08002662 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 if (displayId) {
2665 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002666 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002667 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002668 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669
Lloyd Pique90c115d2018-09-18 21:39:42 -07002670 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002672 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002673
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674 // Make sure that composition can never be stalled by a virtual display
2675 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002676 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002677 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002678 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2679 }
2680
Dominik Laskowski075d3172018-05-24 15:50:06 -07002681 creationArgs.displayInstallOrientation =
2682 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002683
Lloyd Pique99d3da52018-01-22 17:48:03 -08002684 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002685 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002686
Lloyd Pique90c115d2018-09-18 21:39:42 -07002687 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002688
2689 if (maxFrameBufferAcquiredBuffers >= 3) {
2690 nativeWindowSurface->preallocateBuffers();
2691 }
2692
2693 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002694 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002695 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002696 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002697 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002698 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002699 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2700 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002701 if (!state.isVirtual()) {
2702 LOG_ALWAYS_FATAL_IF(!displayId);
2703 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002704 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002705
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002706 display->setLayerStack(state.layerStack);
2707 display->setProjection(state.orientation, state.viewport, state.frame);
2708 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002709
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002711}
2712
Lloyd Pique347200f2017-12-14 17:00:15 -08002713void SurfaceFlinger::processDisplayChangesLocked() {
2714 // here we take advantage of Vector's copy-on-write semantics to
2715 // improve performance by skipping the transaction entirely when
2716 // know that the lists are identical
2717 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2718 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2719 if (!curr.isIdenticalTo(draw)) {
2720 mVisibleRegionsDirty = true;
2721 const size_t cc = curr.size();
2722 size_t dc = draw.size();
2723
2724 // find the displays that were removed
2725 // (ie: in drawing state but not in current state)
2726 // also handle displays that changed
2727 // (ie: displays that are in both lists)
2728 for (size_t i = 0; i < dc;) {
2729 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2730 if (j < 0) {
2731 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002732 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002733 // Save display ID before disconnecting.
2734 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002735 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002736
2737 if (!display->isVirtual()) {
2738 LOG_ALWAYS_FATAL_IF(!displayId);
2739 dispatchDisplayHotplugEvent(displayId->value, false);
2740 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002741 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002742
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 } else {
2745 // this display is in both lists. see if something changed.
2746 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2749 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2750 if (state_binder != draw_binder) {
2751 // changing the surface is like destroying and
2752 // recreating the DisplayDevice, so we just remove it
2753 // from the drawing state, so that it get re-added
2754 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002755 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002756 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002758 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 mDrawingState.displays.removeItemsAt(i);
2760 dc--;
2761 // at this point we must loop to the next item
2762 continue;
2763 }
2764
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002765 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002766 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 }
2769 if ((state.orientation != draw[i].orientation) ||
2770 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002771 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 }
2773 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 }
2776 }
2777 }
2778 ++i;
2779 }
2780
2781 // find displays that were added
2782 // (ie: in current state but not in drawing state)
2783 for (size_t i = 0; i < cc; i++) {
2784 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2785 const DisplayDeviceState& state(curr[i]);
2786
Lloyd Pique542307f2018-10-19 13:24:08 -07002787 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 sp<IGraphicBufferProducer> producer;
2789 sp<IGraphicBufferProducer> bqProducer;
2790 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002791 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002792
Dominik Laskowski075d3172018-05-24 15:50:06 -07002793 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002794 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002795 // Virtual displays without a surface are dormant:
2796 // they have external state (layer stack, projection,
2797 // etc.) but no internal state (i.e. a DisplayDevice).
2798 if (state.surface != nullptr) {
2799 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002800 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002801 int width = 0;
2802 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2803 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2804 int height = 0;
2805 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2806 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2807 int intFormat = 0;
2808 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2809 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002810 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002811
Dominik Laskowski075d3172018-05-24 15:50:06 -07002812 displayId =
2813 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002814 }
2815
2816 // TODO: Plumb requested format back up to consumer
2817
2818 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002819 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002820 bqProducer, bqConsumer,
2821 state.displayName);
2822
2823 dispSurface = vds;
2824 producer = vds;
2825 }
2826 } else {
2827 ALOGE_IF(state.surface != nullptr,
2828 "adding a supported display, but rendering "
2829 "surface is provided (%p), ignoring it",
2830 state.surface.get());
2831
Dominik Laskowski075d3172018-05-24 15:50:06 -07002832 displayId = state.displayId;
2833 LOG_ALWAYS_FATAL_IF(!displayId);
2834 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002835 producer = bqProducer;
2836 }
2837
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002838 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002839 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002840 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002841 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002842 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002843 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002844 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002845 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002846 }
2847 }
2848 }
2849 }
2850 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002851
2852 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002853}
2854
Mathias Agopian87baae12012-07-31 12:38:26 -07002855void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002856{
Dan Stoza7dde5992015-05-22 09:51:44 -07002857 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002858 mCurrentState.traverseInZOrder([](Layer* layer) {
2859 layer->notifyAvailableFrames();
2860 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002861
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 /*
2863 * Traversal of the children
2864 * (perform the transaction for each of them if needed)
2865 */
2866
Marissa Wall06255332019-03-27 13:48:27 -07002867 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002868 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002869 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002870 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871
2872 const uint32_t flags = layer->doTransaction(0);
2873 if (flags & Layer::eVisibleRegion)
2874 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002875
2876 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002877 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002878 }
Robert Carr2047fae2016-11-28 14:09:09 -08002879 });
Marissa Wall06255332019-03-27 13:48:27 -07002880 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881 }
2882
2883 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002884 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002885 */
2886
Mathias Agopiane57f2922012-08-09 16:29:12 -07002887 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002888 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002889 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002890 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002892 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002893 // The transform hint might have changed for some layers
2894 // (either because a display has changed, or because a layer
2895 // as changed).
2896 //
2897 // Walk through all the layers in currentLayers,
2898 // and update their transform hint.
2899 //
2900 // If a layer is visible only on a single display, then that
2901 // display is used to calculate the hint, otherwise we use the
2902 // default display.
2903 //
2904 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2905 // the hint is set before we acquire a buffer from the surface texture.
2906 //
2907 // NOTE: layer transactions have taken place already, so we use their
2908 // drawing state. However, SurfaceFlinger's own transaction has not
2909 // happened yet, so we must use the current state layer list
2910 // (soon to become the drawing state list).
2911 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002912 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002913 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002914 bool first = true;
2915 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002916 // NOTE: we rely on the fact that layers are sorted by
2917 // layerStack first (so we don't have to traverse the list
2918 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002919 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002920 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002921 currentlayerStack = layerStack;
2922 // figure out if this layerstack is mirrored
2923 // (more than one display) if so, pick the default display,
2924 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002925 hintDisplay = nullptr;
2926 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002927 if (display->getCompositionDisplay()
2928 ->belongsInOutput(layer->getLayerStack(),
2929 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002930 if (hintDisplay) {
2931 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002932 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002933 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002934 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002935 }
2936 }
2937 }
2938 }
Chet Haase91d25932013-04-11 15:24:55 -07002939
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002940 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002941 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2942 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002943
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002944 // could be null when this layer is using a layerStack
2945 // that is not visible on any display. Also can occur at
2946 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002947 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002948 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002949
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002950 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002951 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 if (hintDisplay) {
2953 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002954 }
Robert Carr2047fae2016-11-28 14:09:09 -08002955
2956 first = false;
2957 });
Mathias Agopian84300952012-11-21 16:02:13 -08002958 }
2959
2960
Mathias Agopian3559b072012-08-15 13:46:03 -07002961 /*
2962 * Perform our own transaction if needed
2963 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964
2965 if (mLayersAdded) {
2966 mLayersAdded = false;
2967 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002968 mVisibleRegionsDirty = true;
2969 }
2970
2971 // some layers might have been removed, so
2972 // we need to update the regions they're exposing.
2973 if (mLayersRemoved) {
2974 mLayersRemoved = false;
2975 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002976 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002977 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002978 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002980 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002981 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002982 }
Robert Carr2047fae2016-11-28 14:09:09 -08002983 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984 }
2985
Vishnu Nairec0ab382019-02-13 15:32:56 -08002986 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002988}
2989
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002990void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002991 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002992 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002993 return;
2994 }
2995
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002996 if (mVisibleRegionsDirty || mInputInfoChanged) {
2997 mInputInfoChanged = false;
2998 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002999 } else if (mInputWindowCommands.syncInputWindows) {
3000 // If the caller requested to sync input windows, but there are no
3001 // changes to input windows, notify immediately.
3002 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003003 }
3004
3005 executeInputWindowCommands();
3006}
3007
3008void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003009 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003010
3011 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3012 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003013 // When calculating the screen bounds we ignore the transparent region since it may
3014 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003015 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003016 }
3017 });
chaviw291d88a2019-02-14 10:33:58 -08003018
3019 mInputFlinger->setInputWindows(inputHandles,
3020 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3021 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003022}
3023
Vishnu Nairec0ab382019-02-13 15:32:56 -08003024void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003025 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003026 mPendingInputWindowCommands.clear();
3027}
3028
chaviwfbe5d9c2018-12-26 12:23:37 -08003029void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003030 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3031 if (transferTouchFocusCommand.fromToken != nullptr &&
3032 transferTouchFocusCommand.toToken != nullptr &&
3033 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3034 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3035 transferTouchFocusCommand.toToken);
3036 }
3037 }
3038
3039 mInputWindowCommands.clear();
3040}
3041
Riley Andrews03414a12014-07-01 14:22:59 -07003042void SurfaceFlinger::updateCursorAsync()
3043{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003044 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003045 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003046 continue;
3047 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003049 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3050 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003051 }
3052 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003053}
3054
chaviw61626f22018-11-15 16:26:27 -08003055void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3056 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003057 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003058 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003059 }
3060 layer->releasePendingBuffer(systemTime());
3061}
3062
Mathias Agopian4fec8732012-06-29 14:12:52 -07003063void SurfaceFlinger::commitTransaction()
3064{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003065 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003066 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003067 for (const auto& l : mLayersPendingRemoval) {
3068 recordBufferingStats(l->getName().string(),
3069 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003070
Lloyd Pique07e33212018-12-18 16:33:37 -08003071 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003072 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003073 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003074 }
chaviw74d90ad2019-04-26 14:45:26 -07003075
3076 // If the layer has been removed and has no parent, then it will not be reachable
3077 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3078 // ensure we can copy its current to drawing state.
3079 if (!l->getParent()) {
3080 mOffscreenLayers.emplace(l.get());
3081 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003082 }
3083 mLayersPendingRemoval.clear();
3084 }
3085
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003086 // If this transaction is part of a window animation then the next frame
3087 // we composite should be considered an animation as well.
3088 mAnimCompositionPending = mAnimTransactionPending;
3089
Nataniel Borges2b796da2019-02-15 13:32:18 -08003090 withTracingLock([&]() {
3091 mDrawingState = mCurrentState;
3092 // clear the "changed" flags in current state
3093 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003094
chaviw74d90ad2019-04-26 14:45:26 -07003095 mDrawingState.traverseInZOrder([&](Layer* layer) {
3096 layer->commitChildList();
3097
3098 // If the layer can be reached when traversing mDrawingState, then the layer is no
3099 // longer offscreen. Remove the layer from the offscreenLayer set.
3100 if (mOffscreenLayers.count(layer)) {
3101 mOffscreenLayers.erase(layer);
3102 }
3103 });
3104
3105 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003107
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003108 mTransactionPending = false;
3109 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003110 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003111}
3112
Nataniel Borges2b796da2019-02-15 13:32:18 -08003113void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3114 if (mTracingEnabledChanged) {
3115 mTracingEnabled = mTracing.isEnabled();
3116 mTracingEnabledChanged = false;
3117 }
3118
3119 // Synchronize with Tracing thread
3120 std::unique_lock<std::mutex> lock;
3121 if (mTracingEnabled) {
3122 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3123 }
3124
3125 lockedOperation();
3126
3127 // Synchronize with Tracing thread
3128 if (mTracingEnabled) {
3129 lock.unlock();
3130 }
3131}
3132
chaviw74d90ad2019-04-26 14:45:26 -07003133void SurfaceFlinger::commitOffscreenLayers() {
3134 for (Layer* offscreenLayer : mOffscreenLayers) {
3135 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3136 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3137 if (!trFlags) return;
3138
3139 layer->doTransaction(0);
3140 layer->commitChildList();
3141 });
3142 }
3143}
3144
Lloyd Pique32cbe282018-10-19 13:09:22 -07003145void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003146 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003147 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003149
Lloyd Pique32cbe282018-10-19 13:09:22 -07003150 auto display = displayDevice->getCompositionDisplay();
3151
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003152 Region aboveOpaqueLayers;
3153 Region aboveCoveredLayers;
3154 Region dirty;
3155
Mathias Agopian87baae12012-07-31 12:38:26 -07003156 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157
Robert Carr2047fae2016-11-28 14:09:09 -08003158 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003159 // start with the whole surface at its current location
3160 const Layer::State& s(layer->getDrawingState());
3161
Jesse Hall01e29052013-02-19 16:13:35 -08003162 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003163 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003164 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003165 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003166
Mathias Agopianab028732010-03-16 16:41:46 -07003167 /*
3168 * opaqueRegion: area of a surface that is fully opaque.
3169 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003171
3172 /*
3173 * visibleRegion: area of a surface that is visible on screen
3174 * and not fully transparent. This is essentially the layer's
3175 * footprint minus the opaque regions above it.
3176 * Areas covered by a translucent surface are considered visible.
3177 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003179
3180 /*
3181 * coveredRegion: area of a surface that is covered by all
3182 * visible regions above it (which includes the translucent areas).
3183 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003185
Jesse Halla8026d22012-09-25 13:25:04 -07003186 /*
3187 * transparentRegion: area of a surface that is hinted to be completely
3188 * transparent. This is only used to tell when the layer has no visible
3189 * non-transparent regions and can be removed from the layer list. It
3190 * does not affect the visibleRegion of this layer or any layers
3191 * beneath it. The hint may not be correct if apps don't respect the
3192 * SurfaceView restrictions (which, sadly, some don't).
3193 */
3194 Region transparentRegion;
3195
Mathias Agopianab028732010-03-16 16:41:46 -07003196
3197 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003198 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003199 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003200 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003203 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003204 if (!visibleRegion.isEmpty()) {
3205 // Remove the transparent area from the visible region
3206 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003207 if (tr.preserveRects()) {
3208 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003209 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003210 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003211 // transformation too complex, can't do the
3212 // transparent region optimization.
3213 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003214 }
Mathias Agopianab028732010-03-16 16:41:46 -07003215 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216
Mathias Agopianab028732010-03-16 16:41:46 -07003217 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003219 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003220 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003221 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003222 // the opaque region is the layer's footprint
3223 opaqueRegion = visibleRegion;
3224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 }
3226 }
3227
Robert Carre5f4f692018-01-12 13:12:28 -08003228 if (visibleRegion.isEmpty()) {
3229 layer->clearVisibilityRegions();
3230 return;
3231 }
3232
Mathias Agopianab028732010-03-16 16:41:46 -07003233 // Clip the covered region to the visible region
3234 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3235
3236 // Update aboveCoveredLayers for next (lower) layer
3237 aboveCoveredLayers.orSelf(visibleRegion);
3238
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 // subtract the opaque region covered by the layers above us
3240 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241
3242 // compute this layer's dirty region
3243 if (layer->contentDirty) {
3244 // we need to invalidate the whole region
3245 dirty = visibleRegion;
3246 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003247 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003248 layer->contentDirty = false;
3249 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003250 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003251 * the exposed region consists of two components:
3252 * 1) what's VISIBLE now and was COVERED before
3253 * 2) what's EXPOSED now less what was EXPOSED before
3254 *
3255 * note that (1) is conservative, we start with the whole
3256 * visible region but only keep what used to be covered by
3257 * something -- which mean it may have been exposed.
3258 *
3259 * (2) handles areas that were not covered by anything but got
3260 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003261 */
Mathias Agopianab028732010-03-16 16:41:46 -07003262 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003263 const Region oldVisibleRegion = layer->visibleRegion;
3264 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003265 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3266 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 }
3268 dirty.subtractSelf(aboveOpaqueLayers);
3269
3270 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003271 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003272
Mathias Agopianab028732010-03-16 16:41:46 -07003273 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003275
Jesse Halla8026d22012-09-25 13:25:04 -07003276 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277 layer->setVisibleRegion(visibleRegion);
3278 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003279 layer->setVisibleNonTransparentRegion(
3280 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003281 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003282
Mathias Agopian87baae12012-07-31 12:38:26 -07003283 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284}
3285
Chia-I Wuab0c3192017-08-01 11:29:00 -07003286void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003287 for (const auto& [token, displayDevice] : mDisplays) {
3288 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003289 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003290 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003291 }
3292 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003293}
3294
Dan Stoza6b9454d2014-11-07 16:00:59 -08003295bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296{
Ady Abraham09bd3922019-04-08 10:44:56 -07003297 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003298 ALOGV("handlePageFlip");
3299
Brian Andersond6927fb2016-07-23 23:37:30 -07003300 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301
Mathias Agopian4fec8732012-06-29 14:12:52 -07003302 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003303 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003304 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003305
3306 // Store the set of layers that need updates. This set must not change as
3307 // buffers are being latched, as this could result in a deadlock.
3308 // Example: Two producers share the same command stream and:
3309 // 1.) Layer 0 is latched
3310 // 2.) Layer 0 gets a new frame
3311 // 2.) Layer 1 gets a new frame
3312 // 3.) Layer 1 is latched.
3313 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3314 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003315 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003316 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003318 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003319 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003320 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003321 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003322 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003323 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003324 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003325 } else {
3326 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003327 }
Robert Carr2047fae2016-11-28 14:09:09 -08003328 });
3329
Lloyd Piquef2c79392018-12-20 16:23:33 -08003330 if (!mLayersWithQueuedFrames.empty()) {
3331 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3332 // writes to Layer current state. See also b/119481871
3333 Mutex::Autolock lock(mStateLock);
3334
3335 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003336 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003337 mLayersPendingRefresh.push_back(layer);
3338 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003339 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003340 if (layer->isBufferLatched()) {
3341 newDataLatched = true;
3342 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003343 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003344 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003345
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003346 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003347
3348 // If we will need to wake up at some time in the future to deal with a
3349 // queued frame that shouldn't be displayed during this vsync period, wake
3350 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003351 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003352 signalLayerUpdate();
3353 }
3354
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003355 // enter boot animation on first buffer latch
3356 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3357 ALOGI("Enter boot animation");
3358 mBootStage = BootStage::BOOTANIMATION;
3359 }
3360
Dan Stoza6b9454d2014-11-07 16:00:59 -08003361 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003362 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363}
3364
Mathias Agopianad456f92011-01-13 17:53:01 -08003365void SurfaceFlinger::invalidateHwcGeometry()
3366{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003367 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003368}
3369
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003371 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003373 // We only need to actually compose the display if:
3374 // 1) It is being handled by hardware composer, which may need this to
3375 // keep its virtual display state machine in sync, or
3376 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003377 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003378 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003379 return;
3380 }
3381
Dan Stoza9e56aa02015-11-02 13:00:03 -08003382 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383 base::unique_fd readyFence;
3384 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003385
3386 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003387 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003388}
3389
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003390bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3391 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003392 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003393 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003394
Lloyd Pique32cbe282018-10-19 13:09:22 -07003395 auto display = displayDevice->getCompositionDisplay();
3396 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003397 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003398 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003399 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003400
3401 const Region bounds(displayState.bounds);
3402 const DisplayRenderArea renderArea(displayDevice);
Ady Abraham50204dd2019-07-19 15:47:11 -07003403 const TracedOrdinal<bool> hasClientComposition = {"hasClientComposition",
3404 getHwComposer().hasClientComposition(
3405 displayId)};
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003406
Chia-I Wu8e50e692018-05-04 10:12:37 -07003407 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003408
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003409 renderengine::DisplaySettings clientCompositionDisplay;
3410 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3411 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003412 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003413
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 if (hasClientComposition) {
3415 ALOGV("hasClientComposition");
3416
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003417 if (displayDevice->isPrimary() && supportProtectedContent) {
3418 bool needsProtected = false;
3419 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3420 // If the layer is a protected layer, mark protected context is needed.
3421 if (layer->isProtected()) {
3422 needsProtected = true;
3423 break;
3424 }
3425 }
Peiyong Lin52010312019-05-02 14:22:16 -07003426 if (needsProtected != renderEngine.isProtected()) {
3427 renderEngine.useProtectedContext(needsProtected);
3428 }
3429 if (needsProtected != display->getRenderSurface()->isProtected() &&
3430 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003431 display->getRenderSurface()->setProtected(needsProtected);
3432 }
3433 }
3434
Alec Mouri6338c9d2019-02-07 16:57:51 -08003435 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003436
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003437 if (buf == nullptr) {
3438 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3439 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003440 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003441 return false;
3442 }
3443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003444 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3445 clientCompositionDisplay.clip = displayState.scissor;
3446 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003447 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003448 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003449
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003450 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003451 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003452 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003453 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003454 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003455 clientCompositionDisplay.outputDataspace = outputDataspace;
3456 clientCompositionDisplay.maxLuminance =
3457 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003458
Lloyd Pique441d5042018-10-18 16:49:51 -07003459 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003460 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003461 getHwComposer()
3462 .hasDisplayCapability(displayId,
3463 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003464
Peiyong Lind3788632018-09-18 16:01:31 -07003465 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003466 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3467 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003468 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003469 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003470 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003471
Mathias Agopian85d751c2012-08-29 16:59:24 -07003472 /*
3473 * and then, render the layers targeted at the framebuffer
3474 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003475
Dan Stoza9e56aa02015-11-02 13:00:03 -08003476 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003477 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003478 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003479 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003480 const Region viewportRegion(displayState.viewport);
3481 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003482 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003483 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003484 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003485 switch (layer->getCompositionType(displayDevice)) {
3486 case Hwc2::IComposerClient::Composition::CURSOR:
3487 case Hwc2::IComposerClient::Composition::DEVICE:
3488 case Hwc2::IComposerClient::Composition::SIDEBAND:
3489 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003490 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003491 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003492 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003493 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003494 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003495 // never clear the very first layer since we're
3496 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003497 renderengine::LayerSettings layerSettings;
3498 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003499 bool prepared =
3500 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3501 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003502
3503 if (prepared) {
3504 layerSettings.source.buffer.buffer = nullptr;
3505 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3506 layerSettings.alpha = half(0.0);
3507 layerSettings.disableBlending = true;
3508 clientCompositionLayers.push_back(layerSettings);
3509 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003510 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003511 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003512 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003513 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003514 renderengine::LayerSettings layerSettings;
3515 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003516 layer->prepareClientLayer(renderArea, clip, clearRegion,
3517 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003518 if (prepared) {
3519 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003520 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003521 break;
3522 }
3523 default:
3524 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003525 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003526 } else {
3527 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003528 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003529 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003530 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003531
Alec Mouri820c7402019-01-23 13:02:39 -08003532 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003533 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003534 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003535
3536 // We boost GPU frequency here because there will be color spaces conversion
3537 // and it's expensive. We boost the GPU frequency so that GPU composition can
3538 // finish in time. We must reset GPU frequency afterwards, because high frequency
3539 // consumes extra battery.
3540 const bool expensiveRenderingExpected =
3541 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3542 if (expensiveRenderingExpected && displayId) {
3543 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3544 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003545 if (!debugRegion.isEmpty()) {
3546 Region::const_iterator it = debugRegion.begin();
3547 Region::const_iterator end = debugRegion.end();
3548 while (it != end) {
3549 const Rect& rect = *it++;
3550 renderengine::LayerSettings layerSettings;
3551 layerSettings.source.buffer.buffer = nullptr;
3552 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3553 layerSettings.geometry.boundaries = rect.toFloatRect();
3554 layerSettings.alpha = half(1.0);
3555 clientCompositionLayers.push_back(layerSettings);
3556 }
3557 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003558 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003559 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3560 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003561 } else if (displayId) {
3562 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003563 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003564 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565}
3566
Robert Carrc0df3122019-04-11 13:18:21 -07003567status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3568 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3569 const sp<IBinder>& parentHandle,
3570 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003571 // add this layer to the current state list
3572 {
3573 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003574 sp<Layer> parent;
3575 if (parentHandle != nullptr) {
3576 parent = fromHandle(parentHandle);
3577 if (parent == nullptr) {
3578 return NAME_NOT_FOUND;
3579 }
3580 } else {
3581 parent = parentLayer;
3582 }
3583
Robert Carr1f0a16a2016-10-24 16:27:39 -07003584 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003585 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3586 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003587 return NO_MEMORY;
3588 }
Robert Carrc0df3122019-04-11 13:18:21 -07003589
3590 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3591
Robert Carrb89ea9d2018-12-10 13:01:14 -08003592 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003593 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003594 } else if (parent == nullptr) {
3595 lbc->onRemovedFromCurrentState();
3596 } else if (parent->isRemovedFromCurrentState()) {
3597 parent->addChild(lbc);
3598 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003599 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003600 parent->addChild(lbc);
3601 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003602
Yiwei Zhang243b3782018-05-15 17:40:04 -07003603 if (gbc != nullptr) {
3604 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3605 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3606 mMaxGraphicBufferProducerListSize,
3607 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3608 mGraphicBufferProducerList.size(),
3609 mMaxGraphicBufferProducerListSize, mNumLayers);
3610 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003611 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003612 }
3613
Mathias Agopian96f08192010-06-02 23:28:45 -07003614 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003615 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003616
Dan Stoza7d89d062015-04-30 13:29:25 -07003617 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003618}
3619
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003620uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003621 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003622}
3623
Mathias Agopian3f844832013-08-07 21:24:32 -07003624uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003625 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003626}
3627
Mathias Agopian3f844832013-08-07 21:24:32 -07003628uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003629 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003630}
3631
3632uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003633 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003634 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003635 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003636 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003637 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 }
3639 return old;
3640}
3641
Marissa Wall713b63f2018-10-17 15:42:43 -07003642bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003643 // to prevent onHandleDestroyed from being called while the lock is held,
3644 // we must keep a copy of the transactions (specifically the composer
3645 // states) around outside the scope of the lock
3646 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003647 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003648 {
3649 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003650
Valerie Haufce31b82019-04-30 16:41:14 -07003651 auto it = mTransactionQueues.begin();
3652 while (it != mTransactionQueues.end()) {
3653 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003654
Valerie Haufce31b82019-04-30 16:41:14 -07003655 while (!transactionQueue.empty()) {
3656 const auto& transaction = transactionQueue.front();
3657 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3658 transaction.states)) {
3659 setTransactionFlags(eTransactionFlushNeeded);
3660 break;
3661 }
3662 transactions.push_back(transaction);
3663 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3664 mPendingInputWindowCommands, transaction.desiredPresentTime,
3665 transaction.buffer, transaction.callback,
3666 transaction.postTime, transaction.privileged,
3667 /*isMainThread*/ true);
3668 transactionQueue.pop();
3669 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003670 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003671
Valerie Haufce31b82019-04-30 16:41:14 -07003672 if (transactionQueue.empty()) {
3673 it = mTransactionQueues.erase(it);
3674 mTransactionCV.broadcast();
3675 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003676 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003677 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003678 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003679 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003680 return flushedATransaction;
3681}
3682
3683bool SurfaceFlinger::transactionFlushNeeded() {
3684 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003685}
3686
chaviwca27f252018-02-06 16:46:39 -08003687bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3688 for (const ComposerState& state : states) {
3689 // Here we need to check that the interface we're given is indeed
3690 // one of our own. A malicious client could give us a nullptr
3691 // IInterface, or one of its own or even one of our own but a
3692 // different type. All these situations would cause us to crash.
3693 if (state.client == nullptr) {
3694 return true;
3695 }
3696
3697 sp<IBinder> binder = IInterface::asBinder(state.client);
3698 if (binder == nullptr) {
3699 return true;
3700 }
3701
3702 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3703 return true;
3704 }
3705 }
3706 return false;
3707}
3708
Marissa Wall17b4e452018-12-26 16:32:34 -08003709bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3710 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003711 nsecs_t expectedPresentTime = getExpectedPresentTime();
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 }
3766 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003767 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003768 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003769 uncacheBuffer, listenerCallbacks, postTime,
3770 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003771 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003772 return;
3773 }
3774
Valerie Haubc6ddb12019-03-08 11:10:15 -08003775 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003776 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003777}
3778
3779void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003780 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003781 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003782 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003783 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003784 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003785 const int64_t postTime, bool privileged,
3786 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003787 uint32_t transactionFlags = 0;
3788
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003789 if (flags & eAnimation) {
3790 // For window updates that are part of an animation we must wait for
3791 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003792 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003793 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003794 if (CC_UNLIKELY(err != NO_ERROR)) {
3795 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003796 // caller after a few seconds.
3797 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3798 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003799 mAnimTransactionPending = false;
3800 break;
3801 }
3802 }
3803 }
3804
chaviwca27f252018-02-06 16:46:39 -08003805 for (const DisplayState& display : displays) {
3806 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003807 }
3808
Marissa Walld600d572019-03-26 15:38:50 -07003809 // In case the client has sent a Transaction that should receive callbacks but without any
3810 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3811 // to the callback thread so it can send an empty callback
3812 if (!listenerCallbacks.empty()) {
3813 mTransactionCompletedThread.run();
3814 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003815 for (const auto& listenerCallback : listenerCallbacks) {
3816 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003817 }
3818
Marissa Walle2ffb422018-10-12 11:33:52 -07003819 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003820 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003821 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3822 postTime, privileged);
3823 }
3824
Marissa Wallefb71af2019-06-27 14:45:53 -07003825 for (const auto& listenerCallback : listenerCallbacks) {
3826 mTransactionCompletedThread.endRegistration(listenerCallback);
3827 }
3828
Marissa Walle2ffb422018-10-12 11:33:52 -07003829 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003830 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003831 mTransactionCompletedThread.sendCallbacks();
3832 }
3833 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003834
chaviw273171b2018-12-26 11:46:30 -08003835 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3836
Marissa Wall947d34e2019-03-29 14:03:53 -07003837 if (uncacheBuffer.isValid()) {
3838 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003839 }
3840
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003841 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3842 // anyway. This can be used as a flush mechanism for previous async transactions.
3843 // Empty animation transaction can be used to simulate back-pressure, so also force a
3844 // transaction for empty animation transactions.
3845 if (transactionFlags == 0 &&
3846 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003847 transactionFlags = eTransactionNeeded;
3848 }
3849
Marissa Wall06255332019-03-27 13:48:27 -07003850 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3851 // so we don't have to wake up again next frame to preform an uneeded traversal.
3852 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3853 transactionFlags = transactionFlags & (~eTraversalNeeded);
3854 mTraversalNeededMainThread = true;
3855 }
3856
Mathias Agopian386aa982011-11-07 21:58:03 -08003857 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003858 if (mInterceptor->isEnabled()) {
3859 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003860 }
Irvel468051e2016-06-13 16:44:44 -07003861
Mathias Agopian386aa982011-11-07 21:58:03 -08003862 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003863 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3864 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003865 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003866
3867 // if this is a synchronous transaction, wait for it to take effect
3868 // before returning.
3869 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003870 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003871 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003872 if (flags & eAnimation) {
3873 mAnimTransactionPending = true;
3874 }
chaviw4fe36852019-04-15 16:25:49 -07003875 if (mPendingInputWindowCommands.syncInputWindows) {
3876 mPendingSyncInputWindows = true;
3877 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003878
3879 // applyTransactionState can be called by either the main SF thread or by
3880 // another process through setTransactionState. While a given process may wish
3881 // to wait on synchronous transactions, the main SF thread should never
3882 // be blocked. Therefore, we only wait if isMainThread is false.
3883 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003884 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3885 if (CC_UNLIKELY(err != NO_ERROR)) {
3886 // just in case something goes wrong in SF, return to the
3887 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003888 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3889 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003890 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003891 break;
3892 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 }
3895}
3896
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003897uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3898 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3899 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003900
Mathias Agopiane57f2922012-08-09 16:29:12 -07003901 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003902 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3903
3904 const uint32_t what = s.what;
3905 if (what & DisplayState::eSurfaceChanged) {
3906 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3907 state.surface = s.surface;
3908 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003909 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003910 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003911 if (what & DisplayState::eLayerStackChanged) {
3912 if (state.layerStack != s.layerStack) {
3913 state.layerStack = s.layerStack;
3914 flags |= eDisplayTransactionNeeded;
3915 }
3916 }
3917 if (what & DisplayState::eDisplayProjectionChanged) {
3918 if (state.orientation != s.orientation) {
3919 state.orientation = s.orientation;
3920 flags |= eDisplayTransactionNeeded;
3921 }
3922 if (state.frame != s.frame) {
3923 state.frame = s.frame;
3924 flags |= eDisplayTransactionNeeded;
3925 }
3926 if (state.viewport != s.viewport) {
3927 state.viewport = s.viewport;
3928 flags |= eDisplayTransactionNeeded;
3929 }
3930 }
3931 if (what & DisplayState::eDisplaySizeChanged) {
3932 if (state.width != s.width) {
3933 state.width = s.width;
3934 flags |= eDisplayTransactionNeeded;
3935 }
3936 if (state.height != s.height) {
3937 state.height = s.height;
3938 flags |= eDisplayTransactionNeeded;
3939 }
3940 }
3941
Mathias Agopiane57f2922012-08-09 16:29:12 -07003942 return flags;
3943}
3944
Robert Carr14167e02019-02-13 13:50:55 -08003945bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003946 IPCThreadState* ipc = IPCThreadState::self();
3947 const int pid = ipc->getCallingPid();
3948 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003949 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003950 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003951 return false;
3952 }
3953 return true;
3954}
3955
Marissa Wall3dad52d2019-03-22 14:03:19 -07003956uint32_t SurfaceFlinger::setClientStateLocked(
3957 const ComposerState& composerState, int64_t desiredPresentTime,
3958 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3959 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003960 const layer_state_t& s = composerState.state;
3961 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3962
Mathias Agopian13127d82013-03-05 17:47:11 -08003963 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003964 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003965 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003966 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003967 new CallbackHandle(listenerCallback.transactionCompletedListener,
3968 listenerCallback.callbackIds, s.surface));
3969 }
chaviw8b3871a2017-11-01 17:41:01 -07003970 return 0;
3971 }
3972
chaviw8b3871a2017-11-01 17:41:01 -07003973 uint32_t flags = 0;
3974
Garfield Tan8a3083e2018-12-03 13:21:07 -08003975 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003976 bool geometryAppliesWithResize =
3977 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003978
3979 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3980 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003981 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003982 layer->pushPendingState();
3983 }
3984
chaviw8b3871a2017-11-01 17:41:01 -07003985 if (what & layer_state_t::ePositionChanged) {
3986 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3987 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003988 }
chaviw8b3871a2017-11-01 17:41:01 -07003989 }
3990 if (what & layer_state_t::eLayerChanged) {
3991 // NOTE: index needs to be calculated before we update the state
3992 const auto& p = layer->getParent();
3993 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003994 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003995 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003996 mCurrentState.layersSortedByZ.removeAt(idx);
3997 mCurrentState.layersSortedByZ.add(layer);
3998 // we need traversal (state changed)
3999 // AND transaction (list changed)
4000 flags |= eTransactionNeeded|eTraversalNeeded;
4001 }
chaviw8b3871a2017-11-01 17:41:01 -07004002 } else {
4003 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004004 flags |= eTransactionNeeded|eTraversalNeeded;
4005 }
4006 }
chaviw8b3871a2017-11-01 17:41:01 -07004007 }
4008 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004009 // NOTE: index needs to be calculated before we update the state
4010 const auto& p = layer->getParent();
4011 if (p == nullptr) {
4012 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4013 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4014 mCurrentState.layersSortedByZ.removeAt(idx);
4015 mCurrentState.layersSortedByZ.add(layer);
4016 // we need traversal (state changed)
4017 // AND transaction (list changed)
4018 flags |= eTransactionNeeded|eTraversalNeeded;
4019 }
4020 } else {
4021 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4022 flags |= eTransactionNeeded|eTraversalNeeded;
4023 }
chaviw8b3871a2017-11-01 17:41:01 -07004024 }
4025 }
4026 if (what & layer_state_t::eSizeChanged) {
4027 if (layer->setSize(s.w, s.h)) {
4028 flags |= eTraversalNeeded;
4029 }
4030 }
4031 if (what & layer_state_t::eAlphaChanged) {
4032 if (layer->setAlpha(s.alpha))
4033 flags |= eTraversalNeeded;
4034 }
4035 if (what & layer_state_t::eColorChanged) {
4036 if (layer->setColor(s.color))
4037 flags |= eTraversalNeeded;
4038 }
Peiyong Lind3788632018-09-18 16:01:31 -07004039 if (what & layer_state_t::eColorTransformChanged) {
4040 if (layer->setColorTransform(s.colorTransform)) {
4041 flags |= eTraversalNeeded;
4042 }
4043 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004044 if (what & layer_state_t::eBackgroundColorChanged) {
4045 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4046 flags |= eTraversalNeeded;
4047 }
4048 }
chaviw8b3871a2017-11-01 17:41:01 -07004049 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004050 // TODO: b/109894387
4051 //
4052 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4053 // rotation. To see the problem observe that if we have a square parent, and a child
4054 // of the same size, then we rotate the child 45 degrees around it's center, the child
4055 // must now be cropped to a non rectangular 8 sided region.
4056 //
4057 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4058 // private API, and the WindowManager only uses rotation in one case, which is on a top
4059 // level layer in which cropping is not an issue.
4060 //
4061 // However given that abuse of rotation matrices could lead to surfaces extending outside
4062 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4063 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4064 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004065 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004066 flags |= eTraversalNeeded;
4067 }
4068 if (what & layer_state_t::eTransparentRegionChanged) {
4069 if (layer->setTransparentRegionHint(s.transparentRegion))
4070 flags |= eTraversalNeeded;
4071 }
4072 if (what & layer_state_t::eFlagsChanged) {
4073 if (layer->setFlags(s.flags, s.mask))
4074 flags |= eTraversalNeeded;
4075 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004076 if (what & layer_state_t::eCropChanged_legacy) {
4077 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004078 flags |= eTraversalNeeded;
4079 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004080 if (what & layer_state_t::eCornerRadiusChanged) {
4081 if (layer->setCornerRadius(s.cornerRadius))
4082 flags |= eTraversalNeeded;
4083 }
chaviw8b3871a2017-11-01 17:41:01 -07004084 if (what & layer_state_t::eLayerStackChanged) {
4085 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4086 // We only allow setting layer stacks for top level layers,
4087 // everything else inherits layer stack from its parent.
4088 if (layer->hasParent()) {
4089 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4090 layer->getName().string());
4091 } else if (idx < 0) {
4092 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4093 "that also does not appear in the top level layer list. Something"
4094 " has gone wrong.", layer->getName().string());
4095 } else if (layer->setLayerStack(s.layerStack)) {
4096 mCurrentState.layersSortedByZ.removeAt(idx);
4097 mCurrentState.layersSortedByZ.add(layer);
4098 // we need traversal (state changed)
4099 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004100 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004101 }
4102 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004103 if (what & layer_state_t::eDeferTransaction_legacy) {
4104 if (s.barrierHandle_legacy != nullptr) {
4105 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4106 } else if (s.barrierGbp_legacy != nullptr) {
4107 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004108 if (authenticateSurfaceTextureLocked(gbp)) {
4109 const auto& otherLayer =
4110 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004111 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004112 } else {
4113 ALOGE("Attempt to defer transaction to to an"
4114 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004115 }
4116 }
chaviw8b3871a2017-11-01 17:41:01 -07004117 // We don't trigger a traversal here because if no other state is
4118 // changed, we don't want this to cause any more work
4119 }
4120 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004121 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004122 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004123 if (!hadParent) {
4124 mCurrentState.layersSortedByZ.remove(layer);
4125 }
chaviw8b3871a2017-11-01 17:41:01 -07004126 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004127 }
chaviw8b3871a2017-11-01 17:41:01 -07004128 }
4129 if (what & layer_state_t::eReparentChildren) {
4130 if (layer->reparentChildren(s.reparentHandle)) {
4131 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004132 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004133 }
chaviw8b3871a2017-11-01 17:41:01 -07004134 if (what & layer_state_t::eDetachChildren) {
4135 layer->detachChildren();
4136 }
4137 if (what & layer_state_t::eOverrideScalingModeChanged) {
4138 layer->setOverrideScalingMode(s.overrideScalingMode);
4139 // We don't trigger a traversal here because if no other state is
4140 // changed, we don't want this to cause any more work
4141 }
Marissa Wall61c58622018-07-18 10:12:20 -07004142 if (what & layer_state_t::eTransformChanged) {
4143 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4144 }
4145 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4146 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4147 flags |= eTraversalNeeded;
4148 }
4149 if (what & layer_state_t::eCropChanged) {
4150 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4151 }
Marissa Wall861616d2018-10-22 12:52:23 -07004152 if (what & layer_state_t::eFrameChanged) {
4153 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4154 }
Marissa Wall61c58622018-07-18 10:12:20 -07004155 if (what & layer_state_t::eAcquireFenceChanged) {
4156 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4157 }
4158 if (what & layer_state_t::eDataspaceChanged) {
4159 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4160 }
4161 if (what & layer_state_t::eHdrMetadataChanged) {
4162 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4163 }
4164 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4165 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4166 }
4167 if (what & layer_state_t::eApiChanged) {
4168 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4169 }
4170 if (what & layer_state_t::eSidebandStreamChanged) {
4171 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4172 }
Robert Carr720e5062018-07-30 17:45:14 -07004173 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004174 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004175 layer->setInputInfo(s.inputInfo);
4176 flags |= eTraversalNeeded;
4177 } else {
4178 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4179 }
Robert Carr720e5062018-07-30 17:45:14 -07004180 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004181 if (what & layer_state_t::eMetadataChanged) {
4182 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4183 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004184 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4185 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4186 flags |= eTraversalNeeded;
4187 }
4188 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004189 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004190 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004191 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004192 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4193 }
4194 }
Marissa Wall78b72202019-03-15 14:58:34 -07004195 bool bufferChanged = what & layer_state_t::eBufferChanged;
4196 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4197 sp<GraphicBuffer> buffer;
4198 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004199 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri1c8d7202019-06-01 18:51:35 -07004200 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4201 wp<ClientCache::ErasedRecipient>(layer));
4202 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004203 buffer = s.buffer;
4204 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004205 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004206 } else if (bufferChanged) {
4207 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004208 }
Marissa Wall78b72202019-03-15 14:58:34 -07004209 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004210 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004211 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004212 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004213 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004214 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4215 // Do not put anything that updates layer state or modifies flags after
4216 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004217 return flags;
4218}
4219
chaviw273171b2018-12-26 11:46:30 -08004220uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4221 uint32_t flags = 0;
4222 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4223 flags |= eTraversalNeeded;
4224 }
4225
chaviwa911b102019-02-14 10:18:33 -08004226 if (inputWindowCommands.syncInputWindows) {
4227 flags |= eTraversalNeeded;
4228 }
4229
Vishnu Nairec0ab382019-02-13 15:32:56 -08004230 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004231 return flags;
4232}
4233
Marissa Wall2d814fb2019-04-09 18:52:57 +00004234status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4235 uint32_t h, PixelFormat format, uint32_t flags,
4236 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004237 sp<IGraphicBufferProducer>* gbp,
4238 const sp<IBinder>& parentHandle,
4239 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004240 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004241 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004242 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004243 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004244 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004245
Robert Carrc0df3122019-04-11 13:18:21 -07004246 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4247 "Expected only one of parentLayer or parentHandle to be non-null. "
4248 "Programmer error?");
4249
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004250 status_t result = NO_ERROR;
4251
4252 sp<Layer> layer;
4253
Cody Northropbc755282017-03-31 12:00:08 -06004254 String8 uniqueName = getUniqueLayerName(name);
4255
Evan Roskya1f1e152019-01-24 16:17:46 -08004256 bool primaryDisplayOnly = false;
4257
4258 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4259 // TODO b/64227542
4260 if (metadata.has(METADATA_WINDOW_TYPE)) {
4261 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4262 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004263 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004264 primaryDisplayOnly = true;
4265 }
4266 }
4267
Mathias Agopian3165cc22012-08-08 19:42:09 -07004268 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004269 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004270 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4271 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004272
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004273 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004274 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004275 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4276 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004277 break;
chaviw13fdc492017-06-27 12:40:18 -07004278 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004279 // check if buffer size is set for color layer.
4280 if (w > 0 || h > 0) {
4281 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4282 int(w), int(h));
4283 return BAD_VALUE;
4284 }
4285
Evan Roskya1f1e152019-01-24 16:17:46 -08004286 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4287 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004288 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004289 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004290 // check if buffer size is set for container layer.
4291 if (w > 0 || h > 0) {
4292 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4293 int(w), int(h));
4294 return BAD_VALUE;
4295 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004296 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4297 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004298 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004299 default:
4300 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004301 break;
4302 }
4303
Dan Stoza7d89d062015-04-30 13:29:25 -07004304 if (result != NO_ERROR) {
4305 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004306 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004307
Evan Roskya1f1e152019-01-24 16:17:46 -08004308 if (primaryDisplayOnly) {
4309 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004310 }
4311
Robert Carrb89ea9d2018-12-10 13:01:14 -08004312 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004313 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4314 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004315 if (result != NO_ERROR) {
4316 return result;
4317 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004318 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004319
4320 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004321 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004322}
4323
Cody Northropbc755282017-03-31 12:00:08 -06004324String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4325{
4326 bool matchFound = true;
4327 uint32_t dupeCounter = 0;
4328
4329 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4330 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4331
Dan Stoza436ccf32018-06-21 12:10:12 -07004332 // Grab the state lock since we're accessing mCurrentState
4333 Mutex::Autolock lock(mStateLock);
4334
Cody Northropbc755282017-03-31 12:00:08 -06004335 // Loop over layers until we're sure there is no matching name
4336 while (matchFound) {
4337 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004338 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004339 if (layer->getName() == uniqueName) {
4340 matchFound = true;
4341 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4342 }
4343 });
4344 }
4345
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004346 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4347 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004348
4349 return uniqueName;
4350}
4351
Marissa Wallfd668622018-05-10 10:21:13 -07004352status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4353 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004354 LayerMetadata metadata, PixelFormat& format,
4355 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004356 sp<IGraphicBufferProducer>* gbp,
4357 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004358 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004359 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004360 case PIXEL_FORMAT_TRANSPARENT:
4361 case PIXEL_FORMAT_TRANSLUCENT:
4362 format = PIXEL_FORMAT_RGBA_8888;
4363 break;
4364 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004365 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004366 break;
4367 }
4368
Evan Roskya1f1e152019-01-24 16:17:46 -08004369 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4370 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004371 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004372 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004373 *handle = layer->getHandle();
4374 *gbp = layer->getProducer();
4375 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004376 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004377
Marissa Wallfd668622018-05-10 10:21:13 -07004378 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004379 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004380}
4381
Marissa Wall61c58622018-07-18 10:12:20 -07004382status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4383 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004384 LayerMetadata metadata, sp<IBinder>* handle,
4385 sp<Layer>* outLayer) {
4386 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4387 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004388 *handle = layer->getHandle();
4389 *outLayer = layer;
4390
4391 return NO_ERROR;
4392}
4393
Evan Roskya1f1e152019-01-24 16:17:46 -08004394status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4395 uint32_t h, uint32_t flags, LayerMetadata metadata,
4396 sp<IBinder>* handle, sp<Layer>* outLayer) {
4397 *outLayer = getFactory().createColorLayer(
4398 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004399 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004400 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004401}
4402
Evan Roskya1f1e152019-01-24 16:17:46 -08004403status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4404 uint32_t w, uint32_t h, uint32_t flags,
4405 LayerMetadata metadata, sp<IBinder>* handle,
4406 sp<Layer>* outLayer) {
4407 *outLayer = getFactory().createContainerLayer(
4408 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004409 *handle = (*outLayer)->getHandle();
4410 return NO_ERROR;
4411}
4412
4413
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004414void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004415 mLayersPendingRemoval.add(layer);
4416 mLayersRemoved = true;
4417 setTransactionFlags(eTransactionNeeded);
4418}
4419
Robert Carr695d5282018-12-18 15:27:58 -08004420void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004421{
Robert Carr2e102c92018-10-23 12:11:15 -07004422 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004423 // If a layer has a parent, we allow it to out-live it's handle
4424 // with the idea that the parent holds a reference and will eventually
4425 // be cleaned up. However no one cleans up the top-level so we do so
4426 // here.
4427 if (layer->getParent() == nullptr) {
4428 mCurrentState.layersSortedByZ.remove(layer);
4429 }
4430 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004431
4432 auto it = mLayersByLocalBinderToken.begin();
4433 while (it != mLayersByLocalBinderToken.end()) {
4434 if (it->second == layer) {
4435 it = mLayersByLocalBinderToken.erase(it);
4436 } else {
4437 it++;
4438 }
4439 }
4440
Robert Carr695d5282018-12-18 15:27:58 -08004441 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004442}
4443
Mathias Agopianb60314a2012-04-10 22:09:54 -07004444// ---------------------------------------------------------------------------
4445
Andy McFadden13a082e2012-08-24 10:16:42 -07004446void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004447 const auto display = getDefaultDisplayDeviceLocked();
4448 if (!display) return;
4449
4450 const sp<IBinder> token = display->getDisplayToken().promote();
4451 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004452
Jesse Hall01e29052013-02-19 16:13:35 -08004453 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004454 Vector<ComposerState> state;
4455 Vector<DisplayState> displays;
4456 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004457 d.what = DisplayState::eDisplayProjectionChanged |
4458 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004459 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004460 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004461 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004462 d.frame.makeInvalid();
4463 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004464 d.width = 0;
4465 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004466 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004467 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004468
Dominik Laskowskie9774092018-12-11 10:04:24 -08004469 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004470
Dominik Laskowski83b88212018-12-11 13:34:06 -08004471 const nsecs_t vsyncPeriod = getVsyncPeriod();
4472 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004473
Brian Andersond0010582017-03-07 13:20:31 -08004474 // Use phase of 0 since phase is not known.
4475 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004476 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004477 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004478}
4479
4480void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004481 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004482 postMessageAsync(
4483 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004484}
4485
Ady Abraham27c70212019-06-11 10:52:26 -07004486void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4487 if (mHWCVsyncState != enabled) {
4488 getHwComposer().setVsyncEnabled(displayId, enabled);
4489 mHWCVsyncState = enabled;
4490 }
4491}
4492
Dominik Laskowskie9774092018-12-11 10:04:24 -08004493void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004494 if (display->isVirtual()) {
4495 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004496 return;
4497 }
4498
Dominik Laskowski075d3172018-05-24 15:50:06 -07004499 const auto displayId = display->getId();
4500 LOG_ALWAYS_FATAL_IF(!displayId);
4501
Dominik Laskowski34157762018-10-31 13:07:19 -07004502 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004503
4504 int currentMode = display->getPowerMode();
4505 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004506 return;
4507 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004509 display->setPowerMode(mode);
4510
Lloyd Pique4dccc412018-01-22 17:21:36 -08004511 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004512 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004513 }
4514
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004515 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004516 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004517 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004518 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004519 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004520 mScheduler->onScreenAcquired(mAppConnectionHandle);
4521 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004522 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004524 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004525 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004526 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004527
4528 struct sched_param param = {0};
4529 param.sched_priority = 1;
4530 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4531 ALOGW("Couldn't set SCHED_FIFO on display on");
4532 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004533 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004534 // Turn off the display
4535 struct sched_param param = {0};
4536 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4537 ALOGW("Couldn't set SCHED_OTHER on display off");
4538 }
4539
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004540 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004541 mScheduler->disableHardwareVsync(true);
4542 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004543 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004544
Ady Abraham27c70212019-06-11 10:52:26 -07004545 // Make sure HWVsync is disabled before turning off the display
4546 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4547
Dominik Laskowski075d3172018-05-24 15:50:06 -07004548 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004549 mVisibleRegionsDirty = true;
4550 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004551 } else if (mode == HWC_POWER_MODE_DOZE ||
4552 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004553 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004554 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004555 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004556 mScheduler->onScreenAcquired(mAppConnectionHandle);
4557 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004558 }
4559 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4560 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004561 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004562 mScheduler->disableHardwareVsync(true);
4563 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004564 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004565 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004566 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004567 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004568 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004569 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004570
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004571 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004572 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004573 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004574 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004575 }
4576
Dominik Laskowski34157762018-10-31 13:07:19 -07004577 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004578}
4579
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004580void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004581 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004582 const auto display = getDisplayDevice(displayToken);
4583 if (!display) {
4584 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4585 displayToken.get());
4586 } else if (display->isVirtual()) {
4587 ALOGW("Attempt to set power mode %d for virtual display", mode);
4588 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004589 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004590 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004591 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004592}
4593
4594// ---------------------------------------------------------------------------
4595
Dominik Laskowskic2867142019-01-21 11:33:38 -08004596status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4597 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004598 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004599
Mathias Agopianbd115332013-04-18 16:41:04 -07004600 IPCThreadState* ipc = IPCThreadState::self();
4601 const int pid = ipc->getCallingPid();
4602 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004603
Mathias Agopianbd115332013-04-18 16:41:04 -07004604 if ((uid != AID_SHELL) &&
4605 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004606 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4607 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004608 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004609 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004610 // (this would indicate SF is stuck, but we want to be able to
4611 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004612 status_t err = mStateLock.timedLock(s2ns(1));
4613 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004614 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004615 StringAppendF(&result,
4616 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4617 "(no locks held)\n",
4618 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004619 }
4620
Dominik Laskowskic2867142019-01-21 11:33:38 -08004621 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004622
Dominik Laskowskic2867142019-01-21 11:33:38 -08004623 static const std::unordered_map<std::string, Dumper> dumpers = {
4624 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4625 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4626 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004627 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004628 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004629 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004630 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4631 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004632 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4633 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4634 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4635 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4636 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4637 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004638 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004639 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4640 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004641
Dominik Laskowskic2867142019-01-21 11:33:38 -08004642 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004643
Dominik Laskowskic2867142019-01-21 11:33:38 -08004644 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4645 (it->second)(args, asProto, result);
4646 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004647 if (asProto) {
4648 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4649 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4650 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004651 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004652 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004653 }
4654
Mathias Agopian9795c422009-08-26 16:36:26 -07004655 if (locked) {
4656 mStateLock.unlock();
4657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004660 return NO_ERROR;
4661}
4662
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004663status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4664 if (asProto && mTracing.isEnabled()) {
4665 mTracing.writeToFileAsync();
4666 }
4667
4668 return doDump(fd, DumpArgs(), asProto);
4669}
4670
Dominik Laskowskic2867142019-01-21 11:33:38 -08004671void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004672 mCurrentState.traverseInZOrder(
4673 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004674}
4675
Dominik Laskowskic2867142019-01-21 11:33:38 -08004676void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004677 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004678
Dominik Laskowskic2867142019-01-21 11:33:38 -08004679 if (args.size() > 1) {
4680 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004681 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004682 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004683 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004684 }
Robert Carr2047fae2016-11-28 14:09:09 -08004685 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004686 } else {
4687 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688 }
4689}
4690
Dominik Laskowskic2867142019-01-21 11:33:38 -08004691void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004692 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004693 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004694 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004695 }
Robert Carr2047fae2016-11-28 14:09:09 -08004696 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004697
Svetoslavd85084b2014-03-20 10:28:31 -07004698 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004699}
4700
Dominik Laskowskic2867142019-01-21 11:33:38 -08004701void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4702 mTimeStats->parseArgs(asProto, args, result);
4703}
4704
Jamie Gennis6547ff42013-07-16 20:12:42 -07004705// This should only be called from the main thread. Otherwise it would need
4706// the lock and should use mCurrentState rather than mDrawingState.
4707void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004708 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004709 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004710 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004711
4712 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4713}
4714
Yiwei Zhang5434a782018-12-05 18:06:32 -08004715void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004716 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004717
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004718 if (isLayerTripleBufferingDisabled())
4719 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004720
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4722 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4723 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4724 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4725 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4726 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004727 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004728}
4729
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004730void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004731 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004732 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004733 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004734 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004735
Ady Abraham97d04232019-03-05 19:48:12 -08004736 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004737 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4738 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004739 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham261614e2019-07-10 17:53:12 -07004740 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4741 if (refresh.second && isDisplayConfigAllowed(refresh.second->configId)) {
4742 StringAppendF(&result, "%dHz, ", refresh.second->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004743 }
4744 }
4745 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4746 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004747 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004748}
4749
Yiwei Zhang5434a782018-12-05 18:06:32 -08004750void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4751 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004752 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4753 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004754 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004755 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004756 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004757 }
David Sodman4a36e932017-11-07 14:29:47 -08004758 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004759 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004760 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4762 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004763}
4764
Dan Stozae77c7662016-05-13 11:37:28 -07004765void SurfaceFlinger::recordBufferingStats(const char* layerName,
4766 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004767 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4768 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004769 for (const auto& segment : history) {
4770 if (!segment.usedThirdBuffer) {
4771 stats.twoBufferTime += segment.totalTime;
4772 }
4773 if (segment.occupancyAverage < 1.0f) {
4774 stats.doubleBufferedTime += segment.totalTime;
4775 } else if (segment.occupancyAverage < 2.0f) {
4776 stats.tripleBufferedTime += segment.totalTime;
4777 }
4778 ++stats.numSegments;
4779 stats.totalTime += segment.totalTime;
4780 }
4781}
4782
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4784 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004785
4786 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4787 const size_t count = currentLayers.size();
4788 for (size_t i=0 ; i<count ; i++) {
4789 currentLayers[i]->dumpFrameEvents(result);
4790 }
4791}
4792
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004794 result.append("Buffering stats:\n");
4795 result.append(" [Layer name] <Active time> <Two buffer> "
4796 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004797 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004798 typedef std::tuple<std::string, float, float, float> BufferTuple;
4799 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004800 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004801 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004802 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004803 if (stats.numSegments == 0) {
4804 continue;
4805 }
4806 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4807 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4808 stats.totalTime;
4809 float doubleBufferRatio = static_cast<float>(
4810 stats.doubleBufferedTime) / stats.totalTime;
4811 float tripleBufferRatio = static_cast<float>(
4812 stats.tripleBufferedTime) / stats.totalTime;
4813 sorted.insert({activeTime, {name, twoBufferRatio,
4814 doubleBufferRatio, tripleBufferRatio}});
4815 }
4816 for (const auto& sortedPair : sorted) {
4817 float activeTime = sortedPair.first;
4818 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004819 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4820 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004821 }
4822 result.append("\n");
4823}
4824
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004826 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004827 const auto displayId = display->getId();
4828 if (!displayId) {
4829 continue;
4830 }
4831 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004832 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004833 continue;
4834 }
4835
Yiwei Zhang5434a782018-12-05 18:06:32 -08004836 StringAppendF(&result,
4837 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4838 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004839 uint8_t port;
4840 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004841 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004842 result.append("no identification data\n");
4843 continue;
4844 }
4845
4846 if (!isEdid(data)) {
4847 result.append("unknown identification data: ");
4848 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004850 }
4851 result.append("\n");
4852 continue;
4853 }
4854
4855 const auto edid = parseEdid(data);
4856 if (!edid) {
4857 result.append("invalid EDID: ");
4858 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004859 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004860 }
4861 result.append("\n");
4862 continue;
4863 }
4864
Yiwei Zhang5434a782018-12-05 18:06:32 -08004865 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004866 result.append(edid->displayName.data(), edid->displayName.length());
4867 result.append("\"\n");
4868 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004869}
4870
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004872 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004873 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4874 StringAppendF(&result, "DisplayColorSetting: %s\n",
4875 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004876
4877 // TODO: print out if wide-color mode is active or not
4878
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004879 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004880 const auto displayId = display->getId();
4881 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004882 continue;
4883 }
4884
Yiwei Zhang5434a782018-12-05 18:06:32 -08004885 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004887 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004888 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004889 }
4890
Lloyd Pique32cbe282018-10-19 13:09:22 -07004891 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004892 StringAppendF(&result, " Current color mode: %s (%d)\n",
4893 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004894 }
4895 result.append("\n");
4896}
4897
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004898LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4899 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004900 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004901 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4902 const State& state = useDrawing ? mDrawingState : mCurrentState;
4903 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004904 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004905 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004906 });
4907
4908 return layersProto;
4909}
4910
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004911LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4912 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004913 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004914
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004915 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004916 resolution->set_w(displayDevice->getWidth());
4917 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004918
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004919 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004920 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004921
Lloyd Pique32cbe282018-10-19 13:09:22 -07004922 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4923 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4924 layersProto.set_global_transform(displayState.orientation);
4925
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004926 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004927 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004928 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004929 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004930 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004931 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004932 }
4933 });
4934
4935 return layersProto;
4936}
4937
Dominik Laskowskic2867142019-01-21 11:33:38 -08004938void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4939 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004940 Colorizer colorizer(colorize);
4941
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004942 // figure out if we're stuck somewhere
4943 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004944 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004945 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4946
4947 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004948 * Dump library configuration.
4949 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004950
4951 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004952 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004953 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004954 appendSfConfigString(result);
4955 appendUiConfigString(result);
4956 appendGuiConfigString(result);
4957 result.append("\n");
4958
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004959 result.append("\nDisplay identification data:\n");
4960 dumpDisplayIdentificationData(result);
4961
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004962 result.append("\nWide-Color information:\n");
4963 dumpWideColorInfo(result);
4964
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004965 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004966 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004967 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004968 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004969 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004970
Andy McFadden41d67d72014-04-25 16:58:34 -07004971 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004972 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004973 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004974 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004975 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004976
Dan Stozab90cf072015-03-05 11:05:59 -08004977 dumpStaticScreenStats(result);
4978 result.append("\n");
4979
Alec Mouri40189b02019-03-05 15:07:54 -08004980 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4981 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4982 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004983
Dan Stozae77c7662016-05-13 11:37:28 -07004984 dumpBufferingStats(result);
4985
Andy McFadden4803b742012-09-24 19:07:20 -07004986 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004987 * Dump the visible layer list
4988 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004989 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004990 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4991 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4992 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004993 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004994
Chia-I Wu2f884132018-09-13 15:17:58 -07004995 {
4996 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4997 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004998 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004999 result.append("\n");
5000 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005001
Lloyd Pique207def92019-02-28 16:09:52 -08005002 {
5003 StringAppendF(&result, "Composition layers\n");
5004 mDrawingState.traverseInZOrder([&](Layer* layer) {
5005 auto compositionLayer = layer->getCompositionLayer();
5006 if (compositionLayer) compositionLayer->dump(result);
5007 });
5008 }
5009
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005010 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005011 * Dump Display state
5012 */
5013
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005014 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005015 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005016 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005017 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005018 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005019 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005020 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005021
5022 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005023 * Dump SurfaceFlinger global state
5024 */
5025
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005026 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005027 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005028 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005029
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005030 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005031
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005032 DebugEGLImageTracker::getInstance()->dump(result);
5033
Dominik Laskowski075d3172018-05-24 15:50:06 -07005034 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005035 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5036 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005037 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5038 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005039 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005040 StringAppendF(&result,
5041 " transaction-flags : %08x\n"
5042 " gpu_to_cpu_unsupported : %d\n",
5043 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005044
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005045 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005046 displayId && getHwComposer().isConnected(*displayId)) {
5047 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005048 StringAppendF(&result,
5049 " refresh-rate : %f fps\n"
5050 " x-dpi : %f\n"
5051 " y-dpi : %f\n",
5052 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5053 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005054 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005055
Yiwei Zhang5434a782018-12-05 18:06:32 -08005056 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005057
Dan Stozae22aec72016-08-01 13:20:59 -07005058 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005059 * Tracing state
5060 */
5061 mTracing.dump(result);
5062 result.append("\n");
5063
5064 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005065 * HWC layer minidump
5066 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005067 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005068 const auto displayId = display->getId();
5069 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005070 continue;
5071 }
5072
Yiwei Zhang5434a782018-12-05 18:06:32 -08005073 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005074 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005075 const sp<DisplayDevice> displayDevice = display;
5076 mCurrentState.traverseInZOrder(
5077 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005078 result.append("\n");
5079 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005080
5081 /*
5082 * Dump HWComposer state
5083 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005084 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005085 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005086 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005087 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005088 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005089 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005090
5091 /*
5092 * Dump gralloc state
5093 */
5094 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5095 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005096
5097 /*
5098 * Dump VrFlinger state if in use.
5099 */
5100 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5101 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005102 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005103 result.append("\n");
5104 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005105
5106 /**
5107 * Scheduler dump state.
5108 */
Ana Krulecc2870422019-01-29 19:00:58 -08005109 result.append("\nScheduler state:\n");
5110 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005111 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005112 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005113
5114 result.append(mTimeStats->miniDump());
5115 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005116}
5117
Dominik Laskowski075d3172018-05-24 15:50:06 -07005118const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005119 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005120 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005121 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005122 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005123 }
5124 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005125
Dominik Laskowski34157762018-10-31 13:07:19 -07005126 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005127 static const Vector<sp<Layer>> empty;
5128 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005129}
5130
Chia-I Wu28f320b2018-05-03 11:02:56 -07005131void SurfaceFlinger::updateColorMatrixLocked() {
5132 mat4 colorMatrix;
5133 if (mGlobalSaturationFactor != 1.0f) {
5134 // Rec.709 luma coefficients
5135 float3 luminance{0.213f, 0.715f, 0.072f};
5136 luminance *= 1.0f - mGlobalSaturationFactor;
5137 mat4 saturationMatrix = mat4(
5138 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5139 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5140 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5141 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5142 );
5143 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5144 } else {
5145 colorMatrix = mClientColorMatrix * mDaltonizer();
5146 }
5147
5148 if (mCurrentState.colorMatrix != colorMatrix) {
5149 mCurrentState.colorMatrix = colorMatrix;
5150 mCurrentState.colorMatrixChanged = true;
5151 setTransactionFlags(eTransactionNeeded);
5152 }
5153}
5154
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005155status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005156#pragma clang diagnostic push
5157#pragma clang diagnostic error "-Wswitch-enum"
5158 switch (static_cast<ISurfaceComposerTag>(code)) {
5159 // These methods should at minimum make sure that the client requested
5160 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005161 case BOOT_FINISHED:
5162 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005163 case CREATE_DISPLAY:
5164 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005165 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005166 case GET_ANIMATION_FRAME_STATS:
5167 case GET_HDR_CAPABILITIES:
5168 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005169 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005170 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005171 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005172 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005173 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005174 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005175 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005176 case GET_DISPLAYED_CONTENT_SAMPLE:
5177 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005178 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5179 IPCThreadState* ipc = IPCThreadState::self();
5180 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5181 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005182 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005183 }
Robert Carr1db73f62016-12-21 12:58:51 -08005184 return OK;
5185 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005186 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005187 IPCThreadState* ipc = IPCThreadState::self();
5188 const int pid = ipc->getCallingPid();
5189 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005190 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5191 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005192 return PERMISSION_DENIED;
5193 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005194 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005195 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005196 // Used by apps to hook Choreographer to SurfaceFlinger.
5197 case CREATE_DISPLAY_EVENT_CONNECTION:
5198 // The following calls are currently used by clients that do not
5199 // request necessary permissions. However, they do not expose any secret
5200 // information, so it is OK to pass them.
5201 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005202 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005203 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005204 case GET_PHYSICAL_DISPLAY_IDS:
5205 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005206 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005207 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005208 case GET_DISPLAY_CONFIGS:
5209 case GET_DISPLAY_STATS:
5210 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5211 // Calling setTransactionState is safe, because you need to have been
5212 // granted a reference to Client* and Handle* to do anything with it.
5213 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005214 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005215 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005216 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005217 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005218 case IS_WIDE_COLOR_DISPLAY:
5219 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5220 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005221 return OK;
5222 }
Chong Zhangda6c1592019-07-16 13:45:06 -07005223 case CAPTURE_LAYERS: {
5224 IPCThreadState* ipc = IPCThreadState::self();
5225 const int pid = ipc->getCallingPid();
5226 const int uid = ipc->getCallingUid();
5227 // allow media to capture layer for video thumbnails
5228 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
5229 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5230 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
5231 return PERMISSION_DENIED;
5232 }
5233 return OK;
5234 }
Dan Stoza84ab9372018-12-17 15:27:57 -08005235 case CAPTURE_SCREEN:
5236 case ADD_REGION_SAMPLING_LISTENER:
5237 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005238 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005239 IPCThreadState* ipc = IPCThreadState::self();
5240 const int pid = ipc->getCallingPid();
5241 const int uid = ipc->getCallingUid();
5242 if ((uid != AID_GRAPHICS) &&
5243 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5244 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5245 return PERMISSION_DENIED;
5246 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005247 return OK;
5248 }
5249 // The following codes are deprecated and should never be allowed to access SF.
5250 case CONNECT_DISPLAY_UNUSED:
5251 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5252 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5253 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005254 }
chaviw93df2ea2019-04-30 16:45:12 -07005255 case CAPTURE_SCREEN_BY_ID: {
5256 IPCThreadState* ipc = IPCThreadState::self();
5257 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005258 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005259 return OK;
5260 }
5261 return PERMISSION_DENIED;
5262 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005263 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005264
5265 // These codes are used for the IBinder protocol to either interrogate the recipient
5266 // side of the transaction for its canonical interface descriptor or to dump its state.
5267 // We let them pass by default.
5268 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5269 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5270 code == IBinder::SYSPROPS_TRANSACTION) {
5271 return OK;
5272 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005273 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005274 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005275 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005276 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5277 return OK;
5278 }
5279 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5280 return PERMISSION_DENIED;
5281#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005282}
5283
Ana Krulec13be8ad2018-08-21 02:43:56 +00005284status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5285 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005286 status_t credentialCheck = CheckTransactCodeCredentials(code);
5287 if (credentialCheck != OK) {
5288 return credentialCheck;
5289 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005290
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005291 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5292 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005293 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005294 IPCThreadState* ipc = IPCThreadState::self();
5295 const int uid = ipc->getCallingUid();
5296 if (CC_UNLIKELY(uid != AID_SYSTEM
5297 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005298 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005299 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005300 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005301 return PERMISSION_DENIED;
5302 }
5303 int n;
5304 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005305 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005306 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005307 return NO_ERROR;
5308 case 1002: // SHOW_UPDATES
5309 n = data.readInt32();
5310 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005311 invalidateHwcGeometry();
5312 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005313 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005314 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005315 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005316 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005317 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005318 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005319 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005320 setTransactionFlags(
5321 eTransactionNeeded|
5322 eDisplayTransactionNeeded|
5323 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005324 return NO_ERROR;
5325 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005326 case 1006:{ // send empty update
5327 signalRefresh();
5328 return NO_ERROR;
5329 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005330 case 1008: // toggle use of hw composer
5331 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005332 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005333 invalidateHwcGeometry();
5334 repaintEverything();
5335 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005336 case 1009: // toggle use of transform hint
5337 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005338 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005339 invalidateHwcGeometry();
5340 repaintEverything();
5341 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005342 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005343 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005344 reply->writeInt32(0);
5345 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005346 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005347 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005348 return NO_ERROR;
5349 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005350 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005351 if (!display) {
5352 return NAME_NOT_FOUND;
5353 }
5354
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005355 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005356 return NO_ERROR;
5357 }
5358 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005359 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005360 // daltonize
5361 n = data.readInt32();
5362 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005363 case 1:
5364 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5365 break;
5366 case 2:
5367 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5368 break;
5369 case 3:
5370 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5371 break;
5372 default:
5373 mDaltonizer.setType(ColorBlindnessType::None);
5374 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005375 }
5376 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005377 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005378 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005379 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005380 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005381
5382 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005383 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005384 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005385 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005386 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005387 // apply a color matrix
5388 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005389 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005390 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005391 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005392 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005393 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005394 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005395 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005396 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005397 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005398 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005399
5400 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5401 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005402 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005403 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5404 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5405 }
5406
Chia-I Wu28f320b2018-05-03 11:02:56 -07005407 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005408 return NO_ERROR;
5409 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005410 // This is an experimental interface
5411 // Needs to be shifted to proper binder interface when we productize
5412 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005413 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005414 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005415 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005416 return NO_ERROR;
5417 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005418 case 1017: {
5419 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005420 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005421 return NO_ERROR;
5422 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005423 case 1018: { // Modify Choreographer's phase offset
5424 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005425 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005426 return NO_ERROR;
5427 }
5428 case 1019: { // Modify SurfaceFlinger's phase offset
5429 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005430 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005431 return NO_ERROR;
5432 }
Irvel468051e2016-06-13 16:44:44 -07005433 case 1020: { // Layer updates interceptor
5434 n = data.readInt32();
5435 if (n) {
5436 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005437 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005438 }
5439 else{
5440 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005441 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005442 }
5443 return NO_ERROR;
5444 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005445 case 1021: { // Disable HWC virtual displays
5446 n = data.readInt32();
5447 mUseHwcVirtualDisplays = !n;
5448 return NO_ERROR;
5449 }
Romain Guy0147a172017-06-01 13:53:56 -07005450 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005451 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005452 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005453
Chia-I Wu28f320b2018-05-03 11:02:56 -07005454 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005455 return NO_ERROR;
5456 }
Romain Guy54f154a2017-10-24 21:40:32 +01005457 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005458 int32_t colorMode;
5459
Chia-I Wu0d711262018-05-21 15:19:35 -07005460 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005461 if (data.readInt32(&colorMode) == NO_ERROR) {
5462 mForceColorMode = static_cast<ColorMode>(colorMode);
5463 }
Romain Guy54f154a2017-10-24 21:40:32 +01005464 invalidateHwcGeometry();
5465 repaintEverything();
5466 return NO_ERROR;
5467 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005468 // Deprecate, use 1030 to check whether the device is color managed.
5469 case 1024: {
5470 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005471 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005472 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005473 n = data.readInt32();
5474 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005475 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005476 Mutex::Autolock lock(mStateLock);
5477 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005478 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005479 reply->writeInt32(NO_ERROR);
5480 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005481 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005482 bool writeFile = false;
5483 {
5484 Mutex::Autolock lock(mStateLock);
5485 mTracingEnabledChanged = true;
5486 writeFile = mTracing.disable();
5487 }
5488
5489 if (writeFile) {
5490 reply->writeInt32(mTracing.writeToFile());
5491 } else {
5492 reply->writeInt32(NO_ERROR);
5493 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005494 }
5495 return NO_ERROR;
5496 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005497 case 1026: { // Get layer tracing status
5498 reply->writeBool(mTracing.isEnabled());
5499 return NO_ERROR;
5500 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005501 // Is a DisplayColorSetting supported?
5502 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005503 const auto display = getDefaultDisplayDevice();
5504 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005505 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005506 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005507
5508 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5509 switch (setting) {
5510 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005511 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005512 break;
5513 case DisplayColorSetting::UNMANAGED:
5514 reply->writeBool(true);
5515 break;
5516 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005517 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005518 break;
5519 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005520 reply->writeBool(
5521 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005522 break;
5523 }
5524 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005525 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005526 // Is VrFlinger active?
5527 case 1028: {
5528 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005529 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005530 return NO_ERROR;
5531 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005532 // Set buffer size for SF tracing (value in KB)
5533 case 1029: {
5534 n = data.readInt32();
5535 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5536 ALOGW("Invalid buffer size: %d KB", n);
5537 reply->writeInt32(BAD_VALUE);
5538 return BAD_VALUE;
5539 }
5540
5541 ALOGD("Updating trace buffer to %d KB", n);
5542 mTracing.setBufferSize(n * 1024);
5543 reply->writeInt32(NO_ERROR);
5544 return NO_ERROR;
5545 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005546 // Is device color managed?
5547 case 1030: {
5548 reply->writeBool(useColorManagement);
5549 return NO_ERROR;
5550 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005551 // Override default composition data space
5552 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5553 // && adb shell stop zygote && adb shell start zygote
5554 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5555 // adb shell stop zygote && adb shell start zygote
5556 case 1031: {
5557 Mutex::Autolock _l(mStateLock);
5558 n = data.readInt32();
5559 if (n) {
5560 n = data.readInt32();
5561 if (n) {
5562 Dataspace dataspace = static_cast<Dataspace>(n);
5563 if (!validateCompositionDataspace(dataspace)) {
5564 return BAD_VALUE;
5565 }
5566 mDefaultCompositionDataspace = dataspace;
5567 }
5568 n = data.readInt32();
5569 if (n) {
5570 Dataspace dataspace = static_cast<Dataspace>(n);
5571 if (!validateCompositionDataspace(dataspace)) {
5572 return BAD_VALUE;
5573 }
5574 mWideColorGamutCompositionDataspace = dataspace;
5575 }
5576 } else {
5577 // restore composition data space.
5578 mDefaultCompositionDataspace = defaultCompositionDataspace;
5579 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5580 }
5581 return NO_ERROR;
5582 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005583 // Set trace flags
5584 case 1033: {
5585 n = data.readUint32();
5586 ALOGD("Updating trace flags to 0x%x", n);
5587 mTracing.setTraceFlags(n);
5588 reply->writeInt32(NO_ERROR);
5589 return NO_ERROR;
5590 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005591 case 1034: {
5592 // TODO(b/129297325): expose this via developer menu option
5593 n = data.readInt32();
5594 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005595 RefreshRateType type;
5596 {
5597 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5598 type = mDesiredActiveConfig.type;
5599 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005600 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005601 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005602 } else if (!n) {
5603 mRefreshRateOverlay.reset();
5604 }
5605 return NO_ERROR;
5606 }
Ady Abraham34392f72019-04-10 11:29:27 -07005607 case 1035: {
5608 n = data.readInt32();
5609 mDebugDisplayConfigSetByBackdoor = false;
5610 if (n >= 0) {
5611 const auto displayToken = getInternalDisplayToken();
5612 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5613 if (result != NO_ERROR) {
5614 return result;
5615 }
5616 mDebugDisplayConfigSetByBackdoor = true;
5617 }
5618 return NO_ERROR;
5619 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005620 }
5621 }
5622 return err;
5623}
5624
Steven Thomas6d8110b2017-08-31 18:24:21 -07005625void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005626 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005627 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005628}
5629
Ana Krulec7d1d6832018-12-27 11:10:09 -08005630void SurfaceFlinger::repaintEverythingForHWC() {
5631 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005632 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005633}
5634
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005635// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5636class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005637public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5639 ~WindowDisconnector() {
5640 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005641 }
5642
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005643private:
5644 ANativeWindow* mWindow;
5645 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005646};
5647
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005648status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005649 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5650 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005651 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005652 uint32_t reqWidth, uint32_t reqHeight,
5653 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005654 ISurfaceComposer::Rotation rotation,
5655 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005657
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005658 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005659
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005660 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5661
Chia-I Wu20261cb2018-08-23 12:55:44 -07005662 sp<DisplayDevice> display;
5663 {
5664 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005665
Chia-I Wu20261cb2018-08-23 12:55:44 -07005666 display = getDisplayDeviceLocked(displayToken);
5667 if (!display) return BAD_VALUE;
5668
Chia-I Wucb023152018-08-28 12:57:23 -07005669 // set the requested width/height to the logical display viewport size
5670 // by default
5671 if (reqWidth == 0 || reqHeight == 0) {
5672 reqWidth = uint32_t(display->getViewport().width());
5673 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005674 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005675 }
5676
Peiyong Lin0e003c92018-09-17 11:09:51 -07005677 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005678 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005679
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005680 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5681 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005682 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005683 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005684}
5685
chaviw93df2ea2019-04-30 16:45:12 -07005686static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5687 switch (colorMode) {
5688 case ColorMode::DISPLAY_P3:
5689 case ColorMode::BT2100_PQ:
5690 case ColorMode::BT2100_HLG:
5691 case ColorMode::DISPLAY_BT2020:
5692 return Dataspace::DISPLAY_P3;
5693 default:
5694 return Dataspace::V0_SRGB;
5695 }
5696}
5697
5698const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5699 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5700 if (displayToken) {
5701 return getDisplayDeviceLocked(displayToken);
5702 }
5703 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5704 // may not have a displayId.
5705 for (const auto& [token, display] : mDisplays) {
5706 if (display->getLayerStack() == displayOrLayerStack) {
5707 return display;
5708 }
5709 }
5710 return nullptr;
5711}
5712
5713status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5714 sp<GraphicBuffer>* outBuffer) {
5715 sp<DisplayDevice> display;
5716 uint32_t width;
5717 uint32_t height;
5718 ui::Transform::orientation_flags captureOrientation;
5719 {
5720 Mutex::Autolock _l(mStateLock);
5721 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5722 if (!display) {
5723 return BAD_VALUE;
5724 }
5725
5726 width = uint32_t(display->getViewport().width());
5727 height = uint32_t(display->getViewport().height());
5728
5729 captureOrientation = fromSurfaceComposerRotation(
5730 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005731 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5732 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5733 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5734 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5735 }
chaviw93df2ea2019-04-30 16:45:12 -07005736 *outDataspace =
5737 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5738 }
5739
5740 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5741 false /* captureSecureLayers */);
5742
5743 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5744 std::placeholders::_1);
5745 bool ignored = false;
5746 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5747 false /* useIdentityTransform */,
5748 ignored /* outCapturedSecureLayers */);
5749}
5750
Robert Carr866455f2019-04-02 16:28:26 -07005751status_t SurfaceFlinger::captureLayers(
5752 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5753 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5754 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5755 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005756 ATRACE_CALL();
5757
5758 class LayerRenderArea : public RenderArea {
5759 public:
Robert Carr578038f2018-03-09 12:25:24 -08005760 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005761 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5762 bool childrenOnly)
5763 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005764 mLayer(layer),
5765 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005766 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005767 mFlinger(flinger),
5768 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005769 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005770 Rect getBounds() const override {
5771 const Layer::State& layerState(mLayer->getDrawingState());
5772 return mLayer->getBufferSize(layerState);
5773 }
Marissa Wall61c58622018-07-18 10:12:20 -07005774 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005775 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005776 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005777 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005778 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005779 }
chaviwa76b2712017-09-20 12:02:26 -07005780 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005781 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005782 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005783 Rect getSourceCrop() const override {
5784 if (mCrop.isEmpty()) {
5785 return getBounds();
5786 } else {
5787 return mCrop;
5788 }
5789 }
Robert Carr578038f2018-03-09 12:25:24 -08005790 class ReparentForDrawing {
5791 public:
5792 const sp<Layer>& oldParent;
5793 const sp<Layer>& newParent;
5794
Vishnu Nair4351ad52019-02-11 14:13:02 -08005795 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5796 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005797 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005798 // Compute and cache the bounds for the new parent layer.
5799 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005800 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005801 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005802 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005803 };
5804
5805 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005806 const Rect sourceCrop = getSourceCrop();
5807 // no need to check rotation because there is none
5808 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5809 sourceCrop.height() != getReqHeight();
5810
Robert Carr578038f2018-03-09 12:25:24 -08005811 if (!mChildrenOnly) {
5812 mTransform = mLayer->getTransform().inverse();
5813 drawLayers();
5814 } else {
5815 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005816 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005817 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005818 bounds.getWidth(), bounds.getHeight(), 0,
5819 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005820
Vishnu Nair4351ad52019-02-11 14:13:02 -08005821 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005822 drawLayers();
5823 }
5824 }
chaviwa76b2712017-09-20 12:02:26 -07005825
chaviwa76b2712017-09-20 12:02:26 -07005826 private:
chaviw7206d492017-11-10 16:16:12 -08005827 const sp<Layer> mLayer;
5828 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005829
5830 // In the "childrenOnly" case we reparent the children to a screenshot
5831 // layer which has no properties set and which does not draw.
5832 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005833 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005834 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005835
5836 SurfaceFlinger* mFlinger;
5837 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005838 };
5839
Robert Carrc0df3122019-04-11 13:18:21 -07005840 int reqWidth = 0;
5841 int reqHeight = 0;
5842 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005843 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005844 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005845
Robert Carrc0df3122019-04-11 13:18:21 -07005846 {
5847 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005848
Robert Carrc0df3122019-04-11 13:18:21 -07005849 parent = fromHandle(layerHandleBinder);
5850 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5851 ALOGE("captureLayers called with an invalid or removed parent");
5852 return NAME_NOT_FOUND;
5853 }
5854
5855 const int uid = IPCThreadState::self()->getCallingUid();
5856 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5857 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5858 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5859 return PERMISSION_DENIED;
5860 }
5861
5862 if (sourceCrop.width() <= 0) {
5863 crop.left = 0;
5864 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5865 }
5866
5867 if (sourceCrop.height() <= 0) {
5868 crop.top = 0;
5869 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5870 }
5871 reqWidth = crop.width() * frameScale;
5872 reqHeight = crop.height() * frameScale;
5873
5874 for (const auto& handle : excludeHandles) {
5875 sp<Layer> excludeLayer = fromHandle(handle);
5876 if (excludeLayer != nullptr) {
5877 excludeLayers.emplace(excludeLayer);
5878 } else {
5879 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5880 return NAME_NOT_FOUND;
5881 }
5882 }
5883 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005884
Chia-I Wu20261cb2018-08-23 12:55:44 -07005885 // really small crop or frameScale
5886 if (reqWidth <= 0) {
5887 reqWidth = 1;
5888 }
5889 if (reqHeight <= 0) {
5890 reqHeight = 1;
5891 }
5892
Robert Carr866455f2019-04-02 16:28:26 -07005893 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5894 auto traverseLayers = [parent, childrenOnly,
5895 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005896 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5897 if (!layer->isVisible()) {
5898 return;
Robert Carr578038f2018-03-09 12:25:24 -08005899 } else if (childrenOnly && layer == parent.get()) {
5900 return;
chaviwa76b2712017-09-20 12:02:26 -07005901 }
Robert Carr866455f2019-04-02 16:28:26 -07005902
5903 sp<Layer> p = layer;
5904 while (p != nullptr) {
5905 if (excludeLayers.count(p) != 0) {
5906 return;
5907 }
5908 p = p->getParent();
5909 }
5910
chaviwa76b2712017-09-20 12:02:26 -07005911 visitor(layer);
5912 });
5913 };
Robert Carr108b2c72019-04-02 16:32:58 -07005914
5915 bool outCapturedSecureLayers = false;
5916 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5917 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005918}
5919
5920status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5921 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005922 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005923 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005924 bool useIdentityTransform,
5925 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005926 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005927
Peiyong Lin0e003c92018-09-17 11:09:51 -07005928 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005929 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5930 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005931 *outBuffer =
5932 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5933 static_cast<android_pixel_format>(reqPixelFormat), 1,
5934 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005935
Robert Carr108b2c72019-04-02 16:32:58 -07005936 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5937 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005938}
5939
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005940status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5941 TraverseLayersFunction traverseLayers,
5942 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005943 bool useIdentityTransform,
5944 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005945 // This mutex protects syncFd and captureResult for communication of the return values from the
5946 // main thread back to this Binder thread
5947 std::mutex captureMutex;
5948 std::condition_variable captureCondition;
5949 std::unique_lock<std::mutex> captureLock(captureMutex);
5950 int syncFd = -1;
5951 std::optional<status_t> captureResult;
5952
Robert Carr03480e22018-01-04 16:02:06 -08005953 const int uid = IPCThreadState::self()->getCallingUid();
5954 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5955
Dominik Laskowski8c001672018-05-30 16:52:06 -07005956 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005957 // If there is a refresh pending, bug out early and tell the binder thread to try again
5958 // after the refresh.
5959 if (mRefreshPending) {
5960 ATRACE_NAME("Skipping screenshot for now");
5961 std::unique_lock<std::mutex> captureLock(captureMutex);
5962 captureResult = std::make_optional<status_t>(EAGAIN);
5963 captureCondition.notify_one();
5964 return;
5965 }
5966
5967 status_t result = NO_ERROR;
5968 int fd = -1;
5969 {
5970 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005971 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005972 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005973 useIdentityTransform, forSystem, &fd,
5974 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005975 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005976 }
5977
5978 {
5979 std::unique_lock<std::mutex> captureLock(captureMutex);
5980 syncFd = fd;
5981 captureResult = std::make_optional<status_t>(result);
5982 captureCondition.notify_one();
5983 }
5984 });
5985
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005986 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005987 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005988 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005989 while (*captureResult == EAGAIN) {
5990 captureResult.reset();
5991 result = postMessageAsync(message);
5992 if (result != NO_ERROR) {
5993 return result;
5994 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005995 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005996 }
5997 result = *captureResult;
5998 }
5999
6000 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006001 sync_wait(syncFd, -1);
6002 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006003 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006004
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006005 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006006}
6007
chaviwa76b2712017-09-20 12:02:26 -07006008void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006009 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006010 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6011 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006012 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006013
chaviwa76b2712017-09-20 12:02:26 -07006014 const auto reqWidth = renderArea.getReqWidth();
6015 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006016 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006017 const auto transform = renderArea.getTransform();
6018 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006019
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006020 renderengine::DisplaySettings clientCompositionDisplay;
6021 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006022
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006023 // assume that bounds are never offset, and that they are the same as the
6024 // buffer bounds.
6025 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006026 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006027 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006028
6029 // Now take into account the rotation flag. We append a transform that
6030 // rotates the layer stack about the origin, then translate by buffer
6031 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006032 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006033 int displacementX = 0;
6034 int displacementY = 0;
6035 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6036 switch (rotation) {
6037 case ui::Transform::ROT_90:
6038 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006039 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006040 break;
6041 case ui::Transform::ROT_180:
6042 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006043 displacementY = renderArea.getBounds().getWidth();
6044 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006045 break;
6046 case ui::Transform::ROT_270:
6047 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006048 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006049 break;
6050 default:
6051 break;
6052 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006053
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006054 // We need to transform the clipping window into the right spot.
6055 // First, rotate the clipping rectangle by the rotation hint to get the
6056 // right orientation
6057 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6058 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6059 const vec4 rotClipTL = rotMatrix * clipTL;
6060 const vec4 rotClipBR = rotMatrix * clipBR;
6061 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6062 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6063 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6064 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6065
6066 // Now reposition the clipping rectangle with the displacement vector
6067 // computed above.
6068 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006069 clientCompositionDisplay.clip =
6070 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6071 newClipRight + displacementX, newClipBottom + displacementY);
6072
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006073 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006074 clientCompositionDisplay.globalTransform =
6075 clipTransform * clientCompositionDisplay.globalTransform;
6076
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006077 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6078 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006079
chaviw50da5042018-04-09 13:49:37 -07006080 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006081
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006082 renderengine::LayerSettings fillLayer;
6083 fillLayer.source.buffer.buffer = nullptr;
6084 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6085 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6086 fillLayer.alpha = half(alpha);
6087 clientCompositionLayers.push_back(fillLayer);
6088
6089 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006090 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006091 renderengine::LayerSettings layerSettings;
6092 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006093 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006094 if (prepared) {
6095 clientCompositionLayers.push_back(layerSettings);
6096 }
chaviwa76b2712017-09-20 12:02:26 -07006097 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006098
6099 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006100 // Use an empty fence for the buffer fence, since we just created the buffer so
6101 // there is no need for synchronization with the GPU.
6102 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006103 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006104 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006105 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006106 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006107
6108 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006109}
6110
chaviwa76b2712017-09-20 12:02:26 -07006111status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6112 TraverseLayersFunction traverseLayers,
6113 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006114 bool useIdentityTransform, bool forSystem,
6115 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006116 ATRACE_CALL();
6117
chaviwa76b2712017-09-20 12:02:26 -07006118 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006119 outCapturedSecureLayers =
6120 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006121 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006122
Robert Carr03480e22018-01-04 16:02:06 -08006123 // We allow the system server to take screenshots of secure layers for
6124 // use in situations like the Screen-rotation animation and place
6125 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006126 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006127 ALOGW("FB is protected: PERMISSION_DENIED");
6128 return PERMISSION_DENIED;
6129 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006130 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006131 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006132}
6133
chaviw95ef3c42019-02-14 10:55:09 -08006134void SurfaceFlinger::setInputWindowsFinished() {
6135 Mutex::Autolock _l(mStateLock);
6136
6137 mPendingSyncInputWindows = false;
6138 mTransactionCV.broadcast();
6139}
chaviw5f21a5e2019-02-14 10:00:34 -08006140
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006141// ---------------------------------------------------------------------------
6142
Dan Stoza412903f2017-04-27 13:42:17 -07006143void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6144 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006145}
6146
Dan Stoza412903f2017-04-27 13:42:17 -07006147void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6148 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006149}
6150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006151void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006152 const LayerVector::Visitor& visitor) {
6153 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006154 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006155 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006156 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006157 continue;
6158 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006159 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006160 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006161 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006162 return;
6163 }
chaviwa76b2712017-09-20 12:02:26 -07006164 if (!layer->isVisible()) {
6165 return;
6166 }
6167 visitor(layer);
6168 });
6169 }
6170}
6171
Dominik Laskowski22488f62019-03-28 09:53:04 -07006172void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6173 const std::vector<int32_t>& allowedConfigs) {
6174 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006175 return;
6176 }
6177
6178 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006179 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006180
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006181 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006182 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006183 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006184 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006185 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006186 setDesiredActiveConfig(
6187 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006188 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006189 }
6190 }
Ady Abraham838de062019-02-04 10:24:03 -08006191}
6192
Dominik Laskowski22488f62019-03-28 09:53:04 -07006193status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006194 const std::vector<int32_t>& allowedConfigs) {
6195 ATRACE_CALL();
6196
Dominik Laskowski22488f62019-03-28 09:53:04 -07006197 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006198 return BAD_VALUE;
6199 }
6200
Ady Abraham34392f72019-04-10 11:29:27 -07006201 if (mDebugDisplayConfigSetByBackdoor) {
6202 // ignore this request as config is overridden by backdoor
6203 return NO_ERROR;
6204 }
6205
Ady Abraham838de062019-02-04 10:24:03 -08006206 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006207 const auto display = getDisplayDeviceLocked(displayToken);
6208 if (!display) {
6209 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6210 displayToken.get());
6211 } else if (display->isVirtual()) {
6212 ALOGW("Attempt to set allowed display configs for virtual display");
6213 } else {
6214 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6215 }
Ady Abraham838de062019-02-04 10:24:03 -08006216 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006217
Ady Abraham838de062019-02-04 10:24:03 -08006218 return NO_ERROR;
6219}
6220
Dominik Laskowski22488f62019-03-28 09:53:04 -07006221status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006222 std::vector<int32_t>* outAllowedConfigs) {
6223 ATRACE_CALL();
6224
Dominik Laskowski22488f62019-03-28 09:53:04 -07006225 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006226 return BAD_VALUE;
6227 }
6228
Dominik Laskowski22488f62019-03-28 09:53:04 -07006229 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006230
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006231 const auto display = getDisplayDeviceLocked(displayToken);
6232 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006233 return NAME_NOT_FOUND;
6234 }
6235
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006236 if (display->isPrimary()) {
6237 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6238 }
6239
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006240 return NO_ERROR;
6241}
6242
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006243void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006244 mFlinger->setInputWindowsFinished();
6245}
6246
Robert Carrc0df3122019-04-11 13:18:21 -07006247sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6248 BBinder *b = handle->localBinder();
6249 if (b == nullptr) {
6250 return nullptr;
6251 }
6252 auto it = mLayersByLocalBinderToken.find(b);
6253 if (it != mLayersByLocalBinderToken.end()) {
6254 return it->second.promote();
6255 }
6256 return nullptr;
6257}
6258
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006259} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006260
Mathias Agopian3f844832013-08-07 21:24:32 -07006261#if defined(__gl_h_)
6262#error "don't include gl/gl.h in this file"
6263#endif
6264
6265#if defined(__gl2_h_)
6266#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006267#endif