blob: 1c8cc35abf2d256fcd1f18d1ff0d9866e55678dd [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
Steven Thomas137d4bc2019-07-25 16:55:14 -0700706 char primeShaderCache[PROPERTY_VALUE_MAX];
707 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
708 if (atoi(primeShaderCache)) {
709 getRenderEngine().primeCache();
710 }
Dan Stoza4e637772016-07-28 13:31:51 -0700711
Wei Wangf9b05ee2017-07-19 20:59:39 -0700712 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700713
714 const bool presentFenceReliable =
715 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
716 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717
718 if (mStartPropertySetThread->Start() != NO_ERROR) {
719 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800720 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800721
Alec Mouri93bc83d2019-04-17 14:47:43 -0700722 mScheduler->setChangeRefreshRateCallback(
723 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
724 Mutex::Autolock lock(mStateLock);
725 setRefreshRateTo(type, event);
726 });
Alec Mouri7f015182019-07-11 13:56:22 -0700727 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
728 Mutex::Autolock lock(mStateLock);
729 const auto display = getDefaultDisplayDeviceLocked();
730 if (!display) {
731 // If we don't have a default display the fallback to the default
732 // refresh rate type
733 return RefreshRateType::DEFAULT;
734 }
735
736 const int configId = display->getActiveConfig();
737 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
738 if (refresh && refresh->configId == configId) {
739 return type;
740 }
741 }
742 // This should never happen, but just gracefully fallback to default.
743 return RefreshRateType::DEFAULT;
744 });
Alec Mouridc28b372019-04-18 21:17:13 -0700745 mScheduler->setGetVsyncPeriodCallback([this] {
746 Mutex::Autolock lock(mStateLock);
747 return getVsyncPeriod();
748 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700749
Dominik Laskowski22488f62019-03-28 09:53:04 -0700750 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
751 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800752
Dan Stoza9e56aa02015-11-02 13:00:03 -0800753 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700754}
755
Romain Guy11d63f42017-07-20 12:47:14 -0700756void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700757 Mutex::Autolock _l(mStateLock);
758
Romain Guy11d63f42017-07-20 12:47:14 -0700759 char value[PROPERTY_VALUE_MAX];
760
761 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800762 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700763 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800764 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100765
766 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700767 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800768
769 property_get("persist.sys.sf.color_mode", value, "0");
770 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700771}
772
Mathias Agopiana67e4182012-06-19 17:26:12 -0700773void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800774 // Start boot animation service by setting a property mailbox
775 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700776 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800777 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700778 if (mStartPropertySetThread->join() != NO_ERROR) {
779 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800780 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700781}
782
Mathias Agopian875d8e12013-06-07 15:35:48 -0700783size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700784 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800791// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800792
Jamie Gennis582270d2011-08-17 18:19:00 -0700793bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800794 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800795 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800796 return authenticateSurfaceTextureLocked(bufferProducer);
797}
798
799bool SurfaceFlinger::authenticateSurfaceTextureLocked(
800 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800801 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800802 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800803}
804
Brian Anderson6b376712017-04-04 10:51:39 -0700805status_t SurfaceFlinger::getSupportedFrameTimestamps(
806 std::vector<FrameEvent>* outSupported) const {
807 *outSupported = {
808 FrameEvent::REQUESTED_PRESENT,
809 FrameEvent::ACQUIRE,
810 FrameEvent::LATCH,
811 FrameEvent::FIRST_REFRESH_START,
812 FrameEvent::LAST_REFRESH_START,
813 FrameEvent::GPU_COMPOSITION_DONE,
814 FrameEvent::DEQUEUE_READY,
815 FrameEvent::RELEASE,
816 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700817 ConditionalLock _l(mStateLock,
818 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700819 if (!getHwComposer().hasCapability(
820 HWC2::Capability::PresentFenceIsNotReliable)) {
821 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
822 }
823 return NO_ERROR;
824}
825
Dominik Laskowski22488f62019-03-28 09:53:04 -0700826status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
827 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700828 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700829 return BAD_VALUE;
830 }
831
Dominik Laskowski22488f62019-03-28 09:53:04 -0700832 Mutex::Autolock lock(mStateLock);
833
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800834 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700835 if (!displayId) {
836 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700837 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 // TODO: Not sure if display density should handled by SF any longer
840 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700843 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800844 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700845 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700846 }
847 return density;
848 }
849 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700850 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700851 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700852 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853 return getDensityFromProperty("ro.sf.lcd_density"); }
854 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700855
Dan Stoza7f7da322014-05-02 15:26:25 -0700856 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700857
Dominik Laskowski075d3172018-05-24 15:50:06 -0700858 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700859 DisplayInfo info = DisplayInfo();
860
Dan Stoza9e56aa02015-11-02 13:00:03 -0800861 float xdpi = hwConfig->getDpiX();
862 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700863
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700864 info.w = hwConfig->getWidth();
865 info.h = hwConfig->getHeight();
866 // Default display viewport to display width and height
867 info.viewportW = info.w;
868 info.viewportH = info.h;
869
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800870 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 // The density of the device is provided by a build property
872 float density = Density::getBuildDensity() / 160.0f;
873 if (density == 0) {
874 // the build doesn't provide a density -- this is wrong!
875 // use xdpi instead
876 ALOGE("ro.sf.lcd_density must be defined as a build property");
877 density = xdpi / 160.0f;
878 }
879 if (Density::getEmuDensity()) {
880 // if "qemu.sf.lcd_density" is specified, it overrides everything
881 xdpi = ydpi = density = Density::getEmuDensity();
882 density /= 160.0f;
883 }
884 info.density = density;
885
886 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887 const auto display = getDefaultDisplayDeviceLocked();
888 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700889
890 // This is for screenrecord
891 const Rect viewport = display->getViewport();
892 if (viewport.isValid()) {
893 info.viewportW = uint32_t(viewport.getWidth());
894 info.viewportH = uint32_t(viewport.getHeight());
895 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700896 } else {
897 // TODO: where should this value come from?
898 static const int TV_DENSITY = 213;
899 info.density = TV_DENSITY / 160.0f;
900 info.orientation = 0;
901 }
902
Dan Stoza7f7da322014-05-02 15:26:25 -0700903 info.xdpi = xdpi;
904 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700906 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
907 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
908 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800909
Andy McFadden91b2ca82014-06-13 14:04:23 -0700910 // This is how far in advance a buffer must be queued for
911 // presentation at a given time. If you want a buffer to appear
912 // on the screen at time N, you must submit the buffer before
913 // (N - presentationDeadline).
914 //
915 // Normally it's one full refresh period (to give SF a chance to
916 // latch the buffer), but this can be reduced by configuring a
917 // DispSync offset. Any additional delays introduced by the hardware
918 // composer or panel must be accounted for here.
919 //
920 // We add an additional 1ms to allow for processing time and
921 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700922 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700923
924 // All non-virtual displays are currently considered secure.
925 info.secure = true;
926
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800927 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700928 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800929 std::swap(info.w, info.h);
930 }
931
Michael Wright28f24d02016-07-12 13:30:53 -0700932 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700933 }
934
Dan Stoza7f7da322014-05-02 15:26:25 -0700935 return NO_ERROR;
936}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
939 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700940 return BAD_VALUE;
941 }
942
Ana Krulecc2870422019-01-29 19:00:58 -0800943 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700944 return NO_ERROR;
945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
948 const auto display = getDisplayDevice(displayToken);
949 if (!display) {
950 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800951 return BAD_VALUE;
952 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700955}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700956
Ady Abraham03b02dd2019-03-21 15:40:11 -0700957void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800959
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800961 // config twice. However event generation config might have changed so we need to update it
962 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700964 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
965 mDesiredActiveConfig = info;
966 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967
968 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800969 // This will trigger HWC refresh without resetting the idle timer.
970 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700971 // Start receiving vsync samples now, so that we can detect a period
972 // switch.
973 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700974 // As we called to set period, we will call to onRefreshRateChangeCompleted once
975 // DispSync model is locked.
976 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700977 mPhaseOffsets->setRefreshRateType(info.type);
978 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700979 mVsyncModulator.setPhaseOffsets(early, gl, late,
980 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800982 mDesiredActiveConfigChanged = true;
983 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700984
985 if (mRefreshRateOverlay) {
986 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
987 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988}
989
990status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
991 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800992
993 std::vector<int32_t> allowedConfig;
994 allowedConfig.push_back(mode);
995
996 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997}
998
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999void SurfaceFlinger::setActiveConfigInternal() {
1000 ATRACE_CALL();
1001
Dominik Laskowski22488f62019-03-28 09:53:04 -07001002 const auto display = getDefaultDisplayDeviceLocked();
1003 if (!display) {
1004 return;
1005 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001006
Dominik Laskowski22488f62019-03-28 09:53:04 -07001007 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1008 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
1009
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010 display->setActiveConfig(mUpcomingActiveConfig.configId);
1011
Alec Mouri754c98a2019-03-18 18:53:42 -07001012 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001013 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001014 mVsyncModulator.setPhaseOffsets(early, gl, late,
1015 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001016 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001017
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001018 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001019 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1020 mUpcomingActiveConfig.configId);
1021 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022}
1023
Ady Abraham53852a52019-05-28 18:07:44 -07001024void SurfaceFlinger::desiredActiveConfigChangeDone() {
1025 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1026 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1027 mDesiredActiveConfigChanged = false;
1028 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1029
1030 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1031 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1032 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001033 mVsyncModulator.setPhaseOffsets(early, gl, late,
1034 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -07001035}
1036
Dominik Laskowski22488f62019-03-28 09:53:04 -07001037bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001038 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001040 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001042 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 return true;
1044 }
1045
1046 // We received the present fence from the HWC, so we assume it successfully updated
1047 // the config, hence we update SF.
1048 mCheckPendingFence = false;
1049 setActiveConfigInternal();
1050 }
1051
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001052 // Store the local variable to release the lock.
1053 ActiveConfigInfo desiredActiveConfig;
1054 {
1055 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 if (!mDesiredActiveConfigChanged) {
1057 return false;
1058 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001059 desiredActiveConfig = mDesiredActiveConfig;
1060 }
1061
Dominik Laskowski22488f62019-03-28 09:53:04 -07001062 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001063 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1064 // display is not valid or we are already in the requested mode
1065 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001066 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001067 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001068 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001069
Ady Abraham838de062019-02-04 10:24:03 -08001070 // Desired active config was set, it is different than the config currently in use, however
1071 // allowed configs might have change by the time we process the refresh.
1072 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001073 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001074 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001075 return false;
1076 }
Alec Mouri7f015182019-07-11 13:56:22 -07001077
Ady Abrahamb838aed2019-02-12 15:30:16 -08001078 mUpcomingActiveConfig = desiredActiveConfig;
1079 const auto displayId = display->getId();
1080 LOG_ALWAYS_FATAL_IF(!displayId);
1081
1082 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1083 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1084
1085 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001086 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001087 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001088 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001089}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1092 Vector<ColorMode>* outColorModes) {
1093 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001094 return BAD_VALUE;
1095 }
1096
Peiyong Lina52f0292018-03-14 17:26:31 -07001097 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001098 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001099 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001100 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1101
1102 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1103 if (!displayId) {
1104 return NAME_NOT_FOUND;
1105 }
1106
Dominik Laskowski075d3172018-05-24 15:50:06 -07001107 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001108 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001109 }
Michael Wright28f24d02016-07-12 13:30:53 -07001110 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001111
1112 // If it's built-in display and the configuration claims it's not wide color capable,
1113 // filter out all wide color modes. The typical reason why this happens is that the
1114 // hardware is not good enough to support GPU composition of wide color, and thus the
1115 // OEMs choose to disable this capability.
1116 if (isInternalDisplay && !hasWideColorDisplay) {
1117 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1118 isWideColorMode);
1119 } else {
1120 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1121 }
Michael Wright28f24d02016-07-12 13:30:53 -07001122
1123 return NO_ERROR;
1124}
1125
Daniel Solomon42d04562019-01-20 21:03:19 -08001126status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1127 ui::DisplayPrimaries &primaries) {
1128 if (!displayToken) {
1129 return BAD_VALUE;
1130 }
1131
1132 // Currently we only support this API for a single internal display.
1133 if (getInternalDisplayToken() != displayToken) {
1134 return BAD_VALUE;
1135 }
1136
1137 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1138 return NO_ERROR;
1139}
1140
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001141ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1142 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001143 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001144 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001145 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001146}
1147
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001148status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001149 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001150 Vector<ColorMode> modes;
1151 getDisplayColorModes(displayToken, &modes);
1152 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1153 if (mode < ColorMode::NATIVE || !exists) {
1154 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1155 decodeColorMode(mode).c_str(), mode, displayToken.get());
1156 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001157 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001158 const auto display = getDisplayDevice(displayToken);
1159 if (!display) {
1160 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1161 decodeColorMode(mode).c_str(), mode, displayToken.get());
1162 } else if (display->isVirtual()) {
1163 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1164 decodeColorMode(mode).c_str(), mode);
1165 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001166 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1167 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 }
1169 }));
1170
Michael Wright28f24d02016-07-12 13:30:53 -07001171 return NO_ERROR;
1172}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001173
Svetoslavd85084b2014-03-20 10:28:31 -07001174status_t SurfaceFlinger::clearAnimationFrameStats() {
1175 Mutex::Autolock _l(mStateLock);
1176 mAnimFrameTracker.clearStats();
1177 return NO_ERROR;
1178}
1179
1180status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1181 Mutex::Autolock _l(mStateLock);
1182 mAnimFrameTracker.getStats(outStats);
1183 return NO_ERROR;
1184}
1185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001186status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1187 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001188 Mutex::Autolock _l(mStateLock);
1189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001190 const auto display = getDisplayDeviceLocked(displayToken);
1191 if (!display) {
1192 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001193 return BAD_VALUE;
1194 }
1195
Peiyong Linfb069302018-04-25 14:34:31 -07001196 // At this point the DisplayDeivce should already be set up,
1197 // meaning the luminance information is already queried from
1198 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001199 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001200 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1201 capabilities.getDesiredMaxLuminance(),
1202 capabilities.getDesiredMaxAverageLuminance(),
1203 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001204
1205 return NO_ERROR;
1206}
1207
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001208status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1209 ui::PixelFormat* outFormat,
1210 ui::Dataspace* outDataspace,
1211 uint8_t* outComponentMask) const {
1212 if (!outFormat || !outDataspace || !outComponentMask) {
1213 return BAD_VALUE;
1214 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001215 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001216 if (!display || !display->getId()) {
1217 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1218 return BAD_VALUE;
1219 }
1220 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1221 outDataspace, outComponentMask);
1222}
1223
Kevin DuBois74e53772018-11-19 10:52:38 -08001224status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1225 bool enable, uint8_t componentMask,
1226 uint64_t maxFrames) const {
1227 const auto display = getDisplayDevice(displayToken);
1228 if (!display || !display->getId()) {
1229 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1230 return BAD_VALUE;
1231 }
1232
1233 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1234 componentMask, maxFrames);
1235}
1236
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001237status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1238 uint64_t maxFrames, uint64_t timestamp,
1239 DisplayedFrameStats* outStats) const {
1240 const auto display = getDisplayDevice(displayToken);
1241 if (!display || !display->getId()) {
1242 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1243 return BAD_VALUE;
1244 }
1245
1246 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1247 outStats);
1248}
1249
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001250status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1251 if (!outSupported) {
1252 return BAD_VALUE;
1253 }
1254 *outSupported = getRenderEngine().supportsProtectedContent();
1255 return NO_ERROR;
1256}
1257
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001258status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1259 bool* outIsWideColorDisplay) const {
1260 if (!displayToken || !outIsWideColorDisplay) {
1261 return BAD_VALUE;
1262 }
1263 Mutex::Autolock _l(mStateLock);
1264 const auto display = getDisplayDeviceLocked(displayToken);
1265 if (!display) {
1266 return BAD_VALUE;
1267 }
Peiyong Linff84a152019-05-17 18:36:19 -07001268
1269 // Use hasWideColorDisplay to override built-in display.
1270 const auto displayId = display->getId();
1271 if (displayId && displayId == getInternalDisplayIdLocked()) {
1272 *outIsWideColorDisplay = hasWideColorDisplay;
1273 return NO_ERROR;
1274 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001275 *outIsWideColorDisplay = display->hasWideColorGamut();
1276 return NO_ERROR;
1277}
1278
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001279status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001280 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001281 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001282
Chia-I Wu90f669f2017-10-05 14:24:41 -07001283 if (mInjectVSyncs == enable) {
1284 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001285 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001286
Ana Krulecc2870422019-01-29 19:00:58 -08001287 auto resyncCallback =
1288 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001289
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001290 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001291 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001292 if (enable) {
1293 ALOGV("VSync Injections enabled");
1294 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001295 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001296 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001297 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001298 impl::EventThread::InterceptVSyncsCallback(),
1299 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001300 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001301 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001302 } else {
1303 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001304 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1305 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001306 }
1307
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001308 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001309 }));
1310
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001311 return NO_ERROR;
1312}
1313
1314status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001315 Mutex::Autolock _l(mStateLock);
1316
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001317 if (!mInjectVSyncs) {
1318 ALOGE("VSync Injections not enabled");
1319 return BAD_VALUE;
1320 }
1321 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1322 ALOGV("Injecting VSync inside SurfaceFlinger");
1323 mVSyncInjector->onInjectSyncEvent(when);
1324 }
1325 return NO_ERROR;
1326}
1327
Lloyd Pique755e3192018-01-31 16:46:15 -08001328status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1329 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001330 // Try to acquire a lock for 1s, fail gracefully
1331 const status_t err = mStateLock.timedLock(s2ns(1));
1332 const bool locked = (err == NO_ERROR);
1333 if (!locked) {
1334 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1335 return TIMED_OUT;
1336 }
1337
1338 outLayers->clear();
1339 mCurrentState.traverseInZOrder([&](Layer* layer) {
1340 outLayers->push_back(layer->getLayerDebugInfo());
1341 });
1342
1343 mStateLock.unlock();
1344 return NO_ERROR;
1345}
1346
Peiyong Linc6780972018-10-28 15:24:08 -07001347status_t SurfaceFlinger::getCompositionPreference(
1348 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1349 Dataspace* outWideColorGamutDataspace,
1350 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001351 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001352 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001353 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001354 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001355 return NO_ERROR;
1356}
1357
Dan Stozaec460082018-12-17 15:35:09 -08001358status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1359 const sp<IBinder>& stopLayerHandle,
1360 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001361 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001362 return BAD_VALUE;
1363 }
1364 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001365 return NO_ERROR;
1366}
1367
Dan Stozaec460082018-12-17 15:35:09 -08001368status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001369 if (!listener) {
1370 return BAD_VALUE;
1371 }
Dan Stozaec460082018-12-17 15:35:09 -08001372 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001373 return NO_ERROR;
1374}
Dan Gittik57e63c52019-01-18 16:37:54 +00001375
1376status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1377 bool* outSupport) const {
1378 if (!displayToken || !outSupport) {
1379 return BAD_VALUE;
1380 }
1381 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1382 if (!displayId) {
1383 return NAME_NOT_FOUND;
1384 }
1385 *outSupport =
1386 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1387 return NO_ERROR;
1388}
1389
1390status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1391 float brightness) const {
1392 if (!displayToken) {
1393 return BAD_VALUE;
1394 }
1395 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1396 if (!displayId) {
1397 return NAME_NOT_FOUND;
1398 }
1399 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1400}
1401
Ady Abraham8532d012019-05-08 14:50:56 -07001402status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1403 PowerHint powerHint = static_cast<PowerHint>(hintId);
1404
1405 if (powerHint == PowerHint::INTERACTION) {
1406 mScheduler->notifyTouchEvent();
1407 }
1408
1409 return NO_ERROR;
1410}
1411
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001412// ----------------------------------------------------------------------------
1413
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001414sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001415 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001416 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001417 Mutex::Autolock lock(mStateLock);
1418 return getVsyncPeriod();
1419 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001420
Ana Krulecc2870422019-01-29 19:00:58 -08001421 const auto& handle =
1422 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001423
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001424 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1425 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001426}
1427
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001428// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001429
1430void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001431 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432}
1433
1434void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001435 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001436 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001437}
1438
1439void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001440 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001441 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001442}
1443
1444void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001445 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001446 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001447}
1448
1449status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001450 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001451 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001452}
1453
1454status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001455 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001456 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001457 if (res == NO_ERROR) {
1458 msg->wait();
1459 }
1460 return res;
1461}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001462
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001463void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001464 do {
1465 waitForEvent();
1466 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001467}
1468
Dominik Laskowski83b88212018-12-11 13:34:06 -08001469nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001470 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001471 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1472 return 0;
1473 }
1474
1475 const auto config = getHwComposer().getActiveConfig(*displayId);
1476 return config ? config->getVsyncPeriod() : 0;
1477}
1478
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001479void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1480 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001481 ATRACE_NAME("SF onVsync");
1482
Steven Thomas3cfac282017-02-06 12:29:30 -08001483 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001485 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 return;
1487 }
1488
Dominik Laskowski075d3172018-05-24 15:50:06 -07001489 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001490 return;
1491 }
1492
Dominik Laskowski075d3172018-05-24 15:50:06 -07001493 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001494 // For now, we don't do anything with external display vsyncs.
1495 return;
1496 }
1497
Alec Mourif8e689c2019-05-20 18:32:22 -07001498 bool periodFlushed = false;
1499 mScheduler->addResyncSample(timestamp, &periodFlushed);
1500 if (periodFlushed) {
1501 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001502 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001503}
1504
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001506 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1507 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001508}
1509
Ady Abraham261614e2019-07-10 17:53:12 -07001510bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001511 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001512}
1513
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001514void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001515 const auto display = getDefaultDisplayDeviceLocked();
1516 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001517 return;
1518 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001519 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001520
Ana Krulec7d1d6832018-12-27 11:10:09 -08001521 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001522 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001523 if (!refreshRateConfig) {
1524 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001525 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001526 }
Ady Abraham1902d072019-03-01 17:18:59 -08001527
Alec Mouri0a1cc962019-03-14 12:33:02 -07001528 const int desiredConfigId = refreshRateConfig->configId;
1529
Dominik Laskowski22488f62019-03-28 09:53:04 -07001530 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001531 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1532 return;
1533 }
1534
Dominik Laskowski22488f62019-03-28 09:53:04 -07001535 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001536}
1537
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001538void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001539 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001540 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001541 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542
Lloyd Piqueba04e622017-12-14 17:11:26 -08001543 // Ignore events that do not have the right sequenceId.
1544 if (sequenceId != getBE().mComposerSequenceId) {
1545 return;
1546 }
1547
Steven Thomasb02664d2017-07-26 18:48:28 -07001548 // Only lock if we're not on the main thread. This function is normally
1549 // called on a hwbinder thread, but for the primary display it's called on
1550 // the main thread with the state lock already held, so don't attempt to
1551 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001552 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001553
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001554 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001555
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001556 if (std::this_thread::get_id() == mMainThreadId) {
1557 // Process all pending hot plug events immediately if we are on the main thread.
1558 processDisplayHotplugEventsLocked();
1559 }
1560
Lloyd Piqueba04e622017-12-14 17:11:26 -08001561 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001562}
1563
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001564void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001565 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001566 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001568 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001569 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001570}
1571
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001572void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001573 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001574
1575 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1576 // display power state.
1577 postMessageAsync(new LambdaMessage(
1578 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1579}
1580
1581void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1582 ATRACE_CALL();
1583
Ady Abraham27c70212019-06-11 10:52:26 -07001584 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1585
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001586 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001587 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1588 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001589 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001590 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001591 }
Mathias Agopian86303202012-07-24 22:46:10 -07001592}
1593
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001595void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001596 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001597 // Clear the drawing state so that the logic inside of
1598 // handleTransactionLocked will fire. It will determine the delta between
1599 // mCurrentState and mDrawingState and re-apply all changes when we make the
1600 // transition.
1601 mDrawingState.displays.clear();
1602 mDisplays.clear();
1603}
1604
Steven Thomas050b2c82017-03-06 11:45:16 -08001605void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001606 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001607 if (!mVrFlinger)
1608 return;
1609 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001610 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001611 return;
1612 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613
Lloyd Pique441d5042018-10-18 16:49:51 -07001614 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 ALOGE("Vr flinger is only supported for remote hardware composer"
1616 " service connections. Ignoring request to transition to vr"
1617 " flinger.");
1618 mVrFlingerRequestsDisplay = false;
1619 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001620 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001621
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001623
Steven Thomas0123ac62018-07-12 11:32:34 -07001624 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001625 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001626
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001627 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001628
1629 // Clear out all the output layers from the composition engine for all
1630 // displays before destroying the hardware composer interface. This ensures
1631 // any HWC layers are destroyed through that interface before it becomes
1632 // invalid.
1633 for (const auto& [token, displayDevice] : mDisplays) {
1634 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1635 compositionengine::Output::OutputLayers());
1636 }
1637
Steven Thomas0123ac62018-07-12 11:32:34 -07001638 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1639 // called below. Clear the reference now so we don't accidentally use it
1640 // later.
1641 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001642
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001644 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001645 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001646
Steven Thomasb02664d2017-07-26 18:48:28 -07001647 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001648 // Delete the current instance before creating the new one
1649 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1650 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1651 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1652 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001653
Lloyd Pique441d5042018-10-18 16:49:51 -07001654 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001655 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001656
1657 if (vrFlingerRequestsDisplay) {
1658 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001659 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001660
1661 mVisibleRegionsDirty = true;
1662 invalidateHwcGeometry();
1663
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001664 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001665 display = getDefaultDisplayDeviceLocked();
1666 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001667 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001668
Steven Thomasb02664d2017-07-26 18:48:28 -07001669 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001670 const nsecs_t vsyncPeriod = getVsyncPeriod();
1671 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001672
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001673 // The present fences returned from vr_hwc are not an accurate
1674 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001675 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001676
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 // Use phase of 0 since phase is not known.
1678 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001679 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001680 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001681
Ana Krulecc2870422019-01-29 19:00:58 -08001682 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001683
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001684 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001686}
1687
Ady Abrahambe0f9482019-04-24 15:41:53 -07001688bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1689 // We are storing the last 2 present fences. If sf's phase offset is to be
1690 // woken up before the actual vsync but targeting the next vsync, we need to check
1691 // fence N-2
1692 const sp<Fence>& fence =
1693 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1694 ? mPreviousPresentFences[0]
1695 : mPreviousPresentFences[1];
1696
1697 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1698}
1699
Ady Abraham7c03ce62019-07-19 10:59:45 -07001700void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
Alec Mouriaa614192019-06-06 13:28:34 -07001701 DisplayStatInfo stats;
1702 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001703 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001704 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham7c03ce62019-07-19 10:59:45 -07001705 mExpectedPresentTime =
Alec Mouriaa614192019-06-06 13:28:34 -07001706 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1707 ? presentTime
1708 : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001709}
1710
Dominik Laskowski22488f62019-03-28 09:53:04 -07001711void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001712 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001713 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001714 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001715 // calculate the expected present time once and use the cached
1716 // value throughout this frame to make sure all layers are
1717 // seeing this same value.
1718 populateExpectedPresentTime();
1719
Ady Abrahambe0f9482019-04-24 15:41:53 -07001720 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001721 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1722 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1723 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1724 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1725 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1726 if (frameMissed) {
1727 mFrameMissedCount++;
1728 mTimeStats->incrementMissedFrames();
1729 }
1730
Alec Mouri40189b02019-03-05 15:07:54 -08001731 if (hwcFrameMissed) {
1732 mHwcFrameMissedCount++;
1733 }
1734
1735 if (gpuFrameMissed) {
1736 mGpuFrameMissedCount++;
1737 }
1738
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001739 if (mUseSmart90ForVideo) {
1740 // This call is made each time SF wakes up and creates a new frame. It is part
1741 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001742 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001743 }
1744
Ady Abrahamb838aed2019-02-12 15:30:16 -08001745 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001746 break;
1747 }
1748
Ady Abraham4658e112019-07-22 13:07:26 -07001749 if (frameMissed && mPropagateBackpressure) {
1750 if ((hwcFrameMissed && !gpuFrameMissed) ||
1751 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001752 signalLayerUpdate();
1753 break;
1754 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001755 }
Dan Stoza50182882016-07-08 12:02:20 -07001756
Steven Thomas050b2c82017-03-06 11:45:16 -08001757 // Now that we're going to make it to the handleMessageTransaction()
1758 // call below it's safe to call updateVrFlinger(), which will
1759 // potentially trigger a display handoff.
1760 updateVrFlinger();
1761
Dan Stoza6b9454d2014-11-07 16:00:59 -08001762 bool refreshNeeded = handleMessageTransaction();
1763 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001764
1765 updateCursorAsync();
1766 updateInputFlinger();
1767
Dan Stoza58784442014-12-02 16:58:17 -08001768 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001769 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001770 // Signal a refresh if a transaction modified the window state,
1771 // a new buffer was latched, or if HWC has requested a full
1772 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001773 signalRefresh();
1774 }
1775 break;
1776 }
1777 case MessageQueue::REFRESH: {
1778 handleMessageRefresh();
1779 break;
1780 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001781 }
1782}
1783
Dan Stoza6b9454d2014-11-07 16:00:59 -08001784bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001785 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001786 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001787
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001788 bool flushedATransaction = flushTransactionQueues();
1789
1790 bool runHandleTransaction = transactionFlags &&
1791 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1792
1793 if (runHandleTransaction) {
1794 handleTransaction(eTransactionMask);
1795 } else {
1796 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001797 }
1798
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001799 if (transactionFlushNeeded()) {
1800 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001801 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001802
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001803 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001804}
1805
Mathias Agopian4fec8732012-06-29 14:12:52 -07001806void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001808
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001809 mRefreshPending = false;
1810
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001811 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001812 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001813 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001814 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001815 for (const auto& [token, display] : mDisplays) {
1816 beginFrame(display);
1817 prepareFrame(display);
1818 doDebugFlashRegions(display, repaintEverything);
1819 doComposition(display, repaintEverything);
1820 }
1821
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001822 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001823
1824 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001825 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001826
Dan Stozabfbffeb2016-07-21 14:49:33 -07001827 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001828 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001829 for (const auto& [token, displayDevice] : mDisplays) {
1830 auto display = displayDevice->getCompositionDisplay();
1831 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001832 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001833 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001834 mHadDeviceComposition =
1835 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001836 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001837
Jorim Jaggi90535212018-05-23 23:44:06 +02001838 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001839
David Sodman7e4ae112018-02-09 15:02:28 -08001840 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001841 if (mVisibleRegionsDirty) {
1842 mVisibleRegionsDirty = false;
1843 if (mTracingEnabled) {
1844 mTracing.notify("visibleRegionsDirty");
1845 }
1846 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001847}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001848
David Sodmanfa9b2af2017-12-24 13:28:59 -08001849
1850bool SurfaceFlinger::handleMessageInvalidate() {
1851 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001852 bool refreshNeeded = handlePageFlip();
1853
Vishnu Nair4351ad52019-02-11 14:13:02 -08001854 if (mVisibleRegionsDirty) {
1855 computeLayerBounds();
1856 }
1857
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001858 for (auto& layer : mLayersPendingRefresh) {
1859 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001860 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001861 invalidateLayerStack(layer, visibleReg);
1862 }
1863 mLayersPendingRefresh.clear();
1864 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001865}
1866
David Sodman79bba0e2018-08-05 18:07:49 -07001867void SurfaceFlinger::calculateWorkingSet() {
1868 ATRACE_CALL();
1869 ALOGV(__FUNCTION__);
1870
David Sodman79bba0e2018-08-05 18:07:49 -07001871 // build the h/w work list
1872 if (CC_UNLIKELY(mGeometryInvalid)) {
1873 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001874 for (const auto& [token, displayDevice] : mDisplays) {
1875 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001876
Lloyd Piquea83776c2019-01-29 18:42:32 -08001877 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001878
Lloyd Piquea83776c2019-01-29 18:42:32 -08001879 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1880 auto& compositionState = layer->editState();
1881 compositionState.forceClientComposition = false;
1882 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1883 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001884 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001885
Lloyd Piquea83776c2019-01-29 18:42:32 -08001886 // The output Z order is set here based on a simple counter.
1887 compositionState.z = zOrder++;
1888
1889 // Update the display independent composition state. This goes
1890 // to the general composition layer state structure.
1891 // TODO: Do this once per compositionengine::CompositionLayer.
1892 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1893 true);
1894
1895 // Recalculate the geometry state of the output layer.
1896 layer->updateCompositionState(true);
1897
1898 // Write the updated geometry state to the HWC
1899 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001900 }
1901 }
1902 }
1903
1904 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001905 for (const auto& [token, displayDevice] : mDisplays) {
1906 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001907 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001908 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001909 continue;
1910 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001911 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001912
1913 if (mDrawingState.colorMatrixChanged) {
1914 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001915 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001916 Dataspace targetDataspace = Dataspace::UNKNOWN;
1917 if (useColorManagement) {
1918 ColorMode colorMode;
1919 RenderIntent renderIntent;
1920 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1921 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001922
1923 if (isHdrColorMode(colorMode)) {
1924 targetDataspace = Dataspace::UNKNOWN;
1925 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1926 targetDataspace = mColorSpaceAgnosticDataspace;
1927 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001928 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001929
Lloyd Pique32cbe282018-10-19 13:09:22 -07001930 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001931 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001932 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001933 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1934 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001935 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001936 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001937 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1938 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001939 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001940 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001941 }
1942
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001943 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001944 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001945 }
1946
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001947 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001948 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001949 layer->setCompositionType(displayDevice,
1950 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001951 continue;
1952 }
1953
Lloyd Pique32cbe282018-10-19 13:09:22 -07001954 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001955 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001956 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001957 }
1958 }
1959
1960 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001961
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001962 for (const auto& [token, displayDevice] : mDisplays) {
1963 auto display = displayDevice->getCompositionDisplay();
1964 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001965 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1966 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1967 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001968 }
1969 }
David Sodman79bba0e2018-08-05 18:07:49 -07001970}
1971
Lloyd Pique32cbe282018-10-19 13:09:22 -07001972void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1973 bool repaintEverything) {
1974 auto display = displayDevice->getCompositionDisplay();
1975 const auto& displayState = display->getState();
1976
Mathias Agopiancd60f992012-08-16 16:28:27 -07001977 // is debugging enabled
1978 if (CC_LIKELY(!mDebugRegion))
1979 return;
1980
Lloyd Pique32cbe282018-10-19 13:09:22 -07001981 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001982 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001983 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001984 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001985 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001986 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001987 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001989 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001990 }
1991 }
1992
Lloyd Pique32cbe282018-10-19 13:09:22 -07001993 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994
1995 if (mDebugRegion > 1) {
1996 usleep(mDebugRegion * 1000);
1997 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001998
Lloyd Pique32cbe282018-10-19 13:09:22 -07001999 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002000}
2001
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002002void SurfaceFlinger::logLayerStats() {
2003 ATRACE_CALL();
2004 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002005 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002006 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002007 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002008 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002009 }
2010 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002011
2012 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002013 }
2014}
2015
David Sodman2b406362017-12-15 13:33:47 -08002016void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002017{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002018 ATRACE_CALL();
2019 ALOGV("preComposition");
2020
David Sodman2b406362017-12-15 13:33:47 -08002021 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2022
Mathias Agopiancd60f992012-08-16 16:28:27 -07002023 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002024 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002025 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002026 needExtraInvalidate = true;
2027 }
Robert Carr2047fae2016-11-28 14:09:09 -08002028 });
2029
Mathias Agopiancd60f992012-08-16 16:28:27 -07002030 if (needExtraInvalidate) {
2031 signalLayerUpdate();
2032 }
2033}
2034
Ana Krulece588e312018-09-18 12:32:24 -07002035void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2036 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002037 // Update queue of past composite+present times and determine the
2038 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002039 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002040 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002041 while (!getBE().mCompositePresentTimes.empty()) {
2042 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002043 // Cached values should have been updated before calling this method,
2044 // which helps avoid duplicate syscalls.
2045 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2046 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2047 break;
2048 }
2049 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002050 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 }
2052
2053 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002054 while (getBE().mCompositePresentTimes.size() > 16) {
2055 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002056 }
2057
Ana Krulece588e312018-09-18 12:32:24 -07002058 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002059}
2060
Ana Krulece588e312018-09-18 12:32:24 -07002061void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2062 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063 // Integer division and modulo round toward 0 not -inf, so we need to
2064 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002065 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2066 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2067 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002068
Ana Krulec757f63a2019-01-25 10:46:18 -08002069 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002070 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002071 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002072 }
2073
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002074 // Snap the latency to a value that removes scheduling jitter from the
2075 // composition and present times, which often have >1ms of jitter.
2076 // Reducing jitter is important if an app attempts to extrapolate
2077 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002078 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002079 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002080 nsecs_t bias = stats.vsyncPeriod / 2;
2081 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2082 nsecs_t snappedCompositeToPresentLatency =
2083 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002084
David Sodman99974d22017-11-28 12:04:33 -08002085 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002086 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2087 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002088 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089}
2090
David Sodman2b406362017-12-15 13:33:47 -08002091void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002092{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002093 ATRACE_CALL();
2094 ALOGV("postComposition");
2095
Brian Anderson3546a3f2016-07-14 11:51:14 -07002096 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002097 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002098 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002099 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002100 }
2101
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002102 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002103 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002104
David Sodman73beded2017-11-15 11:56:06 -08002105 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002106 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002107 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002108 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002109 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2110 ->getRenderSurface()
2111 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002112 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002113 } else {
2114 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2115 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002116
David Sodman73beded2017-11-15 11:56:06 -08002117 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002118 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2119 mPreviousPresentFences[0] = displayDevice
2120 ? getHwComposer().getPresentFence(*displayDevice->getId())
2121 : Fence::NO_FENCE;
2122 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002123 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002124
Ana Krulece588e312018-09-18 12:32:24 -07002125 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002126 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002127
David Sodman2b406362017-12-15 13:33:47 -08002128 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002129 // when we started doing work for this frame, but that should be okay
2130 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002131 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002132 CompositorTiming compositorTiming;
2133 {
David Sodman99974d22017-11-28 12:04:33 -08002134 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2135 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002136 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002137
Robert Carr2047fae2016-11-28 14:09:09 -08002138 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002139 bool frameLatched =
2140 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2141 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002142 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002143 recordBufferingStats(layer->getName().string(),
2144 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002145 }
Robert Carr2047fae2016-11-28 14:09:09 -08002146 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002147
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002148 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002149 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002150 }
2151
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002152 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002153 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2154 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002155 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002156 }
2157 }
2158
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002159 if (mAnimCompositionPending) {
2160 mAnimCompositionPending = false;
2161
Brian Anderson4e606e32017-03-16 15:34:57 -07002162 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002163 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002164 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002165 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002166 // The HWC doesn't support present fences, so use the refresh
2167 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002168 const nsecs_t presentTime =
2169 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002170 mAnimFrameTracker.setActualPresentTime(presentTime);
2171 }
2172 mAnimFrameTracker.advanceFrame();
2173 }
Dan Stozab90cf072015-03-05 11:05:59 -08002174
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002175 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002176 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002177 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002178 }
2179
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002180 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002181
Lloyd Pique32cbe282018-10-19 13:09:22 -07002182 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2183 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002184 return;
2185 }
2186
2187 nsecs_t currentTime = systemTime();
2188 if (mHasPoweredOff) {
2189 mHasPoweredOff = false;
2190 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002191 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002192 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002193 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2194 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002195 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002196 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002197 }
David Sodman4a36e932017-11-07 14:29:47 -08002198 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002199 }
David Sodman4a36e932017-11-07 14:29:47 -08002200 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002201
2202 {
2203 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002204 if (mTexturePool.size() < mTexturePoolSize) {
2205 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002206 const size_t offset = mTexturePool.size();
2207 mTexturePool.resize(mTexturePoolSize);
2208 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2209 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002210 } else if (mTexturePool.size() > mTexturePoolSize) {
2211 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2212 const size_t offset = mTexturePoolSize;
2213 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2214 mTexturePool.resize(mTexturePoolSize);
2215 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002216 }
2217 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002218
Ady Abrahambe0f9482019-04-24 15:41:53 -07002219 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002220 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002221
Kevin DuBois413287f2019-02-25 08:46:47 -08002222 if (mLumaSampling && mRegionSamplingThread) {
2223 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002224 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002225
2226 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2227 // side-effect of getTotalSize(), so we check that again here
2228 if (ATRACE_ENABLED()) {
2229 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2230 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002231}
2232
Vishnu Nair4351ad52019-02-11 14:13:02 -08002233void SurfaceFlinger::computeLayerBounds() {
2234 for (const auto& pair : mDisplays) {
2235 const auto& displayDevice = pair.second;
2236 const auto display = displayDevice->getCompositionDisplay();
2237 for (const auto& layer : mDrawingState.layersSortedByZ) {
2238 // only consider the layers on the given layer stack
2239 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002240 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002241 }
2242
2243 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2244 }
2245 }
2246}
2247
Mathias Agopiancd60f992012-08-16 16:28:27 -07002248void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 ATRACE_CALL();
2250 ALOGV("rebuildLayerStacks");
2251
Mathias Agopiancd60f992012-08-16 16:28:27 -07002252 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002253 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002254 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002255 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002256
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002257 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 const auto& displayDevice = pair.second;
2259 auto display = displayDevice->getCompositionDisplay();
2260 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002261 Region opaqueRegion;
2262 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002263 compositionengine::Output::OutputLayers layersSortedByZ;
2264 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002265 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002266 const ui::Transform& tr = displayState.transform;
2267 const Rect bounds = displayState.bounds;
2268 if (displayState.isEnabled) {
2269 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270
Jeff Sharkey76488112017-02-27 14:15:18 -07002271 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002272 auto compositionLayer = layer->getCompositionLayer();
2273 if (compositionLayer == nullptr) {
2274 return;
2275 }
2276
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002278 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2279 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2280
Lloyd Pique07e33212018-12-18 16:33:37 -08002281 bool needsOutputLayer = false;
2282
Lloyd Piqueef36b002019-01-23 17:52:04 -08002283 if (display->belongsInOutput(layer->getLayerStack(),
2284 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002285 Region drawRegion(tr.transform(
2286 layer->visibleNonTransparentRegion));
2287 drawRegion.andSelf(bounds);
2288 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002289 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002290 }
Chia-I Wu83806892017-11-16 10:50:20 -08002291 }
2292
Lloyd Pique07e33212018-12-18 16:33:37 -08002293 if (needsOutputLayer) {
2294 layersSortedByZ.emplace_back(
2295 display->getOrCreateOutputLayer(displayId, compositionLayer,
2296 layerFE));
2297 deprecated_layersSortedByZ.add(layer);
2298
2299 auto& outputLayerState = layersSortedByZ.back()->editState();
2300 outputLayerState.visibleRegion =
2301 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2302 } else if (displayId) {
2303 // For layers that are being removed from a HWC display,
2304 // and that have queued frames, add them to a a list of
2305 // released layers so we can properly set a fence.
2306 bool hasExistingOutputLayer =
2307 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2308 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2309 mLayersWithQueuedFrames.cend(),
2310 layer) != mLayersWithQueuedFrames.cend();
2311
2312 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002313 layersNeedingFences.add(layer);
2314 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002315 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002316 });
2317 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002318
2319 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2320
2321 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002322 displayDevice->setLayersNeedingFences(layersNeedingFences);
2323
2324 Region undefinedRegion{bounds};
2325 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2326
2327 display->editState().undefinedRegion = undefinedRegion;
2328 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002329 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002330 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002331}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002332
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002333// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002334// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002335// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002336// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002337// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338// The returned HDR data space is one of
2339// - Dataspace::UNKNOWN
2340// - Dataspace::BT2020_HLG
2341// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002342Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2343 Dataspace* outHdrDataSpace,
2344 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002345 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002346 *outHdrDataSpace = Dataspace::UNKNOWN;
2347
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002348 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002349 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002350 case Dataspace::V0_SCRGB:
2351 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002352 case Dataspace::BT2020:
2353 case Dataspace::BT2020_ITU:
2354 case Dataspace::BT2020_LINEAR:
2355 case Dataspace::DISPLAY_BT2020:
2356 bestDataSpace = Dataspace::DISPLAY_BT2020;
2357 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002358 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002359 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002361 case Dataspace::BT2020_PQ:
2362 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002363 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002364 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002365 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002366 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002367 case Dataspace::BT2020_HLG:
2368 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002369 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002370 // When there's mixed PQ content and HLG content, we set the HDR
2371 // data space to be BT2020_PQ and convert HLG to PQ.
2372 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2373 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002374 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002375 break;
2376 default:
2377 break;
2378 }
Romain Guy54f154a2017-10-24 21:40:32 +01002379 }
2380
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002382}
2383
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002384// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2386 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2388 *outMode = ColorMode::NATIVE;
2389 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002390 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002391 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002392 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002393
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002394 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002395 bool isHdrClientComposition = false;
2396 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002397
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002398 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2399
Peiyong Lina3ea5592019-02-10 14:45:00 -08002400 switch (mForceColorMode) {
2401 case ColorMode::SRGB:
2402 bestDataSpace = Dataspace::V0_SRGB;
2403 break;
2404 case ColorMode::DISPLAY_P3:
2405 bestDataSpace = Dataspace::DISPLAY_P3;
2406 break;
2407 default:
2408 break;
2409 }
2410
Peiyong Lindfde5112018-06-05 10:58:41 -07002411 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002412 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2413 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002414 if (isHdr) {
2415 bestDataSpace = hdrDataSpace;
2416 }
2417
Chia-I Wu0d711262018-05-21 15:19:35 -07002418 RenderIntent intent;
2419 switch (mDisplayColorSetting) {
2420 case DisplayColorSetting::MANAGED:
2421 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002422 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002423 break;
2424 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002425 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002426 break;
2427 default: // vendor display color setting
2428 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2429 break;
2430 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002431
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002432 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002433}
2434
Lloyd Pique32cbe282018-10-19 13:09:22 -07002435void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2436 auto display = displayDevice->getCompositionDisplay();
2437 const auto& displayState = display->getState();
2438
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002439 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2441 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002442
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 // If nothing has changed (!dirty), don't recompose.
2444 // If something changed, but we don't currently have any visible layers,
2445 // and didn't when we last did a composition, then skip it this time.
2446 // The second rule does two things:
2447 // - When all layers are removed from a display, we'll emit one black
2448 // frame, then nothing more until we get new layers.
2449 // - When a display is created with a private layer stack, we won't
2450 // emit any black frames until a layer is added to the layer stack.
2451 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002452
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 const char flagPrefix[] = {'-', '+'};
2454 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002455 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2456 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2457 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2458 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002459
Lloyd Pique31cb2942018-10-19 17:23:03 -07002460 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002461
David Sodmanfa9b2af2017-12-24 13:28:59 -08002462 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002464 }
2465}
2466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2468 auto display = displayDevice->getCompositionDisplay();
2469 const auto& displayState = display->getState();
2470
2471 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002472 return;
David Sodman2b406362017-12-15 13:33:47 -08002473 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002474
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002475 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002477 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002478}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002479
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002481 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002482 ALOGV("doComposition");
2483
Lloyd Pique32cbe282018-10-19 13:09:22 -07002484 auto display = displayDevice->getCompositionDisplay();
2485 const auto& displayState = display->getState();
2486
2487 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002488 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002489 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002490
David Sodmanfa9b2af2017-12-24 13:28:59 -08002491 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002492 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002493
Lloyd Pique32cbe282018-10-19 13:09:22 -07002494 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002495 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002496 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002497 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002498}
2499
David Sodmanfa9b2af2017-12-24 13:28:59 -08002500void SurfaceFlinger::postFrame()
2501{
2502 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002503 const auto display = getDefaultDisplayDeviceLocked();
2504 if (display && getHwComposer().isConnected(*display->getId())) {
2505 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002506 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2507 logFrameStats();
2508 }
2509 }
2510}
2511
Lloyd Pique32cbe282018-10-19 13:09:22 -07002512void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002513 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002514 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002515
Lloyd Pique32cbe282018-10-19 13:09:22 -07002516 auto display = displayDevice->getCompositionDisplay();
2517 const auto& displayState = display->getState();
2518 const auto displayId = display->getId();
2519
Lloyd Pique32cbe282018-10-19 13:09:22 -07002520 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002521 if (displayId) {
2522 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002523 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002524 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002525 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002526 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002527 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002528
Chia-I Wu7b549592017-11-15 09:14:57 -08002529 // The layer buffer from the previous frame (if any) is released
2530 // by HWC only when the release fence from this frame (if any) is
2531 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002532 if (layer->getState().hwc) {
2533 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002534 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002535 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2536 usedClientComposition =
2537 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002538 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002539
2540 // If the layer was client composited in the previous frame, we
2541 // need to merge with the previous client target acquire fence.
2542 // Since we do not track that, always merge with the current
2543 // client target acquire fence when it is available, even though
2544 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002545 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002546 releaseFence =
2547 Fence::merge("LayerRelease", releaseFence,
2548 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002549 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002550
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002551 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002552 }
Chia-I Wu83806892017-11-16 10:50:20 -08002553
2554 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002555 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002556 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002557 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002559 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002560 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002561 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002562 }
2563 }
2564
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 if (displayId) {
2566 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002567 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002568 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002569}
2570
Mathias Agopian87baae12012-07-31 12:38:26 -07002571void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572{
Mathias Agopian841cde52012-03-01 15:44:37 -08002573 ATRACE_CALL();
2574
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002575 // here we keep a copy of the drawing state (that is the state that's
2576 // going to be overwritten by handleTransactionLocked()) outside of
2577 // mStateLock so that the side-effects of the State assignment
2578 // don't happen with mStateLock held (which can cause deadlocks).
2579 State drawingState(mDrawingState);
2580
Mathias Agopianca4d3602011-05-19 15:38:14 -07002581 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002582 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002583
Mathias Agopianca4d3602011-05-19 15:38:14 -07002584 // Here we're guaranteed that some transaction flags are set
2585 // so we can call handleTransactionLocked() unconditionally.
2586 // We call getTransactionFlags(), which will also clear the flags,
2587 // with mStateLock held to guarantee that mCurrentState won't change
2588 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002589
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002590 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002591 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002592 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002593
Mathias Agopianca4d3602011-05-19 15:38:14 -07002594 mDebugInTransaction = 0;
2595 invalidateHwcGeometry();
2596 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002597}
2598
Lloyd Piqueba04e622017-12-14 17:11:26 -08002599void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2600 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 const std::optional<DisplayIdentificationInfo> info =
2602 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002603
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002605 continue;
2606 }
2607
Lloyd Piqueba04e622017-12-14 17:11:26 -08002608 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002610 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 mPhysicalDisplayTokens[info->id] = new BBinder();
2612 DisplayDeviceState state;
2613 state.displayId = info->id;
2614 state.isSecure = true; // All physical displays are currently considered secure.
2615 state.displayName = info->name;
2616 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2617 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002618 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002619 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002620 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002621
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2623 if (index >= 0) {
2624 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2625 mInterceptor->saveDisplayDeletion(state.sequenceId);
2626 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002627 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002628 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002629 }
2630
2631 processDisplayChangesLocked();
2632 }
2633
2634 mPendingHotplugEvents.clear();
2635}
2636
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002637void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002638 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2639 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002640}
2641
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002644 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002645 const sp<IGraphicBufferProducer>& producer) {
2646 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002647 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002648 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002649 creationArgs.isSecure = state.isSecure;
2650 creationArgs.displaySurface = dispSurface;
2651 creationArgs.hasWideColorGamut = false;
2652 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002653
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002654 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002655 creationArgs.isPrimary = isInternalDisplay;
2656
2657 if (useColorManagement && displayId) {
2658 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002660 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002661 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002663
Dominik Laskowski7e045462018-05-30 13:02:02 -07002664 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002665 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002666 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 }
tangrobin6753a022018-08-10 10:58:54 +08002668 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002669
Dominik Laskowski075d3172018-05-24 15:50:06 -07002670 if (displayId) {
2671 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002672 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002673 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002674 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675
Lloyd Pique90c115d2018-09-18 21:39:42 -07002676 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002678 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680 // Make sure that composition can never be stalled by a virtual display
2681 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002682 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002683 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002684 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2685 }
2686
Dominik Laskowski075d3172018-05-24 15:50:06 -07002687 creationArgs.displayInstallOrientation =
2688 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002689
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002691 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002692
Lloyd Pique90c115d2018-09-18 21:39:42 -07002693 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002694
2695 if (maxFrameBufferAcquiredBuffers >= 3) {
2696 nativeWindowSurface->preallocateBuffers();
2697 }
2698
2699 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002700 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002701 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002703 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002704 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002705 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2706 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002707 if (!state.isVirtual()) {
2708 LOG_ALWAYS_FATAL_IF(!displayId);
2709 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002710 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 display->setLayerStack(state.layerStack);
2713 display->setProjection(state.orientation, state.viewport, state.frame);
2714 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002716 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002717}
2718
Lloyd Pique347200f2017-12-14 17:00:15 -08002719void SurfaceFlinger::processDisplayChangesLocked() {
2720 // here we take advantage of Vector's copy-on-write semantics to
2721 // improve performance by skipping the transaction entirely when
2722 // know that the lists are identical
2723 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2724 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2725 if (!curr.isIdenticalTo(draw)) {
2726 mVisibleRegionsDirty = true;
2727 const size_t cc = curr.size();
2728 size_t dc = draw.size();
2729
2730 // find the displays that were removed
2731 // (ie: in drawing state but not in current state)
2732 // also handle displays that changed
2733 // (ie: displays that are in both lists)
2734 for (size_t i = 0; i < dc;) {
2735 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2736 if (j < 0) {
2737 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002738 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002739 // Save display ID before disconnecting.
2740 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002741 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002742
2743 if (!display->isVirtual()) {
2744 LOG_ALWAYS_FATAL_IF(!displayId);
2745 dispatchDisplayHotplugEvent(displayId->value, false);
2746 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002747 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002748
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002749 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 } else {
2751 // this display is in both lists. see if something changed.
2752 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002753 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2755 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2756 if (state_binder != draw_binder) {
2757 // changing the surface is like destroying and
2758 // recreating the DisplayDevice, so we just remove it
2759 // from the drawing state, so that it get re-added
2760 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002761 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002762 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002763 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002764 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 mDrawingState.displays.removeItemsAt(i);
2766 dc--;
2767 // at this point we must loop to the next item
2768 continue;
2769 }
2770
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002771 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002773 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 }
2775 if ((state.orientation != draw[i].orientation) ||
2776 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002777 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002778 }
2779 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002780 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 }
2782 }
2783 }
2784 ++i;
2785 }
2786
2787 // find displays that were added
2788 // (ie: in current state but not in drawing state)
2789 for (size_t i = 0; i < cc; i++) {
2790 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2791 const DisplayDeviceState& state(curr[i]);
2792
Lloyd Pique542307f2018-10-19 13:24:08 -07002793 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 sp<IGraphicBufferProducer> producer;
2795 sp<IGraphicBufferProducer> bqProducer;
2796 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002797 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002798
Dominik Laskowski075d3172018-05-24 15:50:06 -07002799 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002800 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002801 // Virtual displays without a surface are dormant:
2802 // they have external state (layer stack, projection,
2803 // etc.) but no internal state (i.e. a DisplayDevice).
2804 if (state.surface != nullptr) {
2805 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002806 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 int width = 0;
2808 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2809 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2810 int height = 0;
2811 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2812 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2813 int intFormat = 0;
2814 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2815 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002816 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002817
Dominik Laskowski075d3172018-05-24 15:50:06 -07002818 displayId =
2819 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002820 }
2821
2822 // TODO: Plumb requested format back up to consumer
2823
2824 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002825 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002826 bqProducer, bqConsumer,
2827 state.displayName);
2828
2829 dispSurface = vds;
2830 producer = vds;
2831 }
2832 } else {
2833 ALOGE_IF(state.surface != nullptr,
2834 "adding a supported display, but rendering "
2835 "surface is provided (%p), ignoring it",
2836 state.surface.get());
2837
Dominik Laskowski075d3172018-05-24 15:50:06 -07002838 displayId = state.displayId;
2839 LOG_ALWAYS_FATAL_IF(!displayId);
2840 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 producer = bqProducer;
2842 }
2843
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002844 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002845 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002846 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002847 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002849 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002850 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002851 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002852 }
2853 }
2854 }
2855 }
2856 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002857
2858 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002859}
2860
Mathias Agopian87baae12012-07-31 12:38:26 -07002861void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002862{
Dan Stoza7dde5992015-05-22 09:51:44 -07002863 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002864 mCurrentState.traverseInZOrder([](Layer* layer) {
2865 layer->notifyAvailableFrames();
2866 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002868 /*
2869 * Traversal of the children
2870 * (perform the transaction for each of them if needed)
2871 */
2872
Marissa Wall06255332019-03-27 13:48:27 -07002873 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002874 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002875 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002876 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877
2878 const uint32_t flags = layer->doTransaction(0);
2879 if (flags & Layer::eVisibleRegion)
2880 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002881
2882 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002883 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002884 }
Robert Carr2047fae2016-11-28 14:09:09 -08002885 });
Marissa Wall06255332019-03-27 13:48:27 -07002886 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 }
2888
2889 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002890 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 */
2892
Mathias Agopiane57f2922012-08-09 16:29:12 -07002893 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002894 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002895 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002896 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002898 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002899 // The transform hint might have changed for some layers
2900 // (either because a display has changed, or because a layer
2901 // as changed).
2902 //
2903 // Walk through all the layers in currentLayers,
2904 // and update their transform hint.
2905 //
2906 // If a layer is visible only on a single display, then that
2907 // display is used to calculate the hint, otherwise we use the
2908 // default display.
2909 //
2910 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2911 // the hint is set before we acquire a buffer from the surface texture.
2912 //
2913 // NOTE: layer transactions have taken place already, so we use their
2914 // drawing state. However, SurfaceFlinger's own transaction has not
2915 // happened yet, so we must use the current state layer list
2916 // (soon to become the drawing state list).
2917 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002918 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002919 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002920 bool first = true;
2921 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002922 // NOTE: we rely on the fact that layers are sorted by
2923 // layerStack first (so we don't have to traverse the list
2924 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002926 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002927 currentlayerStack = layerStack;
2928 // figure out if this layerstack is mirrored
2929 // (more than one display) if so, pick the default display,
2930 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002931 hintDisplay = nullptr;
2932 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002933 if (display->getCompositionDisplay()
2934 ->belongsInOutput(layer->getLayerStack(),
2935 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 if (hintDisplay) {
2937 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002938 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002939 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002940 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002941 }
2942 }
2943 }
2944 }
Chet Haase91d25932013-04-11 15:24:55 -07002945
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002946 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002947 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2948 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002949
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002950 // could be null when this layer is using a layerStack
2951 // that is not visible on any display. Also can occur at
2952 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002953 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002954 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002955
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002956 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002957 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002958 if (hintDisplay) {
2959 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002960 }
Robert Carr2047fae2016-11-28 14:09:09 -08002961
2962 first = false;
2963 });
Mathias Agopian84300952012-11-21 16:02:13 -08002964 }
2965
2966
Mathias Agopian3559b072012-08-15 13:46:03 -07002967 /*
2968 * Perform our own transaction if needed
2969 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002970
2971 if (mLayersAdded) {
2972 mLayersAdded = false;
2973 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002974 mVisibleRegionsDirty = true;
2975 }
2976
2977 // some layers might have been removed, so
2978 // we need to update the regions they're exposing.
2979 if (mLayersRemoved) {
2980 mLayersRemoved = false;
2981 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002982 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002983 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002984 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002985 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002986 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002987 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002988 }
Robert Carr2047fae2016-11-28 14:09:09 -08002989 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990 }
2991
Vishnu Nairec0ab382019-02-13 15:32:56 -08002992 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002993 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002994}
2995
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002996void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002997 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002998 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002999 return;
3000 }
3001
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003002 if (mVisibleRegionsDirty || mInputInfoChanged) {
3003 mInputInfoChanged = false;
3004 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08003005 } else if (mInputWindowCommands.syncInputWindows) {
3006 // If the caller requested to sync input windows, but there are no
3007 // changes to input windows, notify immediately.
3008 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003009 }
3010
3011 executeInputWindowCommands();
3012}
3013
3014void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003015 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003016
3017 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3018 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003019 // When calculating the screen bounds we ignore the transparent region since it may
3020 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003021 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003022 }
3023 });
chaviw291d88a2019-02-14 10:33:58 -08003024
3025 mInputFlinger->setInputWindows(inputHandles,
3026 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3027 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003028}
3029
Vishnu Nairec0ab382019-02-13 15:32:56 -08003030void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003031 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003032 mPendingInputWindowCommands.clear();
3033}
3034
chaviwfbe5d9c2018-12-26 12:23:37 -08003035void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003036 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3037 if (transferTouchFocusCommand.fromToken != nullptr &&
3038 transferTouchFocusCommand.toToken != nullptr &&
3039 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3040 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3041 transferTouchFocusCommand.toToken);
3042 }
3043 }
3044
3045 mInputWindowCommands.clear();
3046}
3047
Riley Andrews03414a12014-07-01 14:22:59 -07003048void SurfaceFlinger::updateCursorAsync()
3049{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003050 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003051 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003052 continue;
3053 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003055 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3056 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003057 }
3058 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059}
3060
chaviw61626f22018-11-15 16:26:27 -08003061void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3062 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003063 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003064 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003065 }
3066 layer->releasePendingBuffer(systemTime());
3067}
3068
Mathias Agopian4fec8732012-06-29 14:12:52 -07003069void SurfaceFlinger::commitTransaction()
3070{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003071 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003072 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003073 for (const auto& l : mLayersPendingRemoval) {
3074 recordBufferingStats(l->getName().string(),
3075 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003076
Lloyd Pique07e33212018-12-18 16:33:37 -08003077 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003078 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003079 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003080 }
chaviw74d90ad2019-04-26 14:45:26 -07003081
3082 // If the layer has been removed and has no parent, then it will not be reachable
3083 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3084 // ensure we can copy its current to drawing state.
3085 if (!l->getParent()) {
3086 mOffscreenLayers.emplace(l.get());
3087 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003088 }
3089 mLayersPendingRemoval.clear();
3090 }
3091
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003092 // If this transaction is part of a window animation then the next frame
3093 // we composite should be considered an animation as well.
3094 mAnimCompositionPending = mAnimTransactionPending;
3095
Nataniel Borges2b796da2019-02-15 13:32:18 -08003096 withTracingLock([&]() {
3097 mDrawingState = mCurrentState;
3098 // clear the "changed" flags in current state
3099 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003100
chaviw74d90ad2019-04-26 14:45:26 -07003101 mDrawingState.traverseInZOrder([&](Layer* layer) {
3102 layer->commitChildList();
3103
3104 // If the layer can be reached when traversing mDrawingState, then the layer is no
3105 // longer offscreen. Remove the layer from the offscreenLayer set.
3106 if (mOffscreenLayers.count(layer)) {
3107 mOffscreenLayers.erase(layer);
3108 }
3109 });
3110
3111 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003112 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003113
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003114 mTransactionPending = false;
3115 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003116 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117}
3118
Nataniel Borges2b796da2019-02-15 13:32:18 -08003119void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3120 if (mTracingEnabledChanged) {
3121 mTracingEnabled = mTracing.isEnabled();
3122 mTracingEnabledChanged = false;
3123 }
3124
3125 // Synchronize with Tracing thread
3126 std::unique_lock<std::mutex> lock;
3127 if (mTracingEnabled) {
3128 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3129 }
3130
3131 lockedOperation();
3132
3133 // Synchronize with Tracing thread
3134 if (mTracingEnabled) {
3135 lock.unlock();
3136 }
3137}
3138
chaviw74d90ad2019-04-26 14:45:26 -07003139void SurfaceFlinger::commitOffscreenLayers() {
3140 for (Layer* offscreenLayer : mOffscreenLayers) {
3141 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3142 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3143 if (!trFlags) return;
3144
3145 layer->doTransaction(0);
3146 layer->commitChildList();
3147 });
3148 }
3149}
3150
Lloyd Pique32cbe282018-10-19 13:09:22 -07003151void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003152 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003153 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003154 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003155
Lloyd Pique32cbe282018-10-19 13:09:22 -07003156 auto display = displayDevice->getCompositionDisplay();
3157
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 Region aboveOpaqueLayers;
3159 Region aboveCoveredLayers;
3160 Region dirty;
3161
Mathias Agopian87baae12012-07-31 12:38:26 -07003162 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163
Robert Carr2047fae2016-11-28 14:09:09 -08003164 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003165 // start with the whole surface at its current location
3166 const Layer::State& s(layer->getDrawingState());
3167
Jesse Hall01e29052013-02-19 16:13:35 -08003168 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003169 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003170 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003171 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003172
Mathias Agopianab028732010-03-16 16:41:46 -07003173 /*
3174 * opaqueRegion: area of a surface that is fully opaque.
3175 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003176 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003177
3178 /*
3179 * visibleRegion: area of a surface that is visible on screen
3180 * and not fully transparent. This is essentially the layer's
3181 * footprint minus the opaque regions above it.
3182 * Areas covered by a translucent surface are considered visible.
3183 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003185
3186 /*
3187 * coveredRegion: area of a surface that is covered by all
3188 * visible regions above it (which includes the translucent areas).
3189 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003190 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003191
Jesse Halla8026d22012-09-25 13:25:04 -07003192 /*
3193 * transparentRegion: area of a surface that is hinted to be completely
3194 * transparent. This is only used to tell when the layer has no visible
3195 * non-transparent regions and can be removed from the layer list. It
3196 * does not affect the visibleRegion of this layer or any layers
3197 * beneath it. The hint may not be correct if apps don't respect the
3198 * SurfaceView restrictions (which, sadly, some don't).
3199 */
3200 Region transparentRegion;
3201
Mathias Agopianab028732010-03-16 16:41:46 -07003202
3203 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003204 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003205 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003206 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003208 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003209 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003210 if (!visibleRegion.isEmpty()) {
3211 // Remove the transparent area from the visible region
3212 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003213 if (tr.preserveRects()) {
3214 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003215 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003216 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003217 // transformation too complex, can't do the
3218 // transparent region optimization.
3219 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003220 }
Mathias Agopianab028732010-03-16 16:41:46 -07003221 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222
Mathias Agopianab028732010-03-16 16:41:46 -07003223 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003224 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003225 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003226 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003227 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003228 // the opaque region is the layer's footprint
3229 opaqueRegion = visibleRegion;
3230 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231 }
3232 }
3233
Robert Carre5f4f692018-01-12 13:12:28 -08003234 if (visibleRegion.isEmpty()) {
3235 layer->clearVisibilityRegions();
3236 return;
3237 }
3238
Mathias Agopianab028732010-03-16 16:41:46 -07003239 // Clip the covered region to the visible region
3240 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3241
3242 // Update aboveCoveredLayers for next (lower) layer
3243 aboveCoveredLayers.orSelf(visibleRegion);
3244
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003245 // subtract the opaque region covered by the layers above us
3246 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247
3248 // compute this layer's dirty region
3249 if (layer->contentDirty) {
3250 // we need to invalidate the whole region
3251 dirty = visibleRegion;
3252 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003253 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 layer->contentDirty = false;
3255 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003256 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003257 * the exposed region consists of two components:
3258 * 1) what's VISIBLE now and was COVERED before
3259 * 2) what's EXPOSED now less what was EXPOSED before
3260 *
3261 * note that (1) is conservative, we start with the whole
3262 * visible region but only keep what used to be covered by
3263 * something -- which mean it may have been exposed.
3264 *
3265 * (2) handles areas that were not covered by anything but got
3266 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003267 */
Mathias Agopianab028732010-03-16 16:41:46 -07003268 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003269 const Region oldVisibleRegion = layer->visibleRegion;
3270 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003271 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3272 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 }
3274 dirty.subtractSelf(aboveOpaqueLayers);
3275
3276 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003277 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003278
Mathias Agopianab028732010-03-16 16:41:46 -07003279 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003281
Jesse Halla8026d22012-09-25 13:25:04 -07003282 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283 layer->setVisibleRegion(visibleRegion);
3284 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003285 layer->setVisibleNonTransparentRegion(
3286 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003287 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288
Mathias Agopian87baae12012-07-31 12:38:26 -07003289 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290}
3291
Chia-I Wuab0c3192017-08-01 11:29:00 -07003292void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003293 for (const auto& [token, displayDevice] : mDisplays) {
3294 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003295 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003296 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003297 }
3298 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003299}
3300
Dan Stoza6b9454d2014-11-07 16:00:59 -08003301bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003302{
Ady Abraham09bd3922019-04-08 10:44:56 -07003303 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003304 ALOGV("handlePageFlip");
3305
Brian Andersond6927fb2016-07-23 23:37:30 -07003306 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003307
Mathias Agopian4fec8732012-06-29 14:12:52 -07003308 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003309 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003310 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003311
3312 // Store the set of layers that need updates. This set must not change as
3313 // buffers are being latched, as this could result in a deadlock.
3314 // Example: Two producers share the same command stream and:
3315 // 1.) Layer 0 is latched
3316 // 2.) Layer 0 gets a new frame
3317 // 2.) Layer 1 gets a new frame
3318 // 3.) Layer 1 is latched.
3319 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3320 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003321 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003322 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003323 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003324 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003325 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003326 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003327 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003328 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003329 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003330 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003331 } else {
3332 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003333 }
Robert Carr2047fae2016-11-28 14:09:09 -08003334 });
3335
Lloyd Piquef2c79392018-12-20 16:23:33 -08003336 if (!mLayersWithQueuedFrames.empty()) {
3337 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3338 // writes to Layer current state. See also b/119481871
3339 Mutex::Autolock lock(mStateLock);
3340
3341 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003342 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003343 mLayersPendingRefresh.push_back(layer);
3344 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003345 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003346 if (layer->isBufferLatched()) {
3347 newDataLatched = true;
3348 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003349 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003350 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003351
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003352 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003353
3354 // If we will need to wake up at some time in the future to deal with a
3355 // queued frame that shouldn't be displayed during this vsync period, wake
3356 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003357 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003358 signalLayerUpdate();
3359 }
3360
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003361 // enter boot animation on first buffer latch
3362 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3363 ALOGI("Enter boot animation");
3364 mBootStage = BootStage::BOOTANIMATION;
3365 }
3366
Dan Stoza6b9454d2014-11-07 16:00:59 -08003367 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003368 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003369}
3370
Mathias Agopianad456f92011-01-13 17:53:01 -08003371void SurfaceFlinger::invalidateHwcGeometry()
3372{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003373 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003374}
3375
Lloyd Pique32cbe282018-10-19 13:09:22 -07003376void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003377 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003378 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003379 // We only need to actually compose the display if:
3380 // 1) It is being handled by hardware composer, which may need this to
3381 // keep its virtual display state machine in sync, or
3382 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003383 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003384 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003385 return;
3386 }
3387
Dan Stoza9e56aa02015-11-02 13:00:03 -08003388 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003389 base::unique_fd readyFence;
3390 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003391
3392 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003393 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003394}
3395
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003396bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3397 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003398 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003399 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003400
Lloyd Pique32cbe282018-10-19 13:09:22 -07003401 auto display = displayDevice->getCompositionDisplay();
3402 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003403 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003404 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003405 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003406
3407 const Region bounds(displayState.bounds);
3408 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003409 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003410 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003411
Chia-I Wu8e50e692018-05-04 10:12:37 -07003412 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003413
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003414 renderengine::DisplaySettings clientCompositionDisplay;
3415 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3416 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003417 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003418
Dan Stoza9e56aa02015-11-02 13:00:03 -08003419 if (hasClientComposition) {
3420 ALOGV("hasClientComposition");
3421
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003422 if (displayDevice->isPrimary() && supportProtectedContent) {
3423 bool needsProtected = false;
3424 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3425 // If the layer is a protected layer, mark protected context is needed.
3426 if (layer->isProtected()) {
3427 needsProtected = true;
3428 break;
3429 }
3430 }
Peiyong Lin52010312019-05-02 14:22:16 -07003431 if (needsProtected != renderEngine.isProtected()) {
3432 renderEngine.useProtectedContext(needsProtected);
3433 }
3434 if (needsProtected != display->getRenderSurface()->isProtected() &&
3435 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003436 display->getRenderSurface()->setProtected(needsProtected);
3437 }
3438 }
3439
Alec Mouri6338c9d2019-02-07 16:57:51 -08003440 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003441
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003442 if (buf == nullptr) {
3443 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3444 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003445 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003446 return false;
3447 }
3448
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003449 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3450 clientCompositionDisplay.clip = displayState.scissor;
3451 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003452 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003453 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003454
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003455 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003456 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003457 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003458 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003459 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003460 clientCompositionDisplay.outputDataspace = outputDataspace;
3461 clientCompositionDisplay.maxLuminance =
3462 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003463
Lloyd Pique441d5042018-10-18 16:49:51 -07003464 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003465 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003466 getHwComposer()
3467 .hasDisplayCapability(displayId,
3468 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003469
Peiyong Lind3788632018-09-18 16:01:31 -07003470 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003471 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3472 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003473 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003474 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003475 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003476
Mathias Agopian85d751c2012-08-29 16:59:24 -07003477 /*
3478 * and then, render the layers targeted at the framebuffer
3479 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003480
Dan Stoza9e56aa02015-11-02 13:00:03 -08003481 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003482 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003483 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003484 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003485 const Region viewportRegion(displayState.viewport);
3486 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003487 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003488 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003489 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003490 switch (layer->getCompositionType(displayDevice)) {
3491 case Hwc2::IComposerClient::Composition::CURSOR:
3492 case Hwc2::IComposerClient::Composition::DEVICE:
3493 case Hwc2::IComposerClient::Composition::SIDEBAND:
3494 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003495 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003496 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003497 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003498 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003499 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003500 // never clear the very first layer since we're
3501 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003502 renderengine::LayerSettings layerSettings;
3503 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003504 bool prepared =
3505 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3506 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003507
3508 if (prepared) {
3509 layerSettings.source.buffer.buffer = nullptr;
3510 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3511 layerSettings.alpha = half(0.0);
3512 layerSettings.disableBlending = true;
3513 clientCompositionLayers.push_back(layerSettings);
3514 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003515 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003516 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003517 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003518 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003519 renderengine::LayerSettings layerSettings;
3520 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003521 layer->prepareClientLayer(renderArea, clip, clearRegion,
3522 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003523 if (prepared) {
3524 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003525 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003526 break;
3527 }
3528 default:
3529 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003530 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003531 } else {
3532 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003533 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003534 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003535 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003536
Alec Mouri820c7402019-01-23 13:02:39 -08003537 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003538 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003539 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003540
3541 // We boost GPU frequency here because there will be color spaces conversion
3542 // and it's expensive. We boost the GPU frequency so that GPU composition can
3543 // finish in time. We must reset GPU frequency afterwards, because high frequency
3544 // consumes extra battery.
3545 const bool expensiveRenderingExpected =
3546 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3547 if (expensiveRenderingExpected && displayId) {
3548 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3549 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003550 if (!debugRegion.isEmpty()) {
3551 Region::const_iterator it = debugRegion.begin();
3552 Region::const_iterator end = debugRegion.end();
3553 while (it != end) {
3554 const Rect& rect = *it++;
3555 renderengine::LayerSettings layerSettings;
3556 layerSettings.source.buffer.buffer = nullptr;
3557 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3558 layerSettings.geometry.boundaries = rect.toFloatRect();
3559 layerSettings.alpha = half(1.0);
3560 clientCompositionLayers.push_back(layerSettings);
3561 }
3562 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003563 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003564 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3565 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003566 } else if (displayId) {
3567 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003568 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003569 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003570}
3571
Robert Carrc0df3122019-04-11 13:18:21 -07003572status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3573 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3574 const sp<IBinder>& parentHandle,
3575 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003576 // add this layer to the current state list
3577 {
3578 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003579 sp<Layer> parent;
3580 if (parentHandle != nullptr) {
3581 parent = fromHandle(parentHandle);
3582 if (parent == nullptr) {
3583 return NAME_NOT_FOUND;
3584 }
3585 } else {
3586 parent = parentLayer;
3587 }
3588
Robert Carr1f0a16a2016-10-24 16:27:39 -07003589 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003590 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3591 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003592 return NO_MEMORY;
3593 }
Robert Carrc0df3122019-04-11 13:18:21 -07003594
3595 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3596
Robert Carrb89ea9d2018-12-10 13:01:14 -08003597 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003598 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003599 } else if (parent == nullptr) {
3600 lbc->onRemovedFromCurrentState();
3601 } else if (parent->isRemovedFromCurrentState()) {
3602 parent->addChild(lbc);
3603 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003604 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003605 parent->addChild(lbc);
3606 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003607
Yiwei Zhang243b3782018-05-15 17:40:04 -07003608 if (gbc != nullptr) {
3609 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3610 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3611 mMaxGraphicBufferProducerListSize,
3612 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3613 mGraphicBufferProducerList.size(),
3614 mMaxGraphicBufferProducerListSize, mNumLayers);
3615 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003616 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003617 }
3618
Mathias Agopian96f08192010-06-02 23:28:45 -07003619 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003620 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003621
Dan Stoza7d89d062015-04-30 13:29:25 -07003622 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003623}
3624
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003625uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003626 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003627}
3628
Mathias Agopian3f844832013-08-07 21:24:32 -07003629uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003630 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003631}
3632
Mathias Agopian3f844832013-08-07 21:24:32 -07003633uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003634 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003635}
3636
3637uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003638 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003639 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003640 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003642 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 }
3644 return old;
3645}
3646
Marissa Wall713b63f2018-10-17 15:42:43 -07003647bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003648 // to prevent onHandleDestroyed from being called while the lock is held,
3649 // we must keep a copy of the transactions (specifically the composer
3650 // states) around outside the scope of the lock
3651 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003652 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003653 {
3654 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003655
Valerie Haufce31b82019-04-30 16:41:14 -07003656 auto it = mTransactionQueues.begin();
3657 while (it != mTransactionQueues.end()) {
3658 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003659
Valerie Haufce31b82019-04-30 16:41:14 -07003660 while (!transactionQueue.empty()) {
3661 const auto& transaction = transactionQueue.front();
3662 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3663 transaction.states)) {
3664 setTransactionFlags(eTransactionFlushNeeded);
3665 break;
3666 }
3667 transactions.push_back(transaction);
3668 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3669 mPendingInputWindowCommands, transaction.desiredPresentTime,
3670 transaction.buffer, transaction.callback,
3671 transaction.postTime, transaction.privileged,
3672 /*isMainThread*/ true);
3673 transactionQueue.pop();
3674 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003675 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003676
Valerie Haufce31b82019-04-30 16:41:14 -07003677 if (transactionQueue.empty()) {
3678 it = mTransactionQueues.erase(it);
3679 mTransactionCV.broadcast();
3680 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003681 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003682 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003683 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003684 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003685 return flushedATransaction;
3686}
3687
3688bool SurfaceFlinger::transactionFlushNeeded() {
3689 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003690}
3691
chaviwca27f252018-02-06 16:46:39 -08003692bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3693 for (const ComposerState& state : states) {
3694 // Here we need to check that the interface we're given is indeed
3695 // one of our own. A malicious client could give us a nullptr
3696 // IInterface, or one of its own or even one of our own but a
3697 // different type. All these situations would cause us to crash.
3698 if (state.client == nullptr) {
3699 return true;
3700 }
3701
3702 sp<IBinder> binder = IInterface::asBinder(state.client);
3703 if (binder == nullptr) {
3704 return true;
3705 }
3706
3707 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3708 return true;
3709 }
3710 }
3711 return false;
3712}
3713
Marissa Wall17b4e452018-12-26 16:32:34 -08003714bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3715 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003716 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003717 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3718 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3719 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3720 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3721 return false;
3722 }
3723
Marissa Wall713b63f2018-10-17 15:42:43 -07003724 for (const ComposerState& state : states) {
3725 const layer_state_t& s = state.state;
3726 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3727 continue;
3728 }
3729 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003730 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003731 }
3732 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003733 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003734}
3735
3736void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3737 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003738 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003739 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003740 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003741 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003742 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003743 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003744
Valerie Haubc6ddb12019-03-08 11:10:15 -08003745 const int64_t postTime = systemTime();
3746
Robert Carr14167e02019-02-13 13:50:55 -08003747 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3748
Mathias Agopian698c0872011-06-28 19:09:31 -07003749 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003750
chaviwca27f252018-02-06 16:46:39 -08003751 if (containsAnyInvalidClientState(states)) {
3752 return;
3753 }
3754
Marissa Wall713b63f2018-10-17 15:42:43 -07003755 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003756 auto itr = mTransactionQueues.find(applyToken);
3757 // if this is an animation frame, wait until prior animation frame has
3758 // been applied by SF
3759 if (flags & eAnimation) {
3760 while (itr != mTransactionQueues.end()) {
3761 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3762 if (CC_UNLIKELY(err != NO_ERROR)) {
3763 ALOGW_IF(err == TIMED_OUT,
3764 "setTransactionState timed out "
3765 "waiting for animation frame to apply");
3766 break;
3767 }
3768 itr = mTransactionQueues.find(applyToken);
3769 }
3770 }
3771 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003772 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003773 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003774 uncacheBuffer, listenerCallbacks, postTime,
3775 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003776 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003777 return;
3778 }
3779
Valerie Haubc6ddb12019-03-08 11:10:15 -08003780 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003781 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003782}
3783
3784void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003785 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003786 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003787 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003788 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003789 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003790 const int64_t postTime, bool privileged,
3791 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003792 uint32_t transactionFlags = 0;
3793
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003794 if (flags & eAnimation) {
3795 // For window updates that are part of an animation we must wait for
3796 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003797 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003798 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003799 if (CC_UNLIKELY(err != NO_ERROR)) {
3800 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003801 // caller after a few seconds.
3802 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3803 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003804 mAnimTransactionPending = false;
3805 break;
3806 }
3807 }
3808 }
3809
chaviwca27f252018-02-06 16:46:39 -08003810 for (const DisplayState& display : displays) {
3811 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003812 }
3813
Marissa Walld600d572019-03-26 15:38:50 -07003814 // In case the client has sent a Transaction that should receive callbacks but without any
3815 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3816 // to the callback thread so it can send an empty callback
3817 if (!listenerCallbacks.empty()) {
3818 mTransactionCompletedThread.run();
3819 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003820 for (const auto& listenerCallback : listenerCallbacks) {
3821 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003822 }
3823
Marissa Walle2ffb422018-10-12 11:33:52 -07003824 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003825 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003826 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3827 postTime, privileged);
3828 }
3829
Marissa Wallefb71af2019-06-27 14:45:53 -07003830 for (const auto& listenerCallback : listenerCallbacks) {
3831 mTransactionCompletedThread.endRegistration(listenerCallback);
3832 }
3833
Marissa Walle2ffb422018-10-12 11:33:52 -07003834 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003835 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003836 mTransactionCompletedThread.sendCallbacks();
3837 }
3838 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003839
chaviw273171b2018-12-26 11:46:30 -08003840 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3841
Marissa Wall947d34e2019-03-29 14:03:53 -07003842 if (uncacheBuffer.isValid()) {
3843 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003844 }
3845
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003846 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3847 // anyway. This can be used as a flush mechanism for previous async transactions.
3848 // Empty animation transaction can be used to simulate back-pressure, so also force a
3849 // transaction for empty animation transactions.
3850 if (transactionFlags == 0 &&
3851 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003852 transactionFlags = eTransactionNeeded;
3853 }
3854
Marissa Wall06255332019-03-27 13:48:27 -07003855 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3856 // so we don't have to wake up again next frame to preform an uneeded traversal.
3857 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3858 transactionFlags = transactionFlags & (~eTraversalNeeded);
3859 mTraversalNeededMainThread = true;
3860 }
3861
Mathias Agopian386aa982011-11-07 21:58:03 -08003862 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003863 if (mInterceptor->isEnabled()) {
3864 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003865 }
Irvel468051e2016-06-13 16:44:44 -07003866
Mathias Agopian386aa982011-11-07 21:58:03 -08003867 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003868 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3869 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003870 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003871
3872 // if this is a synchronous transaction, wait for it to take effect
3873 // before returning.
3874 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003875 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003876 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003877 if (flags & eAnimation) {
3878 mAnimTransactionPending = true;
3879 }
chaviw4fe36852019-04-15 16:25:49 -07003880 if (mPendingInputWindowCommands.syncInputWindows) {
3881 mPendingSyncInputWindows = true;
3882 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003883
3884 // applyTransactionState can be called by either the main SF thread or by
3885 // another process through setTransactionState. While a given process may wish
3886 // to wait on synchronous transactions, the main SF thread should never
3887 // be blocked. Therefore, we only wait if isMainThread is false.
3888 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003889 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3890 if (CC_UNLIKELY(err != NO_ERROR)) {
3891 // just in case something goes wrong in SF, return to the
3892 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003893 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3894 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003895 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003896 break;
3897 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003898 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899 }
3900}
3901
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003902uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3903 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3904 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003905
Mathias Agopiane57f2922012-08-09 16:29:12 -07003906 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003907 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3908
3909 const uint32_t what = s.what;
3910 if (what & DisplayState::eSurfaceChanged) {
3911 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3912 state.surface = s.surface;
3913 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003914 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003915 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003916 if (what & DisplayState::eLayerStackChanged) {
3917 if (state.layerStack != s.layerStack) {
3918 state.layerStack = s.layerStack;
3919 flags |= eDisplayTransactionNeeded;
3920 }
3921 }
3922 if (what & DisplayState::eDisplayProjectionChanged) {
3923 if (state.orientation != s.orientation) {
3924 state.orientation = s.orientation;
3925 flags |= eDisplayTransactionNeeded;
3926 }
3927 if (state.frame != s.frame) {
3928 state.frame = s.frame;
3929 flags |= eDisplayTransactionNeeded;
3930 }
3931 if (state.viewport != s.viewport) {
3932 state.viewport = s.viewport;
3933 flags |= eDisplayTransactionNeeded;
3934 }
3935 }
3936 if (what & DisplayState::eDisplaySizeChanged) {
3937 if (state.width != s.width) {
3938 state.width = s.width;
3939 flags |= eDisplayTransactionNeeded;
3940 }
3941 if (state.height != s.height) {
3942 state.height = s.height;
3943 flags |= eDisplayTransactionNeeded;
3944 }
3945 }
3946
Mathias Agopiane57f2922012-08-09 16:29:12 -07003947 return flags;
3948}
3949
Robert Carr14167e02019-02-13 13:50:55 -08003950bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003951 IPCThreadState* ipc = IPCThreadState::self();
3952 const int pid = ipc->getCallingPid();
3953 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003954 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003955 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003956 return false;
3957 }
3958 return true;
3959}
3960
Marissa Wall3dad52d2019-03-22 14:03:19 -07003961uint32_t SurfaceFlinger::setClientStateLocked(
3962 const ComposerState& composerState, int64_t desiredPresentTime,
3963 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3964 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003965 const layer_state_t& s = composerState.state;
3966 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3967
Mathias Agopian13127d82013-03-05 17:47:11 -08003968 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003969 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003970 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003971 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003972 new CallbackHandle(listenerCallback.transactionCompletedListener,
3973 listenerCallback.callbackIds, s.surface));
3974 }
chaviw8b3871a2017-11-01 17:41:01 -07003975 return 0;
3976 }
3977
chaviw8b3871a2017-11-01 17:41:01 -07003978 uint32_t flags = 0;
3979
Garfield Tan8a3083e2018-12-03 13:21:07 -08003980 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003981 bool geometryAppliesWithResize =
3982 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003983
3984 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3985 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003986 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003987 layer->pushPendingState();
3988 }
3989
chaviw8b3871a2017-11-01 17:41:01 -07003990 if (what & layer_state_t::ePositionChanged) {
3991 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3992 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003993 }
chaviw8b3871a2017-11-01 17:41:01 -07003994 }
3995 if (what & layer_state_t::eLayerChanged) {
3996 // NOTE: index needs to be calculated before we update the state
3997 const auto& p = layer->getParent();
3998 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003999 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004000 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004001 mCurrentState.layersSortedByZ.removeAt(idx);
4002 mCurrentState.layersSortedByZ.add(layer);
4003 // we need traversal (state changed)
4004 // AND transaction (list changed)
4005 flags |= eTransactionNeeded|eTraversalNeeded;
4006 }
chaviw8b3871a2017-11-01 17:41:01 -07004007 } else {
4008 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004009 flags |= eTransactionNeeded|eTraversalNeeded;
4010 }
4011 }
chaviw8b3871a2017-11-01 17:41:01 -07004012 }
4013 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004014 // NOTE: index needs to be calculated before we update the state
4015 const auto& p = layer->getParent();
4016 if (p == nullptr) {
4017 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4018 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4019 mCurrentState.layersSortedByZ.removeAt(idx);
4020 mCurrentState.layersSortedByZ.add(layer);
4021 // we need traversal (state changed)
4022 // AND transaction (list changed)
4023 flags |= eTransactionNeeded|eTraversalNeeded;
4024 }
4025 } else {
4026 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4027 flags |= eTransactionNeeded|eTraversalNeeded;
4028 }
chaviw8b3871a2017-11-01 17:41:01 -07004029 }
4030 }
4031 if (what & layer_state_t::eSizeChanged) {
4032 if (layer->setSize(s.w, s.h)) {
4033 flags |= eTraversalNeeded;
4034 }
4035 }
4036 if (what & layer_state_t::eAlphaChanged) {
4037 if (layer->setAlpha(s.alpha))
4038 flags |= eTraversalNeeded;
4039 }
4040 if (what & layer_state_t::eColorChanged) {
4041 if (layer->setColor(s.color))
4042 flags |= eTraversalNeeded;
4043 }
Peiyong Lind3788632018-09-18 16:01:31 -07004044 if (what & layer_state_t::eColorTransformChanged) {
4045 if (layer->setColorTransform(s.colorTransform)) {
4046 flags |= eTraversalNeeded;
4047 }
4048 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004049 if (what & layer_state_t::eBackgroundColorChanged) {
4050 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4051 flags |= eTraversalNeeded;
4052 }
4053 }
chaviw8b3871a2017-11-01 17:41:01 -07004054 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004055 // TODO: b/109894387
4056 //
4057 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4058 // rotation. To see the problem observe that if we have a square parent, and a child
4059 // of the same size, then we rotate the child 45 degrees around it's center, the child
4060 // must now be cropped to a non rectangular 8 sided region.
4061 //
4062 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4063 // private API, and the WindowManager only uses rotation in one case, which is on a top
4064 // level layer in which cropping is not an issue.
4065 //
4066 // However given that abuse of rotation matrices could lead to surfaces extending outside
4067 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4068 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4069 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004070 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004071 flags |= eTraversalNeeded;
4072 }
4073 if (what & layer_state_t::eTransparentRegionChanged) {
4074 if (layer->setTransparentRegionHint(s.transparentRegion))
4075 flags |= eTraversalNeeded;
4076 }
4077 if (what & layer_state_t::eFlagsChanged) {
4078 if (layer->setFlags(s.flags, s.mask))
4079 flags |= eTraversalNeeded;
4080 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004081 if (what & layer_state_t::eCropChanged_legacy) {
4082 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004083 flags |= eTraversalNeeded;
4084 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004085 if (what & layer_state_t::eCornerRadiusChanged) {
4086 if (layer->setCornerRadius(s.cornerRadius))
4087 flags |= eTraversalNeeded;
4088 }
chaviw8b3871a2017-11-01 17:41:01 -07004089 if (what & layer_state_t::eLayerStackChanged) {
4090 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4091 // We only allow setting layer stacks for top level layers,
4092 // everything else inherits layer stack from its parent.
4093 if (layer->hasParent()) {
4094 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4095 layer->getName().string());
4096 } else if (idx < 0) {
4097 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4098 "that also does not appear in the top level layer list. Something"
4099 " has gone wrong.", layer->getName().string());
4100 } else if (layer->setLayerStack(s.layerStack)) {
4101 mCurrentState.layersSortedByZ.removeAt(idx);
4102 mCurrentState.layersSortedByZ.add(layer);
4103 // we need traversal (state changed)
4104 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004105 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004106 }
4107 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004108 if (what & layer_state_t::eDeferTransaction_legacy) {
4109 if (s.barrierHandle_legacy != nullptr) {
4110 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4111 } else if (s.barrierGbp_legacy != nullptr) {
4112 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004113 if (authenticateSurfaceTextureLocked(gbp)) {
4114 const auto& otherLayer =
4115 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004116 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004117 } else {
4118 ALOGE("Attempt to defer transaction to to an"
4119 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004120 }
4121 }
chaviw8b3871a2017-11-01 17:41:01 -07004122 // We don't trigger a traversal here because if no other state is
4123 // changed, we don't want this to cause any more work
4124 }
4125 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004126 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004127 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004128 if (!hadParent) {
4129 mCurrentState.layersSortedByZ.remove(layer);
4130 }
chaviw8b3871a2017-11-01 17:41:01 -07004131 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004132 }
chaviw8b3871a2017-11-01 17:41:01 -07004133 }
4134 if (what & layer_state_t::eReparentChildren) {
4135 if (layer->reparentChildren(s.reparentHandle)) {
4136 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004137 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004138 }
chaviw8b3871a2017-11-01 17:41:01 -07004139 if (what & layer_state_t::eDetachChildren) {
4140 layer->detachChildren();
4141 }
4142 if (what & layer_state_t::eOverrideScalingModeChanged) {
4143 layer->setOverrideScalingMode(s.overrideScalingMode);
4144 // We don't trigger a traversal here because if no other state is
4145 // changed, we don't want this to cause any more work
4146 }
Marissa Wall61c58622018-07-18 10:12:20 -07004147 if (what & layer_state_t::eTransformChanged) {
4148 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4149 }
4150 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4151 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4152 flags |= eTraversalNeeded;
4153 }
4154 if (what & layer_state_t::eCropChanged) {
4155 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4156 }
Marissa Wall861616d2018-10-22 12:52:23 -07004157 if (what & layer_state_t::eFrameChanged) {
4158 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4159 }
Marissa Wall61c58622018-07-18 10:12:20 -07004160 if (what & layer_state_t::eAcquireFenceChanged) {
4161 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4162 }
4163 if (what & layer_state_t::eDataspaceChanged) {
4164 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4165 }
4166 if (what & layer_state_t::eHdrMetadataChanged) {
4167 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4168 }
4169 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4170 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4171 }
4172 if (what & layer_state_t::eApiChanged) {
4173 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4174 }
4175 if (what & layer_state_t::eSidebandStreamChanged) {
4176 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4177 }
Robert Carr720e5062018-07-30 17:45:14 -07004178 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004179 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004180 layer->setInputInfo(s.inputInfo);
4181 flags |= eTraversalNeeded;
4182 } else {
4183 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4184 }
Robert Carr720e5062018-07-30 17:45:14 -07004185 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004186 if (what & layer_state_t::eMetadataChanged) {
4187 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4188 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004189 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4190 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4191 flags |= eTraversalNeeded;
4192 }
4193 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004194 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004195 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004196 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004197 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4198 }
4199 }
Marissa Wall78b72202019-03-15 14:58:34 -07004200 bool bufferChanged = what & layer_state_t::eBufferChanged;
4201 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4202 sp<GraphicBuffer> buffer;
4203 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004204 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri1c8d7202019-06-01 18:51:35 -07004205 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4206 wp<ClientCache::ErasedRecipient>(layer));
4207 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004208 buffer = s.buffer;
4209 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004210 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004211 } else if (bufferChanged) {
4212 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004213 }
Marissa Wall78b72202019-03-15 14:58:34 -07004214 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004215 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004216 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004217 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004218 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004219 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4220 // Do not put anything that updates layer state or modifies flags after
4221 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004222 return flags;
4223}
4224
chaviw273171b2018-12-26 11:46:30 -08004225uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4226 uint32_t flags = 0;
4227 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4228 flags |= eTraversalNeeded;
4229 }
4230
chaviwa911b102019-02-14 10:18:33 -08004231 if (inputWindowCommands.syncInputWindows) {
4232 flags |= eTraversalNeeded;
4233 }
4234
Vishnu Nairec0ab382019-02-13 15:32:56 -08004235 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004236 return flags;
4237}
4238
Marissa Wall2d814fb2019-04-09 18:52:57 +00004239status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4240 uint32_t h, PixelFormat format, uint32_t flags,
4241 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004242 sp<IGraphicBufferProducer>* gbp,
4243 const sp<IBinder>& parentHandle,
4244 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004245 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004246 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004247 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004248 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004249 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004250
Robert Carrc0df3122019-04-11 13:18:21 -07004251 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4252 "Expected only one of parentLayer or parentHandle to be non-null. "
4253 "Programmer error?");
4254
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004255 status_t result = NO_ERROR;
4256
4257 sp<Layer> layer;
4258
Cody Northropbc755282017-03-31 12:00:08 -06004259 String8 uniqueName = getUniqueLayerName(name);
4260
Evan Roskya1f1e152019-01-24 16:17:46 -08004261 bool primaryDisplayOnly = false;
4262
4263 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4264 // TODO b/64227542
4265 if (metadata.has(METADATA_WINDOW_TYPE)) {
4266 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4267 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004268 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004269 primaryDisplayOnly = true;
4270 }
4271 }
4272
Mathias Agopian3165cc22012-08-08 19:42:09 -07004273 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004274 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004275 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4276 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004277
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004278 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004279 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004280 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4281 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004282 break;
chaviw13fdc492017-06-27 12:40:18 -07004283 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004284 // check if buffer size is set for color layer.
4285 if (w > 0 || h > 0) {
4286 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4287 int(w), int(h));
4288 return BAD_VALUE;
4289 }
4290
Evan Roskya1f1e152019-01-24 16:17:46 -08004291 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4292 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004293 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004294 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004295 // check if buffer size is set for container layer.
4296 if (w > 0 || h > 0) {
4297 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4298 int(w), int(h));
4299 return BAD_VALUE;
4300 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004301 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4302 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004303 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004304 default:
4305 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004306 break;
4307 }
4308
Dan Stoza7d89d062015-04-30 13:29:25 -07004309 if (result != NO_ERROR) {
4310 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004311 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004312
Evan Roskya1f1e152019-01-24 16:17:46 -08004313 if (primaryDisplayOnly) {
4314 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004315 }
4316
Robert Carrb89ea9d2018-12-10 13:01:14 -08004317 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004318 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4319 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004320 if (result != NO_ERROR) {
4321 return result;
4322 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004323 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004324
4325 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004326 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004327}
4328
Cody Northropbc755282017-03-31 12:00:08 -06004329String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4330{
4331 bool matchFound = true;
4332 uint32_t dupeCounter = 0;
4333
4334 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4335 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4336
Dan Stoza436ccf32018-06-21 12:10:12 -07004337 // Grab the state lock since we're accessing mCurrentState
4338 Mutex::Autolock lock(mStateLock);
4339
Cody Northropbc755282017-03-31 12:00:08 -06004340 // Loop over layers until we're sure there is no matching name
4341 while (matchFound) {
4342 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004343 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004344 if (layer->getName() == uniqueName) {
4345 matchFound = true;
4346 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4347 }
4348 });
4349 }
4350
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004351 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4352 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004353
4354 return uniqueName;
4355}
4356
Marissa Wallfd668622018-05-10 10:21:13 -07004357status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4358 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004359 LayerMetadata metadata, PixelFormat& format,
4360 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004361 sp<IGraphicBufferProducer>* gbp,
4362 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004363 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004364 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 case PIXEL_FORMAT_TRANSPARENT:
4366 case PIXEL_FORMAT_TRANSLUCENT:
4367 format = PIXEL_FORMAT_RGBA_8888;
4368 break;
4369 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004370 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004371 break;
4372 }
4373
Evan Roskya1f1e152019-01-24 16:17:46 -08004374 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4375 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004376 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004377 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004378 *handle = layer->getHandle();
4379 *gbp = layer->getProducer();
4380 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004382
Marissa Wallfd668622018-05-10 10:21:13 -07004383 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004384 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004385}
4386
Marissa Wall61c58622018-07-18 10:12:20 -07004387status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4388 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004389 LayerMetadata metadata, sp<IBinder>* handle,
4390 sp<Layer>* outLayer) {
4391 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4392 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004393 *handle = layer->getHandle();
4394 *outLayer = layer;
4395
4396 return NO_ERROR;
4397}
4398
Evan Roskya1f1e152019-01-24 16:17:46 -08004399status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4400 uint32_t h, uint32_t flags, LayerMetadata metadata,
4401 sp<IBinder>* handle, sp<Layer>* outLayer) {
4402 *outLayer = getFactory().createColorLayer(
4403 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004404 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004405 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004406}
4407
Evan Roskya1f1e152019-01-24 16:17:46 -08004408status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4409 uint32_t w, uint32_t h, uint32_t flags,
4410 LayerMetadata metadata, sp<IBinder>* handle,
4411 sp<Layer>* outLayer) {
4412 *outLayer = getFactory().createContainerLayer(
4413 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004414 *handle = (*outLayer)->getHandle();
4415 return NO_ERROR;
4416}
4417
4418
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004419void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004420 mLayersPendingRemoval.add(layer);
4421 mLayersRemoved = true;
4422 setTransactionFlags(eTransactionNeeded);
4423}
4424
Robert Carr695d5282018-12-18 15:27:58 -08004425void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004426{
Robert Carr2e102c92018-10-23 12:11:15 -07004427 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004428 // If a layer has a parent, we allow it to out-live it's handle
4429 // with the idea that the parent holds a reference and will eventually
4430 // be cleaned up. However no one cleans up the top-level so we do so
4431 // here.
4432 if (layer->getParent() == nullptr) {
4433 mCurrentState.layersSortedByZ.remove(layer);
4434 }
4435 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004436
4437 auto it = mLayersByLocalBinderToken.begin();
4438 while (it != mLayersByLocalBinderToken.end()) {
4439 if (it->second == layer) {
4440 it = mLayersByLocalBinderToken.erase(it);
4441 } else {
4442 it++;
4443 }
4444 }
4445
Robert Carr695d5282018-12-18 15:27:58 -08004446 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004447}
4448
Mathias Agopianb60314a2012-04-10 22:09:54 -07004449// ---------------------------------------------------------------------------
4450
Andy McFadden13a082e2012-08-24 10:16:42 -07004451void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004452 const auto display = getDefaultDisplayDeviceLocked();
4453 if (!display) return;
4454
4455 const sp<IBinder> token = display->getDisplayToken().promote();
4456 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004457
Jesse Hall01e29052013-02-19 16:13:35 -08004458 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004459 Vector<ComposerState> state;
4460 Vector<DisplayState> displays;
4461 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004462 d.what = DisplayState::eDisplayProjectionChanged |
4463 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004464 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004465 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004466 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004467 d.frame.makeInvalid();
4468 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004469 d.width = 0;
4470 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004471 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004472 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004473
Dominik Laskowskie9774092018-12-11 10:04:24 -08004474 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004475
Dominik Laskowski83b88212018-12-11 13:34:06 -08004476 const nsecs_t vsyncPeriod = getVsyncPeriod();
4477 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004478
Brian Andersond0010582017-03-07 13:20:31 -08004479 // Use phase of 0 since phase is not known.
4480 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004481 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004482 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004483}
4484
4485void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004486 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004487 postMessageAsync(
4488 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004489}
4490
Ady Abraham27c70212019-06-11 10:52:26 -07004491void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4492 if (mHWCVsyncState != enabled) {
4493 getHwComposer().setVsyncEnabled(displayId, enabled);
4494 mHWCVsyncState = enabled;
4495 }
4496}
4497
Dominik Laskowskie9774092018-12-11 10:04:24 -08004498void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004499 if (display->isVirtual()) {
4500 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004501 return;
4502 }
4503
Dominik Laskowski075d3172018-05-24 15:50:06 -07004504 const auto displayId = display->getId();
4505 LOG_ALWAYS_FATAL_IF(!displayId);
4506
Dominik Laskowski34157762018-10-31 13:07:19 -07004507 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004508
4509 int currentMode = display->getPowerMode();
4510 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004511 return;
4512 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004513
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004514 display->setPowerMode(mode);
4515
Lloyd Pique4dccc412018-01-22 17:21:36 -08004516 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004517 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004518 }
4519
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004520 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004521 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004522 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004523 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004524 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004525 mScheduler->onScreenAcquired(mAppConnectionHandle);
4526 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004527 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004529 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004530 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004531 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004532
4533 struct sched_param param = {0};
4534 param.sched_priority = 1;
4535 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4536 ALOGW("Couldn't set SCHED_FIFO on display on");
4537 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004538 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004539 // Turn off the display
4540 struct sched_param param = {0};
4541 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4542 ALOGW("Couldn't set SCHED_OTHER on display off");
4543 }
4544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004545 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004546 mScheduler->disableHardwareVsync(true);
4547 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004548 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004549
Ady Abraham27c70212019-06-11 10:52:26 -07004550 // Make sure HWVsync is disabled before turning off the display
4551 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4552
Dominik Laskowski075d3172018-05-24 15:50:06 -07004553 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004554 mVisibleRegionsDirty = true;
4555 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004556 } else if (mode == HWC_POWER_MODE_DOZE ||
4557 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004558 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004559 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004560 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004561 mScheduler->onScreenAcquired(mAppConnectionHandle);
4562 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004563 }
4564 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4565 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004566 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004567 mScheduler->disableHardwareVsync(true);
4568 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004569 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004570 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004571 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004572 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004573 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004574 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004575
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004576 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004577 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004578 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004579 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004580 }
4581
Dominik Laskowski34157762018-10-31 13:07:19 -07004582 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004583}
4584
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004585void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004586 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004587 const auto display = getDisplayDevice(displayToken);
4588 if (!display) {
4589 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4590 displayToken.get());
4591 } else if (display->isVirtual()) {
4592 ALOGW("Attempt to set power mode %d for virtual display", mode);
4593 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004594 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004595 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004596 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004597}
4598
4599// ---------------------------------------------------------------------------
4600
Dominik Laskowskic2867142019-01-21 11:33:38 -08004601status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4602 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004603 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004604
Mathias Agopianbd115332013-04-18 16:41:04 -07004605 IPCThreadState* ipc = IPCThreadState::self();
4606 const int pid = ipc->getCallingPid();
4607 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004608
Mathias Agopianbd115332013-04-18 16:41:04 -07004609 if ((uid != AID_SHELL) &&
4610 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004611 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4612 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004613 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004614 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004615 // (this would indicate SF is stuck, but we want to be able to
4616 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004617 status_t err = mStateLock.timedLock(s2ns(1));
4618 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004619 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result,
4621 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4622 "(no locks held)\n",
4623 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004624 }
4625
Dominik Laskowskic2867142019-01-21 11:33:38 -08004626 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004627
Dominik Laskowskic2867142019-01-21 11:33:38 -08004628 static const std::unordered_map<std::string, Dumper> dumpers = {
4629 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4630 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4631 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004632 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004633 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004634 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004635 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4636 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004637 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4638 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4639 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4640 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4641 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4642 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004643 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004644 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4645 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004646
Dominik Laskowskic2867142019-01-21 11:33:38 -08004647 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004648
Dominik Laskowskic2867142019-01-21 11:33:38 -08004649 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4650 (it->second)(args, asProto, result);
4651 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004652 if (asProto) {
4653 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4654 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4655 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004656 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004657 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004658 }
4659
Mathias Agopian9795c422009-08-26 16:36:26 -07004660 if (locked) {
4661 mStateLock.unlock();
4662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004663 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004664 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004665 return NO_ERROR;
4666}
4667
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004668status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4669 if (asProto && mTracing.isEnabled()) {
4670 mTracing.writeToFileAsync();
4671 }
4672
4673 return doDump(fd, DumpArgs(), asProto);
4674}
4675
Dominik Laskowskic2867142019-01-21 11:33:38 -08004676void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 mCurrentState.traverseInZOrder(
4678 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004679}
4680
Dominik Laskowskic2867142019-01-21 11:33:38 -08004681void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004682 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004683
Dominik Laskowskic2867142019-01-21 11:33:38 -08004684 if (args.size() > 1) {
4685 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004686 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004687 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004688 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004689 }
Robert Carr2047fae2016-11-28 14:09:09 -08004690 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004691 } else {
4692 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693 }
4694}
4695
Dominik Laskowskic2867142019-01-21 11:33:38 -08004696void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004697 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004698 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004699 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004700 }
Robert Carr2047fae2016-11-28 14:09:09 -08004701 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004702
Svetoslavd85084b2014-03-20 10:28:31 -07004703 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004704}
4705
Dominik Laskowskic2867142019-01-21 11:33:38 -08004706void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4707 mTimeStats->parseArgs(asProto, args, result);
4708}
4709
Jamie Gennis6547ff42013-07-16 20:12:42 -07004710// This should only be called from the main thread. Otherwise it would need
4711// the lock and should use mCurrentState rather than mDrawingState.
4712void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004713 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004714 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004715 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004716
4717 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4718}
4719
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004721 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004722
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004723 if (isLayerTripleBufferingDisabled())
4724 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004725
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4727 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4728 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4729 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4730 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4731 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004732 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004733}
4734
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004735void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004736 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004737 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004738 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004739 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004740
Ady Abraham97d04232019-03-05 19:48:12 -08004741 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004742 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4743 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004744 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham261614e2019-07-10 17:53:12 -07004745 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4746 if (refresh.second && isDisplayConfigAllowed(refresh.second->configId)) {
4747 StringAppendF(&result, "%dHz, ", refresh.second->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004748 }
4749 }
4750 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4751 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004752 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004753}
4754
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4756 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004757 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4758 float bucketTimeSec = getBE().mFrameBuckets[b] / 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[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004762 }
David Sodman4a36e932017-11-07 14:29:47 -08004763 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004764 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004765 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004766 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4767 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004768}
4769
Dan Stozae77c7662016-05-13 11:37:28 -07004770void SurfaceFlinger::recordBufferingStats(const char* layerName,
4771 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004772 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4773 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004774 for (const auto& segment : history) {
4775 if (!segment.usedThirdBuffer) {
4776 stats.twoBufferTime += segment.totalTime;
4777 }
4778 if (segment.occupancyAverage < 1.0f) {
4779 stats.doubleBufferedTime += segment.totalTime;
4780 } else if (segment.occupancyAverage < 2.0f) {
4781 stats.tripleBufferedTime += segment.totalTime;
4782 }
4783 ++stats.numSegments;
4784 stats.totalTime += segment.totalTime;
4785 }
4786}
4787
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4789 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004790
4791 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4792 const size_t count = currentLayers.size();
4793 for (size_t i=0 ; i<count ; i++) {
4794 currentLayers[i]->dumpFrameEvents(result);
4795 }
4796}
4797
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004799 result.append("Buffering stats:\n");
4800 result.append(" [Layer name] <Active time> <Two buffer> "
4801 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004802 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004803 typedef std::tuple<std::string, float, float, float> BufferTuple;
4804 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004805 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004806 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004807 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004808 if (stats.numSegments == 0) {
4809 continue;
4810 }
4811 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4812 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4813 stats.totalTime;
4814 float doubleBufferRatio = static_cast<float>(
4815 stats.doubleBufferedTime) / stats.totalTime;
4816 float tripleBufferRatio = static_cast<float>(
4817 stats.tripleBufferedTime) / stats.totalTime;
4818 sorted.insert({activeTime, {name, twoBufferRatio,
4819 doubleBufferRatio, tripleBufferRatio}});
4820 }
4821 for (const auto& sortedPair : sorted) {
4822 float activeTime = sortedPair.first;
4823 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004824 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4825 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004826 }
4827 result.append("\n");
4828}
4829
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004831 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004832 const auto displayId = display->getId();
4833 if (!displayId) {
4834 continue;
4835 }
4836 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004837 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004838 continue;
4839 }
4840
Yiwei Zhang5434a782018-12-05 18:06:32 -08004841 StringAppendF(&result,
4842 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4843 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004844 uint8_t port;
4845 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004846 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004847 result.append("no identification data\n");
4848 continue;
4849 }
4850
4851 if (!isEdid(data)) {
4852 result.append("unknown identification data: ");
4853 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004854 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004855 }
4856 result.append("\n");
4857 continue;
4858 }
4859
4860 const auto edid = parseEdid(data);
4861 if (!edid) {
4862 result.append("invalid EDID: ");
4863 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004864 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004865 }
4866 result.append("\n");
4867 continue;
4868 }
4869
Yiwei Zhang5434a782018-12-05 18:06:32 -08004870 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004871 result.append(edid->displayName.data(), edid->displayName.length());
4872 result.append("\"\n");
4873 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004874}
4875
Yiwei Zhang5434a782018-12-05 18:06:32 -08004876void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004877 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4879 StringAppendF(&result, "DisplayColorSetting: %s\n",
4880 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004881
4882 // TODO: print out if wide-color mode is active or not
4883
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004884 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004885 const auto displayId = display->getId();
4886 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004887 continue;
4888 }
4889
Yiwei Zhang5434a782018-12-05 18:06:32 -08004890 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004891 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004892 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004893 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004894 }
4895
Lloyd Pique32cbe282018-10-19 13:09:22 -07004896 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004897 StringAppendF(&result, " Current color mode: %s (%d)\n",
4898 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004899 }
4900 result.append("\n");
4901}
4902
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004903LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4904 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004905 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004906 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4907 const State& state = useDrawing ? mDrawingState : mCurrentState;
4908 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004909 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004910 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004911 });
4912
4913 return layersProto;
4914}
4915
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004916LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4917 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004918 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004919
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004920 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004921 resolution->set_w(displayDevice->getWidth());
4922 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004923
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004924 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004925 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004926
Lloyd Pique32cbe282018-10-19 13:09:22 -07004927 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4928 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4929 layersProto.set_global_transform(displayState.orientation);
4930
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004931 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004932 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004933 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004934 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004935 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004936 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004937 }
4938 });
4939
4940 return layersProto;
4941}
4942
Dominik Laskowskic2867142019-01-21 11:33:38 -08004943void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4944 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004945 Colorizer colorizer(colorize);
4946
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004947 // figure out if we're stuck somewhere
4948 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004949 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004950 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4951
4952 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004953 * Dump library configuration.
4954 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004955
4956 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004957 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004958 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004959 appendSfConfigString(result);
4960 appendUiConfigString(result);
4961 appendGuiConfigString(result);
4962 result.append("\n");
4963
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004964 result.append("\nDisplay identification data:\n");
4965 dumpDisplayIdentificationData(result);
4966
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004967 result.append("\nWide-Color information:\n");
4968 dumpWideColorInfo(result);
4969
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004970 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004971 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004972 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004973 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004974 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004975
Andy McFadden41d67d72014-04-25 16:58:34 -07004976 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004977 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004978 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004979 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004980 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004981
Dan Stozab90cf072015-03-05 11:05:59 -08004982 dumpStaticScreenStats(result);
4983 result.append("\n");
4984
Alec Mouri40189b02019-03-05 15:07:54 -08004985 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4986 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4987 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004988
Dan Stozae77c7662016-05-13 11:37:28 -07004989 dumpBufferingStats(result);
4990
Andy McFadden4803b742012-09-24 19:07:20 -07004991 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004992 * Dump the visible layer list
4993 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004994 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004995 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4996 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4997 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004998 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004999
Chia-I Wu2f884132018-09-13 15:17:58 -07005000 {
5001 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
5002 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005003 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07005004 result.append("\n");
5005 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005006
Lloyd Pique207def92019-02-28 16:09:52 -08005007 {
5008 StringAppendF(&result, "Composition layers\n");
5009 mDrawingState.traverseInZOrder([&](Layer* layer) {
5010 auto compositionLayer = layer->getCompositionLayer();
5011 if (compositionLayer) compositionLayer->dump(result);
5012 });
5013 }
5014
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005015 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005016 * Dump Display state
5017 */
5018
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005019 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005020 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005021 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005022 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005023 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005024 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005025 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005026
5027 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005028 * Dump SurfaceFlinger global state
5029 */
5030
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005031 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005032 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005033 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005034
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005035 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005036
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005037 DebugEGLImageTracker::getInstance()->dump(result);
5038
Dominik Laskowski075d3172018-05-24 15:50:06 -07005039 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005040 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5041 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005042 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5043 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005044 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005045 StringAppendF(&result,
5046 " transaction-flags : %08x\n"
5047 " gpu_to_cpu_unsupported : %d\n",
5048 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005049
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005050 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005051 displayId && getHwComposer().isConnected(*displayId)) {
5052 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005053 StringAppendF(&result,
5054 " refresh-rate : %f fps\n"
5055 " x-dpi : %f\n"
5056 " y-dpi : %f\n",
5057 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5058 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005059 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005060
Yiwei Zhang5434a782018-12-05 18:06:32 -08005061 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005062
Dan Stozae22aec72016-08-01 13:20:59 -07005063 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005064 * Tracing state
5065 */
5066 mTracing.dump(result);
5067 result.append("\n");
5068
5069 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005070 * HWC layer minidump
5071 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005072 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005073 const auto displayId = display->getId();
5074 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005075 continue;
5076 }
5077
Yiwei Zhang5434a782018-12-05 18:06:32 -08005078 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005079 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005080 const sp<DisplayDevice> displayDevice = display;
5081 mCurrentState.traverseInZOrder(
5082 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005083 result.append("\n");
5084 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005085
5086 /*
5087 * Dump HWComposer state
5088 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005089 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005090 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005091 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005092 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005093 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005094 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005095
5096 /*
5097 * Dump gralloc state
5098 */
5099 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5100 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005101
5102 /*
5103 * Dump VrFlinger state if in use.
5104 */
5105 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5106 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005107 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005108 result.append("\n");
5109 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005110
5111 /**
5112 * Scheduler dump state.
5113 */
Ana Krulecc2870422019-01-29 19:00:58 -08005114 result.append("\nScheduler state:\n");
5115 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005116 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005117 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005118
5119 result.append(mTimeStats->miniDump());
5120 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005121}
5122
Dominik Laskowski075d3172018-05-24 15:50:06 -07005123const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005124 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005125 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005126 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005127 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005128 }
5129 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005130
Dominik Laskowski34157762018-10-31 13:07:19 -07005131 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005132 static const Vector<sp<Layer>> empty;
5133 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005134}
5135
Chia-I Wu28f320b2018-05-03 11:02:56 -07005136void SurfaceFlinger::updateColorMatrixLocked() {
5137 mat4 colorMatrix;
5138 if (mGlobalSaturationFactor != 1.0f) {
5139 // Rec.709 luma coefficients
5140 float3 luminance{0.213f, 0.715f, 0.072f};
5141 luminance *= 1.0f - mGlobalSaturationFactor;
5142 mat4 saturationMatrix = mat4(
5143 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5144 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5145 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5146 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5147 );
5148 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5149 } else {
5150 colorMatrix = mClientColorMatrix * mDaltonizer();
5151 }
5152
5153 if (mCurrentState.colorMatrix != colorMatrix) {
5154 mCurrentState.colorMatrix = colorMatrix;
5155 mCurrentState.colorMatrixChanged = true;
5156 setTransactionFlags(eTransactionNeeded);
5157 }
5158}
5159
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005160status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005161#pragma clang diagnostic push
5162#pragma clang diagnostic error "-Wswitch-enum"
5163 switch (static_cast<ISurfaceComposerTag>(code)) {
5164 // These methods should at minimum make sure that the client requested
5165 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005166 case BOOT_FINISHED:
5167 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005168 case CREATE_DISPLAY:
5169 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005170 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005171 case GET_ANIMATION_FRAME_STATS:
5172 case GET_HDR_CAPABILITIES:
5173 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005174 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005175 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005176 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005177 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005178 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005179 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005180 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005181 case GET_DISPLAYED_CONTENT_SAMPLE:
5182 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005183 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5184 IPCThreadState* ipc = IPCThreadState::self();
5185 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5186 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005187 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005188 }
Robert Carr1db73f62016-12-21 12:58:51 -08005189 return OK;
5190 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005191 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005192 IPCThreadState* ipc = IPCThreadState::self();
5193 const int pid = ipc->getCallingPid();
5194 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005195 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5196 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005197 return PERMISSION_DENIED;
5198 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005199 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005200 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005201 // Used by apps to hook Choreographer to SurfaceFlinger.
5202 case CREATE_DISPLAY_EVENT_CONNECTION:
5203 // The following calls are currently used by clients that do not
5204 // request necessary permissions. However, they do not expose any secret
5205 // information, so it is OK to pass them.
5206 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005207 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005208 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005209 case GET_PHYSICAL_DISPLAY_IDS:
5210 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005211 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005212 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005213 case GET_DISPLAY_CONFIGS:
5214 case GET_DISPLAY_STATS:
5215 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5216 // Calling setTransactionState is safe, because you need to have been
5217 // granted a reference to Client* and Handle* to do anything with it.
5218 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005219 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005220 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005221 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005222 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005223 case IS_WIDE_COLOR_DISPLAY:
5224 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5225 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005226 return OK;
5227 }
Chong Zhangda6c1592019-07-16 13:45:06 -07005228 case CAPTURE_LAYERS: {
5229 IPCThreadState* ipc = IPCThreadState::self();
5230 const int pid = ipc->getCallingPid();
5231 const int uid = ipc->getCallingUid();
5232 // allow media to capture layer for video thumbnails
5233 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
5234 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5235 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
5236 return PERMISSION_DENIED;
5237 }
5238 return OK;
5239 }
Dan Stoza84ab9372018-12-17 15:27:57 -08005240 case CAPTURE_SCREEN:
5241 case ADD_REGION_SAMPLING_LISTENER:
5242 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005243 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005244 IPCThreadState* ipc = IPCThreadState::self();
5245 const int pid = ipc->getCallingPid();
5246 const int uid = ipc->getCallingUid();
5247 if ((uid != AID_GRAPHICS) &&
5248 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5249 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5250 return PERMISSION_DENIED;
5251 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005252 return OK;
5253 }
5254 // The following codes are deprecated and should never be allowed to access SF.
5255 case CONNECT_DISPLAY_UNUSED:
5256 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5257 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5258 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005259 }
chaviw93df2ea2019-04-30 16:45:12 -07005260 case CAPTURE_SCREEN_BY_ID: {
5261 IPCThreadState* ipc = IPCThreadState::self();
5262 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005263 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005264 return OK;
5265 }
5266 return PERMISSION_DENIED;
5267 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005268 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005269
5270 // These codes are used for the IBinder protocol to either interrogate the recipient
5271 // side of the transaction for its canonical interface descriptor or to dump its state.
5272 // We let them pass by default.
5273 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5274 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5275 code == IBinder::SYSPROPS_TRANSACTION) {
5276 return OK;
5277 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005278 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005279 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005280 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005281 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5282 return OK;
5283 }
5284 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5285 return PERMISSION_DENIED;
5286#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005287}
5288
Ana Krulec13be8ad2018-08-21 02:43:56 +00005289status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5290 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005291 status_t credentialCheck = CheckTransactCodeCredentials(code);
5292 if (credentialCheck != OK) {
5293 return credentialCheck;
5294 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005295
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005296 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5297 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005298 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005299 IPCThreadState* ipc = IPCThreadState::self();
5300 const int uid = ipc->getCallingUid();
5301 if (CC_UNLIKELY(uid != AID_SYSTEM
5302 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005303 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005304 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005305 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005306 return PERMISSION_DENIED;
5307 }
5308 int n;
5309 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005310 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005311 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005312 return NO_ERROR;
5313 case 1002: // SHOW_UPDATES
5314 n = data.readInt32();
5315 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005316 invalidateHwcGeometry();
5317 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005318 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005319 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005320 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005321 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005322 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005323 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005324 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005325 setTransactionFlags(
5326 eTransactionNeeded|
5327 eDisplayTransactionNeeded|
5328 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005329 return NO_ERROR;
5330 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005331 case 1006:{ // send empty update
5332 signalRefresh();
5333 return NO_ERROR;
5334 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005335 case 1008: // toggle use of hw composer
5336 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005337 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005338 invalidateHwcGeometry();
5339 repaintEverything();
5340 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005341 case 1009: // toggle use of transform hint
5342 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005343 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005344 invalidateHwcGeometry();
5345 repaintEverything();
5346 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005347 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005348 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005349 reply->writeInt32(0);
5350 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005351 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005352 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005353 return NO_ERROR;
5354 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005355 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005356 if (!display) {
5357 return NAME_NOT_FOUND;
5358 }
5359
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005360 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005361 return NO_ERROR;
5362 }
5363 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005364 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005365 // daltonize
5366 n = data.readInt32();
5367 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005368 case 1:
5369 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5370 break;
5371 case 2:
5372 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5373 break;
5374 case 3:
5375 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5376 break;
5377 default:
5378 mDaltonizer.setType(ColorBlindnessType::None);
5379 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005380 }
5381 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005382 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005383 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005384 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005385 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005386
5387 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005388 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005389 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005390 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005391 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005392 // apply a color matrix
5393 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005394 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005395 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005396 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005397 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005398 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005399 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005400 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005401 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005402 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005403 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005404
5405 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5406 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005407 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005408 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5409 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5410 }
5411
Chia-I Wu28f320b2018-05-03 11:02:56 -07005412 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005413 return NO_ERROR;
5414 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005415 // This is an experimental interface
5416 // Needs to be shifted to proper binder interface when we productize
5417 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005418 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005419 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005420 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005421 return NO_ERROR;
5422 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005423 case 1017: {
5424 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005425 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005426 return NO_ERROR;
5427 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005428 case 1018: { // Modify Choreographer's phase offset
5429 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005430 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005431 return NO_ERROR;
5432 }
5433 case 1019: { // Modify SurfaceFlinger's phase offset
5434 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005435 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005436 return NO_ERROR;
5437 }
Irvel468051e2016-06-13 16:44:44 -07005438 case 1020: { // Layer updates interceptor
5439 n = data.readInt32();
5440 if (n) {
5441 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005442 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005443 }
5444 else{
5445 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005446 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005447 }
5448 return NO_ERROR;
5449 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005450 case 1021: { // Disable HWC virtual displays
5451 n = data.readInt32();
5452 mUseHwcVirtualDisplays = !n;
5453 return NO_ERROR;
5454 }
Romain Guy0147a172017-06-01 13:53:56 -07005455 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005456 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005457 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005458
Chia-I Wu28f320b2018-05-03 11:02:56 -07005459 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005460 return NO_ERROR;
5461 }
Romain Guy54f154a2017-10-24 21:40:32 +01005462 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005463 int32_t colorMode;
5464
Chia-I Wu0d711262018-05-21 15:19:35 -07005465 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005466 if (data.readInt32(&colorMode) == NO_ERROR) {
5467 mForceColorMode = static_cast<ColorMode>(colorMode);
5468 }
Romain Guy54f154a2017-10-24 21:40:32 +01005469 invalidateHwcGeometry();
5470 repaintEverything();
5471 return NO_ERROR;
5472 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005473 // Deprecate, use 1030 to check whether the device is color managed.
5474 case 1024: {
5475 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005476 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005477 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005478 n = data.readInt32();
5479 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005480 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005481 Mutex::Autolock lock(mStateLock);
5482 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005483 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005484 reply->writeInt32(NO_ERROR);
5485 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005486 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005487 bool writeFile = false;
5488 {
5489 Mutex::Autolock lock(mStateLock);
5490 mTracingEnabledChanged = true;
5491 writeFile = mTracing.disable();
5492 }
5493
5494 if (writeFile) {
5495 reply->writeInt32(mTracing.writeToFile());
5496 } else {
5497 reply->writeInt32(NO_ERROR);
5498 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005499 }
5500 return NO_ERROR;
5501 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005502 case 1026: { // Get layer tracing status
5503 reply->writeBool(mTracing.isEnabled());
5504 return NO_ERROR;
5505 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005506 // Is a DisplayColorSetting supported?
5507 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005508 const auto display = getDefaultDisplayDevice();
5509 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005510 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005511 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005512
5513 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5514 switch (setting) {
5515 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005516 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005517 break;
5518 case DisplayColorSetting::UNMANAGED:
5519 reply->writeBool(true);
5520 break;
5521 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005522 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005523 break;
5524 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005525 reply->writeBool(
5526 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005527 break;
5528 }
5529 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005530 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005531 // Is VrFlinger active?
5532 case 1028: {
5533 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005534 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005535 return NO_ERROR;
5536 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005537 // Set buffer size for SF tracing (value in KB)
5538 case 1029: {
5539 n = data.readInt32();
5540 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5541 ALOGW("Invalid buffer size: %d KB", n);
5542 reply->writeInt32(BAD_VALUE);
5543 return BAD_VALUE;
5544 }
5545
5546 ALOGD("Updating trace buffer to %d KB", n);
5547 mTracing.setBufferSize(n * 1024);
5548 reply->writeInt32(NO_ERROR);
5549 return NO_ERROR;
5550 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005551 // Is device color managed?
5552 case 1030: {
5553 reply->writeBool(useColorManagement);
5554 return NO_ERROR;
5555 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005556 // Override default composition data space
5557 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5558 // && adb shell stop zygote && adb shell start zygote
5559 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5560 // adb shell stop zygote && adb shell start zygote
5561 case 1031: {
5562 Mutex::Autolock _l(mStateLock);
5563 n = data.readInt32();
5564 if (n) {
5565 n = data.readInt32();
5566 if (n) {
5567 Dataspace dataspace = static_cast<Dataspace>(n);
5568 if (!validateCompositionDataspace(dataspace)) {
5569 return BAD_VALUE;
5570 }
5571 mDefaultCompositionDataspace = dataspace;
5572 }
5573 n = data.readInt32();
5574 if (n) {
5575 Dataspace dataspace = static_cast<Dataspace>(n);
5576 if (!validateCompositionDataspace(dataspace)) {
5577 return BAD_VALUE;
5578 }
5579 mWideColorGamutCompositionDataspace = dataspace;
5580 }
5581 } else {
5582 // restore composition data space.
5583 mDefaultCompositionDataspace = defaultCompositionDataspace;
5584 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5585 }
5586 return NO_ERROR;
5587 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005588 // Set trace flags
5589 case 1033: {
5590 n = data.readUint32();
5591 ALOGD("Updating trace flags to 0x%x", n);
5592 mTracing.setTraceFlags(n);
5593 reply->writeInt32(NO_ERROR);
5594 return NO_ERROR;
5595 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005596 case 1034: {
5597 // TODO(b/129297325): expose this via developer menu option
5598 n = data.readInt32();
5599 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005600 RefreshRateType type;
5601 {
5602 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5603 type = mDesiredActiveConfig.type;
5604 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005605 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005606 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005607 } else if (!n) {
5608 mRefreshRateOverlay.reset();
5609 }
5610 return NO_ERROR;
5611 }
Ady Abraham34392f72019-04-10 11:29:27 -07005612 case 1035: {
5613 n = data.readInt32();
5614 mDebugDisplayConfigSetByBackdoor = false;
5615 if (n >= 0) {
5616 const auto displayToken = getInternalDisplayToken();
5617 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5618 if (result != NO_ERROR) {
5619 return result;
5620 }
5621 mDebugDisplayConfigSetByBackdoor = true;
5622 }
5623 return NO_ERROR;
5624 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005625 }
5626 }
5627 return err;
5628}
5629
Steven Thomas6d8110b2017-08-31 18:24:21 -07005630void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005631 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005632 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005633}
5634
Ana Krulec7d1d6832018-12-27 11:10:09 -08005635void SurfaceFlinger::repaintEverythingForHWC() {
5636 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005637 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005638}
5639
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005640// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5641class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005642public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005643 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5644 ~WindowDisconnector() {
5645 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005646 }
5647
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005648private:
5649 ANativeWindow* mWindow;
5650 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005651};
5652
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005653status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005654 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5655 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005656 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005657 uint32_t reqWidth, uint32_t reqHeight,
5658 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005659 ISurfaceComposer::Rotation rotation,
5660 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005661 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005662
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005663 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005664
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005665 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5666
Chia-I Wu20261cb2018-08-23 12:55:44 -07005667 sp<DisplayDevice> display;
5668 {
5669 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005670
Chia-I Wu20261cb2018-08-23 12:55:44 -07005671 display = getDisplayDeviceLocked(displayToken);
5672 if (!display) return BAD_VALUE;
5673
Chia-I Wucb023152018-08-28 12:57:23 -07005674 // set the requested width/height to the logical display viewport size
5675 // by default
5676 if (reqWidth == 0 || reqHeight == 0) {
5677 reqWidth = uint32_t(display->getViewport().width());
5678 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005679 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005680 }
5681
Peiyong Lin0e003c92018-09-17 11:09:51 -07005682 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005683 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005684
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005685 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5686 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005687 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005688 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005689}
5690
chaviw93df2ea2019-04-30 16:45:12 -07005691static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5692 switch (colorMode) {
5693 case ColorMode::DISPLAY_P3:
5694 case ColorMode::BT2100_PQ:
5695 case ColorMode::BT2100_HLG:
5696 case ColorMode::DISPLAY_BT2020:
5697 return Dataspace::DISPLAY_P3;
5698 default:
5699 return Dataspace::V0_SRGB;
5700 }
5701}
5702
5703const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5704 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5705 if (displayToken) {
5706 return getDisplayDeviceLocked(displayToken);
5707 }
5708 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5709 // may not have a displayId.
5710 for (const auto& [token, display] : mDisplays) {
5711 if (display->getLayerStack() == displayOrLayerStack) {
5712 return display;
5713 }
5714 }
5715 return nullptr;
5716}
5717
5718status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5719 sp<GraphicBuffer>* outBuffer) {
5720 sp<DisplayDevice> display;
5721 uint32_t width;
5722 uint32_t height;
5723 ui::Transform::orientation_flags captureOrientation;
5724 {
5725 Mutex::Autolock _l(mStateLock);
5726 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5727 if (!display) {
5728 return BAD_VALUE;
5729 }
5730
5731 width = uint32_t(display->getViewport().width());
5732 height = uint32_t(display->getViewport().height());
5733
5734 captureOrientation = fromSurfaceComposerRotation(
5735 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005736 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5737 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5738 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5739 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5740 }
chaviw93df2ea2019-04-30 16:45:12 -07005741 *outDataspace =
5742 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5743 }
5744
5745 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5746 false /* captureSecureLayers */);
5747
5748 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5749 std::placeholders::_1);
5750 bool ignored = false;
5751 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5752 false /* useIdentityTransform */,
5753 ignored /* outCapturedSecureLayers */);
5754}
5755
Robert Carr866455f2019-04-02 16:28:26 -07005756status_t SurfaceFlinger::captureLayers(
5757 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5758 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5759 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5760 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005761 ATRACE_CALL();
5762
5763 class LayerRenderArea : public RenderArea {
5764 public:
Robert Carr578038f2018-03-09 12:25:24 -08005765 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005766 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5767 bool childrenOnly)
5768 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005769 mLayer(layer),
5770 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005771 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005772 mFlinger(flinger),
5773 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005774 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005775 Rect getBounds() const override {
5776 const Layer::State& layerState(mLayer->getDrawingState());
5777 return mLayer->getBufferSize(layerState);
5778 }
Marissa Wall61c58622018-07-18 10:12:20 -07005779 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005780 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005781 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005782 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005783 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005784 }
chaviwa76b2712017-09-20 12:02:26 -07005785 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005786 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005787 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005788 Rect getSourceCrop() const override {
5789 if (mCrop.isEmpty()) {
5790 return getBounds();
5791 } else {
5792 return mCrop;
5793 }
5794 }
Robert Carr578038f2018-03-09 12:25:24 -08005795 class ReparentForDrawing {
5796 public:
5797 const sp<Layer>& oldParent;
5798 const sp<Layer>& newParent;
5799
Vishnu Nair4351ad52019-02-11 14:13:02 -08005800 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5801 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005802 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005803 // Compute and cache the bounds for the new parent layer.
5804 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005805 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005806 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005807 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005808 };
5809
5810 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005811 const Rect sourceCrop = getSourceCrop();
5812 // no need to check rotation because there is none
5813 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5814 sourceCrop.height() != getReqHeight();
5815
Robert Carr578038f2018-03-09 12:25:24 -08005816 if (!mChildrenOnly) {
5817 mTransform = mLayer->getTransform().inverse();
5818 drawLayers();
5819 } else {
5820 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005821 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005822 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005823 bounds.getWidth(), bounds.getHeight(), 0,
5824 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005825
Vishnu Nair4351ad52019-02-11 14:13:02 -08005826 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005827 drawLayers();
5828 }
5829 }
chaviwa76b2712017-09-20 12:02:26 -07005830
chaviwa76b2712017-09-20 12:02:26 -07005831 private:
chaviw7206d492017-11-10 16:16:12 -08005832 const sp<Layer> mLayer;
5833 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005834
5835 // In the "childrenOnly" case we reparent the children to a screenshot
5836 // layer which has no properties set and which does not draw.
5837 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005838 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005839 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005840
5841 SurfaceFlinger* mFlinger;
5842 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005843 };
5844
Robert Carrc0df3122019-04-11 13:18:21 -07005845 int reqWidth = 0;
5846 int reqHeight = 0;
5847 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005848 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005849 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005850
Robert Carrc0df3122019-04-11 13:18:21 -07005851 {
5852 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005853
Robert Carrc0df3122019-04-11 13:18:21 -07005854 parent = fromHandle(layerHandleBinder);
5855 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5856 ALOGE("captureLayers called with an invalid or removed parent");
5857 return NAME_NOT_FOUND;
5858 }
5859
5860 const int uid = IPCThreadState::self()->getCallingUid();
5861 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5862 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5863 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5864 return PERMISSION_DENIED;
5865 }
5866
5867 if (sourceCrop.width() <= 0) {
5868 crop.left = 0;
5869 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5870 }
5871
5872 if (sourceCrop.height() <= 0) {
5873 crop.top = 0;
5874 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5875 }
5876 reqWidth = crop.width() * frameScale;
5877 reqHeight = crop.height() * frameScale;
5878
5879 for (const auto& handle : excludeHandles) {
5880 sp<Layer> excludeLayer = fromHandle(handle);
5881 if (excludeLayer != nullptr) {
5882 excludeLayers.emplace(excludeLayer);
5883 } else {
5884 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5885 return NAME_NOT_FOUND;
5886 }
5887 }
5888 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005889
Chia-I Wu20261cb2018-08-23 12:55:44 -07005890 // really small crop or frameScale
5891 if (reqWidth <= 0) {
5892 reqWidth = 1;
5893 }
5894 if (reqHeight <= 0) {
5895 reqHeight = 1;
5896 }
5897
Robert Carr866455f2019-04-02 16:28:26 -07005898 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5899 auto traverseLayers = [parent, childrenOnly,
5900 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005901 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5902 if (!layer->isVisible()) {
5903 return;
Robert Carr578038f2018-03-09 12:25:24 -08005904 } else if (childrenOnly && layer == parent.get()) {
5905 return;
chaviwa76b2712017-09-20 12:02:26 -07005906 }
Robert Carr866455f2019-04-02 16:28:26 -07005907
5908 sp<Layer> p = layer;
5909 while (p != nullptr) {
5910 if (excludeLayers.count(p) != 0) {
5911 return;
5912 }
5913 p = p->getParent();
5914 }
5915
chaviwa76b2712017-09-20 12:02:26 -07005916 visitor(layer);
5917 });
5918 };
Robert Carr108b2c72019-04-02 16:32:58 -07005919
5920 bool outCapturedSecureLayers = false;
5921 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5922 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005923}
5924
5925status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5926 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005927 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005928 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005929 bool useIdentityTransform,
5930 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005931 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005932
Peiyong Lin0e003c92018-09-17 11:09:51 -07005933 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005934 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5935 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005936 *outBuffer =
5937 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5938 static_cast<android_pixel_format>(reqPixelFormat), 1,
5939 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005940
Robert Carr108b2c72019-04-02 16:32:58 -07005941 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5942 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005943}
5944
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005945status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5946 TraverseLayersFunction traverseLayers,
5947 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005948 bool useIdentityTransform,
5949 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005950 // This mutex protects syncFd and captureResult for communication of the return values from the
5951 // main thread back to this Binder thread
5952 std::mutex captureMutex;
5953 std::condition_variable captureCondition;
5954 std::unique_lock<std::mutex> captureLock(captureMutex);
5955 int syncFd = -1;
5956 std::optional<status_t> captureResult;
5957
Robert Carr03480e22018-01-04 16:02:06 -08005958 const int uid = IPCThreadState::self()->getCallingUid();
5959 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5960
Dominik Laskowski8c001672018-05-30 16:52:06 -07005961 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005962 // If there is a refresh pending, bug out early and tell the binder thread to try again
5963 // after the refresh.
5964 if (mRefreshPending) {
5965 ATRACE_NAME("Skipping screenshot for now");
5966 std::unique_lock<std::mutex> captureLock(captureMutex);
5967 captureResult = std::make_optional<status_t>(EAGAIN);
5968 captureCondition.notify_one();
5969 return;
5970 }
5971
5972 status_t result = NO_ERROR;
5973 int fd = -1;
5974 {
5975 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005976 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005977 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005978 useIdentityTransform, forSystem, &fd,
5979 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005980 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005981 }
5982
5983 {
5984 std::unique_lock<std::mutex> captureLock(captureMutex);
5985 syncFd = fd;
5986 captureResult = std::make_optional<status_t>(result);
5987 captureCondition.notify_one();
5988 }
5989 });
5990
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005991 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005992 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005993 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005994 while (*captureResult == EAGAIN) {
5995 captureResult.reset();
5996 result = postMessageAsync(message);
5997 if (result != NO_ERROR) {
5998 return result;
5999 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07006000 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006001 }
6002 result = *captureResult;
6003 }
6004
6005 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006006 sync_wait(syncFd, -1);
6007 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006008 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006009
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006010 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006011}
6012
chaviwa76b2712017-09-20 12:02:26 -07006013void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006014 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006015 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6016 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006017 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006018
chaviwa76b2712017-09-20 12:02:26 -07006019 const auto reqWidth = renderArea.getReqWidth();
6020 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006021 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006022 const auto transform = renderArea.getTransform();
6023 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006024
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006025 renderengine::DisplaySettings clientCompositionDisplay;
6026 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006027
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006028 // assume that bounds are never offset, and that they are the same as the
6029 // buffer bounds.
6030 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006031 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006032 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006033
6034 // Now take into account the rotation flag. We append a transform that
6035 // rotates the layer stack about the origin, then translate by buffer
6036 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006037 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006038 int displacementX = 0;
6039 int displacementY = 0;
6040 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6041 switch (rotation) {
6042 case ui::Transform::ROT_90:
6043 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006044 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006045 break;
6046 case ui::Transform::ROT_180:
6047 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006048 displacementY = renderArea.getBounds().getWidth();
6049 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006050 break;
6051 case ui::Transform::ROT_270:
6052 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006053 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006054 break;
6055 default:
6056 break;
6057 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006058
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006059 // We need to transform the clipping window into the right spot.
6060 // First, rotate the clipping rectangle by the rotation hint to get the
6061 // right orientation
6062 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6063 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6064 const vec4 rotClipTL = rotMatrix * clipTL;
6065 const vec4 rotClipBR = rotMatrix * clipBR;
6066 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6067 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6068 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6069 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6070
6071 // Now reposition the clipping rectangle with the displacement vector
6072 // computed above.
6073 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006074 clientCompositionDisplay.clip =
6075 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6076 newClipRight + displacementX, newClipBottom + displacementY);
6077
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006078 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006079 clientCompositionDisplay.globalTransform =
6080 clipTransform * clientCompositionDisplay.globalTransform;
6081
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006082 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6083 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006084
chaviw50da5042018-04-09 13:49:37 -07006085 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006086
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006087 renderengine::LayerSettings fillLayer;
6088 fillLayer.source.buffer.buffer = nullptr;
6089 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6090 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6091 fillLayer.alpha = half(alpha);
6092 clientCompositionLayers.push_back(fillLayer);
6093
6094 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006095 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006096 renderengine::LayerSettings layerSettings;
6097 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006098 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006099 if (prepared) {
6100 clientCompositionLayers.push_back(layerSettings);
6101 }
chaviwa76b2712017-09-20 12:02:26 -07006102 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006103
6104 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006105 // Use an empty fence for the buffer fence, since we just created the buffer so
6106 // there is no need for synchronization with the GPU.
6107 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006108 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006109 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006110 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006111 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006112
6113 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006114}
6115
chaviwa76b2712017-09-20 12:02:26 -07006116status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6117 TraverseLayersFunction traverseLayers,
6118 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006119 bool useIdentityTransform, bool forSystem,
6120 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006121 ATRACE_CALL();
6122
chaviwa76b2712017-09-20 12:02:26 -07006123 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006124 outCapturedSecureLayers =
6125 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006126 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006127
Robert Carr03480e22018-01-04 16:02:06 -08006128 // We allow the system server to take screenshots of secure layers for
6129 // use in situations like the Screen-rotation animation and place
6130 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006131 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006132 ALOGW("FB is protected: PERMISSION_DENIED");
6133 return PERMISSION_DENIED;
6134 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006135 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006136 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006137}
6138
chaviw95ef3c42019-02-14 10:55:09 -08006139void SurfaceFlinger::setInputWindowsFinished() {
6140 Mutex::Autolock _l(mStateLock);
6141
6142 mPendingSyncInputWindows = false;
6143 mTransactionCV.broadcast();
6144}
chaviw5f21a5e2019-02-14 10:00:34 -08006145
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006146// ---------------------------------------------------------------------------
6147
Dan Stoza412903f2017-04-27 13:42:17 -07006148void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6149 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006150}
6151
Dan Stoza412903f2017-04-27 13:42:17 -07006152void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6153 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006154}
6155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006156void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006157 const LayerVector::Visitor& visitor) {
6158 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006159 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006160 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006161 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006162 continue;
6163 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006164 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006165 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006166 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006167 return;
6168 }
chaviwa76b2712017-09-20 12:02:26 -07006169 if (!layer->isVisible()) {
6170 return;
6171 }
6172 visitor(layer);
6173 });
6174 }
6175}
6176
Dominik Laskowski22488f62019-03-28 09:53:04 -07006177void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6178 const std::vector<int32_t>& allowedConfigs) {
6179 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006180 return;
6181 }
6182
6183 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006184 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006185
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006186 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006187 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006188 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006189 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006190 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006191 setDesiredActiveConfig(
6192 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006193 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006194 }
6195 }
Ady Abraham838de062019-02-04 10:24:03 -08006196}
6197
Dominik Laskowski22488f62019-03-28 09:53:04 -07006198status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006199 const std::vector<int32_t>& allowedConfigs) {
6200 ATRACE_CALL();
6201
Dominik Laskowski22488f62019-03-28 09:53:04 -07006202 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006203 return BAD_VALUE;
6204 }
6205
Ady Abraham34392f72019-04-10 11:29:27 -07006206 if (mDebugDisplayConfigSetByBackdoor) {
6207 // ignore this request as config is overridden by backdoor
6208 return NO_ERROR;
6209 }
6210
Ady Abraham838de062019-02-04 10:24:03 -08006211 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006212 const auto display = getDisplayDeviceLocked(displayToken);
6213 if (!display) {
6214 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6215 displayToken.get());
6216 } else if (display->isVirtual()) {
6217 ALOGW("Attempt to set allowed display configs for virtual display");
6218 } else {
6219 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6220 }
Ady Abraham838de062019-02-04 10:24:03 -08006221 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006222
Ady Abraham838de062019-02-04 10:24:03 -08006223 return NO_ERROR;
6224}
6225
Dominik Laskowski22488f62019-03-28 09:53:04 -07006226status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006227 std::vector<int32_t>* outAllowedConfigs) {
6228 ATRACE_CALL();
6229
Dominik Laskowski22488f62019-03-28 09:53:04 -07006230 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006231 return BAD_VALUE;
6232 }
6233
Dominik Laskowski22488f62019-03-28 09:53:04 -07006234 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006235
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006236 const auto display = getDisplayDeviceLocked(displayToken);
6237 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006238 return NAME_NOT_FOUND;
6239 }
6240
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006241 if (display->isPrimary()) {
6242 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6243 }
6244
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006245 return NO_ERROR;
6246}
6247
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006248void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006249 mFlinger->setInputWindowsFinished();
6250}
6251
Robert Carrc0df3122019-04-11 13:18:21 -07006252sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6253 BBinder *b = handle->localBinder();
6254 if (b == nullptr) {
6255 return nullptr;
6256 }
6257 auto it = mLayersByLocalBinderToken.find(b);
6258 if (it != mLayersByLocalBinderToken.end()) {
6259 return it->second.promote();
6260 }
6261 return nullptr;
6262}
6263
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006264} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006265
Mathias Agopian3f844832013-08-07 21:24:32 -07006266#if defined(__gl_h_)
6267#error "don't include gl/gl.h in this file"
6268#endif
6269
6270#if defined(__gl2_h_)
6271#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006272#endif