blob: dd0890c8207c08d5f464dbbf2c20dc75296fe4d7 [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 Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/Layer.h>
45#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070046#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080047#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070048#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080049#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080050#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070052#include <gui/DebugEGLImageTracker.h>
53
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070055#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080056#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080057#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070060#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <ui/ColorSpace.h>
62#include <ui/DebugUtils.h>
63#include <ui/DisplayInfo.h>
64#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070065#include <ui/GraphicBufferAllocator.h>
66#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070067#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/String16.h>
70#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070071#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080072#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070073#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopian921e6ac2012-07-23 23:11:29 -070075#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070076#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Robert Carr578038f2018-03-09 12:25:24 -080078#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070079#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070080#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020083#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080084#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070087#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080088#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070089#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070090#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070091#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094
Steven Thomasb02664d2017-07-26 18:48:28 -070095#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070096#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070097#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070098#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070099#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700100#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700101#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700103#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104#include "Scheduler/EventControlThread.h"
105#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700106#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700107#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700108#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700109#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800110#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700111
Mathias Agopianff2ed702013-09-01 21:36:12 -0700112#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700113
David Sodman7e4ae112018-02-09 15:02:28 -0800114#include "android-base/stringprintf.h"
115
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800117#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
118#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700119#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900120#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121
chaviw1d044282017-09-27 12:19:28 -0700122#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
242 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
259 mTimeStats(mFactory.createTimeStats()),
260 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700261 mCompositionEngine(mFactory.createCompositionEngine()),
262 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900267 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 mDefaultCompositionDataspace =
285 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700286 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
287 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 defaultCompositionDataspace = mDefaultCompositionDataspace;
289 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
290 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
291 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
292 wideColorGamutCompositionPixelFormat =
293 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294
Yichi Chenda901bf2019-06-28 14:58:27 +0800295 mColorSpaceAgnosticDataspace =
296 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
301 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
302 switch (tmpPrimaryDisplayOrientation) {
303 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700304 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800305 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700307 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800308 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700310 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
312 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700313 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
315 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700316 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800317
Sundong Ahn85131bd2019-02-18 15:51:53 +0900318 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 // debugging stuff...
321 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700322
Mathias Agopianb4b17302013-03-20 18:36:41 -0700323 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700324 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 property_get("debug.sf.showupdates", value, "0");
327 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700328
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700329 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000330
331 // DDMS debugging deprecated (b/120782499)
332 property_get("debug.sf.ddms", value, "0");
333 int debugDdms = atoi(value);
334 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700335
336 property_get("debug.sf.disable_backpressure", value, "0");
337 mPropagateBackpressure = !atoi(value);
338 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700339
Ady Abraham4658e112019-07-22 13:07:26 -0700340 property_get("debug.sf.enable_gl_backpressure", value, "0");
341 mPropagateBackpressureClientComposition = atoi(value);
342 ALOGI_IF(mPropagateBackpressureClientComposition,
343 "Enabling backpressure propagation for Client Composition");
344
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800345 property_get("debug.sf.enable_hwc_vds", value, "0");
346 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800347 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800348
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800349 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800350 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800351 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700352
Yiwei Zhang243b3782018-05-15 17:40:04 -0700353 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700354 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
355 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
356
Ana Krulece5a06e02019-03-06 17:09:03 -0800357 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800358 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800359
360 int int_value = atoi(value);
361 if (int_value) {
362 mUseSmart90ForVideo = true;
363 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800364
Dan Stozaec460082018-12-17 15:35:09 -0800365 property_get("debug.sf.luma_sampling", value, "1");
366 mLumaSampling = atoi(value);
367
Romain Guy11d63f42017-07-20 12:47:14 -0700368 // We should be reading 'persist.sys.sf.color_saturation' here
369 // but since /data may be encrypted, we need to wait until after vold
370 // comes online to attempt to read the property. The property is
371 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800372
373 if (useTrebleTestingOverride()) {
374 // Without the override SurfaceFlinger cannot connect to HIDL
375 // services that are not listed in the manifests. Considered
376 // deriving the setting from the set service name, but it
377 // would be brittle if the name that's not 'default' is used
378 // for production purposes later on.
379 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381}
382
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800383void SurfaceFlinger::onFirstRef()
384{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800385 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386}
387
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700388SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389
Dan Stozac7014012014-02-14 15:03:43 -0800390void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800391{
392 // the window manager died on us. prepare its eulogy.
393
Andy McFadden13a082e2012-08-24 10:16:42 -0700394 // restore initial conditions (default device unblank, etc)
395 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800396
397 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399}
400
Robert Carr1db73f62016-12-21 12:58:51 -0800401static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700402 status_t err = client->initCheck();
403 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800404 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 }
Robert Carr1db73f62016-12-21 12:58:51 -0800406 return nullptr;
407}
408
409sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
410 return initClient(new Client(this));
411}
412
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700413sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
414 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415{
416 class DisplayToken : public BBinder {
417 sp<SurfaceFlinger> flinger;
418 virtual ~DisplayToken() {
419 // no more references, this display must be terminated
420 Mutex::Autolock _l(flinger->mStateLock);
421 flinger->mCurrentState.displays.removeItem(this);
422 flinger->setTransactionFlags(eDisplayTransactionNeeded);
423 }
424 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700425 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700426 : flinger(flinger) {
427 }
428 };
429
430 sp<BBinder> token = new DisplayToken(this);
431
432 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700433 // Display ID is assigned when virtual display is allocated by HWC.
434 DisplayDeviceState state;
435 state.isSecure = secure;
436 state.displayName = displayName;
437 mCurrentState.displays.add(token, state);
438 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 return token;
440}
441
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700442void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700443 Mutex::Autolock _l(mStateLock);
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
446 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700447 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700448 return;
449 }
450
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
452 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700453 ALOGE("destroyDisplay called for non-virtual display");
454 return;
455 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700456 mInterceptor->saveDisplayDeletion(state.sequenceId);
457 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 setTransactionFlags(eDisplayTransactionNeeded);
459}
460
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800461std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
462 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800464 const auto internalDisplayId = getInternalDisplayIdLocked();
465 if (!internalDisplayId) {
466 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 }
468
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800469 std::vector<PhysicalDisplayId> displayIds;
470 displayIds.reserve(mPhysicalDisplayTokens.size());
471 displayIds.push_back(internalDisplayId->value);
472
473 for (const auto& [id, token] : mPhysicalDisplayTokens) {
474 if (id != *internalDisplayId) {
475 displayIds.push_back(id.value);
476 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479 return displayIds;
480}
481
482sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
483 Mutex::Autolock lock(mStateLock);
484 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485}
486
Ady Abraham37965d42018-11-01 13:43:32 -0700487status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
488 if (!outGetColorManagement) {
489 return BAD_VALUE;
490 }
491 *outGetColorManagement = useColorManagement;
492 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700493}
494
Lloyd Pique441d5042018-10-18 16:49:51 -0700495HWComposer& SurfaceFlinger::getHwComposer() const {
496 return mCompositionEngine->getHwComposer();
497}
498
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700499renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
500 return mCompositionEngine->getRenderEngine();
501}
502
Lloyd Pique70d91362018-10-18 16:02:55 -0700503compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
504 return *mCompositionEngine.get();
505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700516 mTimeStats->initializeTracing();
517
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700518 // wait patiently for the window manager death
519 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700520 mWindowManager = defaultServiceManager()->getService(name);
521 if (mWindowManager != 0) {
522 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523 }
Robert Carr720e5062018-07-30 17:45:14 -0700524 sp<IBinder> input(defaultServiceManager()->getService(
525 String16("inputflinger")));
526 if (input == nullptr) {
527 ALOGE("Failed to link to input service");
528 } else {
529 mInputFlinger = interface_cast<IInputFlinger>(input);
530 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531
Steven Thomas050b2c82017-03-06 11:45:16 -0800532 if (mVrFlinger) {
533 mVrFlinger->OnBootFinished();
534 }
535
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700537 // formerly we would just kill the process, but we now ask it to exit so it
538 // can choose where to stop the animation.
539 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700540
541 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
542 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
543 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700544
Ana Krulecbd6654b2019-02-15 15:18:15 -0800545 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800546 readPersistentProperties();
547 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800548
Ady Abraham97d04232019-03-05 19:48:12 -0800549 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700550 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700551 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800552
Dominik Laskowski22488f62019-03-28 09:53:04 -0700553 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800554 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800556 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800557 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800558 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800559}
560
Dan Stoza436ccf32018-06-21 12:10:12 -0700561uint32_t SurfaceFlinger::getNewTexture() {
562 {
563 std::lock_guard lock(mTexturePoolMutex);
564 if (!mTexturePool.empty()) {
565 uint32_t name = mTexturePool.back();
566 mTexturePool.pop_back();
567 ATRACE_INT("TexturePoolSize", mTexturePool.size());
568 return name;
569 }
570
571 // The pool was too small, so increase it for the future
572 ++mTexturePoolSize;
573 }
574
575 // The pool was empty, so we need to get a new texture name directly using a
576 // blocking call to the main thread
577 uint32_t name = 0;
578 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
579 return name;
580}
581
Mathias Agopian3f844832013-08-07 21:24:32 -0700582void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700583 std::lock_guard lock(mTexturePoolMutex);
584 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
585 // to actually delete this or not based on mTexturePoolSize
586 mTexturePool.push_back(texture);
587 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700588}
589
Wei Wangf9b05ee2017-07-19 20:59:39 -0700590// Do not call property_set on main thread which will be blocked by init
591// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700592void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700593 ALOGI( "SurfaceFlinger's main thread ready to run. "
594 "Initializing graphics H/W...");
595
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700596 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800600 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700601 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
602 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800603 auto resyncCallback =
604 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800605
Ana Krulecc2870422019-01-29 19:00:58 -0800606 mAppConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700607 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700608 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800609 resyncCallback,
610 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700611 mSfConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700612 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700613 mPhaseOffsets->getOffsetThresholdForNextVsync(),
614 resyncCallback, [this](nsecs_t timestamp) {
615 mInterceptor->saveVSyncEvent(timestamp);
616 });
Ana Krulecc2870422019-01-29 19:00:58 -0800617
618 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700619
620 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
621 mPhaseOffsets->getCurrentOffsets());
Ana Krulecc2870422019-01-29 19:00:58 -0800622
Kevin DuBois413287f2019-02-25 08:46:47 -0800623 mRegionSamplingThread =
624 new RegionSamplingThread(*this, *mScheduler,
625 RegionSamplingThread::EnvironmentTimingTunables());
626
Steven Thomasb02664d2017-07-26 18:48:28 -0700627 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700628 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700629 renderEngineFeature |= (useColorManagement ?
630 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700631 renderEngineFeature |= (useContextPriority ?
632 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700633 renderEngineFeature |=
634 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
635 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700636
637 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800638 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700639 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700640 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800641 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700642
643 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
644 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700645 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
646 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800647 // Process any initial hotplug and resulting display changes.
648 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700649 const auto display = getDefaultDisplayDeviceLocked();
650 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700651 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700652 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800653
Steven Thomas050b2c82017-03-06 11:45:16 -0800654 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700656 // This callback is called from the vr flinger dispatch thread. We
657 // need to call signalTransaction(), which requires holding
658 // mStateLock when we're not on the main thread. Acquiring
659 // mStateLock from the vr flinger dispatch thread might trigger a
660 // deadlock in surface flinger (see b/66916578), so post a message
661 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700662 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700663 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
664 mVrFlingerRequestsDisplay = requestDisplay;
665 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700666 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800667 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700668 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
669 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700670 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 .value_or(0),
672 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 if (!mVrFlinger) {
674 ALOGE("Failed to start vrflinger");
675 }
676 }
677
Mathias Agopian92a979a2012-08-02 18:32:23 -0700678 // initialize our drawing state
679 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700680
Andy McFadden13a082e2012-08-24 10:16:42 -0700681 // set initial conditions (e.g. unblank default device)
682 initializeDisplays();
683
Steven Thomas137d4bc2019-07-25 16:55:14 -0700684 char primeShaderCache[PROPERTY_VALUE_MAX];
685 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
686 if (atoi(primeShaderCache)) {
687 getRenderEngine().primeCache();
688 }
Dan Stoza4e637772016-07-28 13:31:51 -0700689
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700691
692 const bool presentFenceReliable =
693 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
694 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700695
696 if (mStartPropertySetThread->Start() != NO_ERROR) {
697 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800698 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699
Alec Mouri93bc83d2019-04-17 14:47:43 -0700700 mScheduler->setChangeRefreshRateCallback(
701 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
702 Mutex::Autolock lock(mStateLock);
703 setRefreshRateTo(type, event);
704 });
Alec Mouri7f015182019-07-11 13:56:22 -0700705 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
706 Mutex::Autolock lock(mStateLock);
707 const auto display = getDefaultDisplayDeviceLocked();
708 if (!display) {
709 // If we don't have a default display the fallback to the default
710 // refresh rate type
711 return RefreshRateType::DEFAULT;
712 }
713
714 const int configId = display->getActiveConfig();
715 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
716 if (refresh && refresh->configId == configId) {
717 return type;
718 }
719 }
720 // This should never happen, but just gracefully fallback to default.
721 return RefreshRateType::DEFAULT;
722 });
Alec Mouridc28b372019-04-18 21:17:13 -0700723 mScheduler->setGetVsyncPeriodCallback([this] {
724 Mutex::Autolock lock(mStateLock);
725 return getVsyncPeriod();
726 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700727
Dominik Laskowski22488f62019-03-28 09:53:04 -0700728 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
729 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800730
Dan Stoza9e56aa02015-11-02 13:00:03 -0800731 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700732}
733
Romain Guy11d63f42017-07-20 12:47:14 -0700734void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700735 Mutex::Autolock _l(mStateLock);
736
Romain Guy11d63f42017-07-20 12:47:14 -0700737 char value[PROPERTY_VALUE_MAX];
738
739 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800740 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800742 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100743
744 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700745 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800746
747 property_get("persist.sys.sf.color_mode", value, "0");
748 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700749}
750
Mathias Agopiana67e4182012-06-19 17:26:12 -0700751void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800752 // Start boot animation service by setting a property mailbox
753 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700756 if (mStartPropertySetThread->join() != NO_ERROR) {
757 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800758 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700759}
760
Mathias Agopian875d8e12013-06-07 15:35:48 -0700761size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700762 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700763}
764
Mathias Agopian875d8e12013-06-07 15:35:48 -0700765size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700766 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700767}
768
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800769// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800770
Jamie Gennis582270d2011-08-17 18:19:00 -0700771bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800772 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800773 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800774 return authenticateSurfaceTextureLocked(bufferProducer);
775}
776
777bool SurfaceFlinger::authenticateSurfaceTextureLocked(
778 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800779 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800780 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800781}
782
Brian Anderson6b376712017-04-04 10:51:39 -0700783status_t SurfaceFlinger::getSupportedFrameTimestamps(
784 std::vector<FrameEvent>* outSupported) const {
785 *outSupported = {
786 FrameEvent::REQUESTED_PRESENT,
787 FrameEvent::ACQUIRE,
788 FrameEvent::LATCH,
789 FrameEvent::FIRST_REFRESH_START,
790 FrameEvent::LAST_REFRESH_START,
791 FrameEvent::GPU_COMPOSITION_DONE,
792 FrameEvent::DEQUEUE_READY,
793 FrameEvent::RELEASE,
794 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700795 ConditionalLock _l(mStateLock,
796 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700797 if (!getHwComposer().hasCapability(
798 HWC2::Capability::PresentFenceIsNotReliable)) {
799 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
800 }
801 return NO_ERROR;
802}
803
Dominik Laskowski22488f62019-03-28 09:53:04 -0700804status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
805 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700806 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 return BAD_VALUE;
808 }
809
Dominik Laskowski22488f62019-03-28 09:53:04 -0700810 Mutex::Autolock lock(mStateLock);
811
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800812 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 if (!displayId) {
814 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700815 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817 // TODO: Not sure if display density should handled by SF any longer
818 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700819 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700821 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800822 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700823 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 }
825 return density;
826 }
827 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700830 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 return getDensityFromProperty("ro.sf.lcd_density"); }
832 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dan Stoza7f7da322014-05-02 15:26:25 -0700834 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dominik Laskowski075d3172018-05-24 15:50:06 -0700836 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 DisplayInfo info = DisplayInfo();
838
Dan Stoza9e56aa02015-11-02 13:00:03 -0800839 float xdpi = hwConfig->getDpiX();
840 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700841
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700842 info.w = hwConfig->getWidth();
843 info.h = hwConfig->getHeight();
844 // Default display viewport to display width and height
845 info.viewportW = info.w;
846 info.viewportH = info.h;
847
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800848 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 // The density of the device is provided by a build property
850 float density = Density::getBuildDensity() / 160.0f;
851 if (density == 0) {
852 // the build doesn't provide a density -- this is wrong!
853 // use xdpi instead
854 ALOGE("ro.sf.lcd_density must be defined as a build property");
855 density = xdpi / 160.0f;
856 }
857 if (Density::getEmuDensity()) {
858 // if "qemu.sf.lcd_density" is specified, it overrides everything
859 xdpi = ydpi = density = Density::getEmuDensity();
860 density /= 160.0f;
861 }
862 info.density = density;
863
864 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700865 const auto display = getDefaultDisplayDeviceLocked();
866 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700867
868 // This is for screenrecord
869 const Rect viewport = display->getViewport();
870 if (viewport.isValid()) {
871 info.viewportW = uint32_t(viewport.getWidth());
872 info.viewportH = uint32_t(viewport.getHeight());
873 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700874 } else {
875 // TODO: where should this value come from?
876 static const int TV_DENSITY = 213;
877 info.density = TV_DENSITY / 160.0f;
878 info.orientation = 0;
879 }
880
Dan Stoza7f7da322014-05-02 15:26:25 -0700881 info.xdpi = xdpi;
882 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700884 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
885 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
886 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800887
Andy McFadden91b2ca82014-06-13 14:04:23 -0700888 // This is how far in advance a buffer must be queued for
889 // presentation at a given time. If you want a buffer to appear
890 // on the screen at time N, you must submit the buffer before
891 // (N - presentationDeadline).
892 //
893 // Normally it's one full refresh period (to give SF a chance to
894 // latch the buffer), but this can be reduced by configuring a
895 // DispSync offset. Any additional delays introduced by the hardware
896 // composer or panel must be accounted for here.
897 //
898 // We add an additional 1ms to allow for processing time and
899 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700900 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700901
902 // All non-virtual displays are currently considered secure.
903 info.secure = true;
904
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800905 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700906 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800907 std::swap(info.w, info.h);
908 }
909
Michael Wright28f24d02016-07-12 13:30:53 -0700910 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700911 }
912
Dan Stoza7f7da322014-05-02 15:26:25 -0700913 return NO_ERROR;
914}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700915
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700916status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
917 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700918 return BAD_VALUE;
919 }
920
Ana Krulecc2870422019-01-29 19:00:58 -0800921 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return NO_ERROR;
923}
924
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700925int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
926 const auto display = getDisplayDevice(displayToken);
927 if (!display) {
928 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800929 return BAD_VALUE;
930 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Ady Abraham03b02dd2019-03-21 15:40:11 -0700935void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800937
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800939 // config twice. However event generation config might have changed so we need to update it
940 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800941 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700942 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
943 mDesiredActiveConfig = info;
944 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945
946 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800947 // This will trigger HWC refresh without resetting the idle timer.
948 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700949 // Start receiving vsync samples now, so that we can detect a period
950 // switch.
951 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700952 // As we called to set period, we will call to onRefreshRateChangeCompleted once
953 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700954 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700955 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700956 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800957 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700959
960 if (mRefreshRateOverlay) {
961 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
962 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800963}
964
965status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
966 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800967
968 std::vector<int32_t> allowedConfig;
969 allowedConfig.push_back(mode);
970
971 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972}
973
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974void SurfaceFlinger::setActiveConfigInternal() {
975 ATRACE_CALL();
976
Dominik Laskowski22488f62019-03-28 09:53:04 -0700977 const auto display = getDefaultDisplayDeviceLocked();
978 if (!display) {
979 return;
980 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981
Dominik Laskowski22488f62019-03-28 09:53:04 -0700982 std::lock_guard<std::mutex> lock(mActiveConfigLock);
983 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
984
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 display->setActiveConfig(mUpcomingActiveConfig.configId);
986
Alec Mouri754c98a2019-03-18 18:53:42 -0700987 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700988 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700990
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800991 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800992 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
993 mUpcomingActiveConfig.configId);
994 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995}
996
Ady Abraham53852a52019-05-28 18:07:44 -0700997void SurfaceFlinger::desiredActiveConfigChangeDone() {
998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1000 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001001
1002 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1003 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001004 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001005}
1006
Dominik Laskowski22488f62019-03-28 09:53:04 -07001007bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001008 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001010 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001012 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 return true;
1014 }
1015
1016 // We received the present fence from the HWC, so we assume it successfully updated
1017 // the config, hence we update SF.
1018 mCheckPendingFence = false;
1019 setActiveConfigInternal();
1020 }
1021
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001022 // Store the local variable to release the lock.
1023 ActiveConfigInfo desiredActiveConfig;
1024 {
1025 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 if (!mDesiredActiveConfigChanged) {
1027 return false;
1028 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001029 desiredActiveConfig = mDesiredActiveConfig;
1030 }
1031
Dominik Laskowski22488f62019-03-28 09:53:04 -07001032 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001033 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1034 // display is not valid or we are already in the requested mode
1035 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001036 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001038 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039
Ady Abraham838de062019-02-04 10:24:03 -08001040 // Desired active config was set, it is different than the config currently in use, however
1041 // allowed configs might have change by the time we process the refresh.
1042 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001043 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001044 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001045 return false;
1046 }
Alec Mouri7f015182019-07-11 13:56:22 -07001047
Ady Abrahamb838aed2019-02-12 15:30:16 -08001048 mUpcomingActiveConfig = desiredActiveConfig;
1049 const auto displayId = display->getId();
1050 LOG_ALWAYS_FATAL_IF(!displayId);
1051
1052 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1053 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1054
1055 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001057 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001059}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001060
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001061status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1062 Vector<ColorMode>* outColorModes) {
1063 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 return BAD_VALUE;
1065 }
1066
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001068 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001069 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001070 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1071
1072 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1073 if (!displayId) {
1074 return NAME_NOT_FOUND;
1075 }
1076
Dominik Laskowski075d3172018-05-24 15:50:06 -07001077 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001078 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001081
1082 // If it's built-in display and the configuration claims it's not wide color capable,
1083 // filter out all wide color modes. The typical reason why this happens is that the
1084 // hardware is not good enough to support GPU composition of wide color, and thus the
1085 // OEMs choose to disable this capability.
1086 if (isInternalDisplay && !hasWideColorDisplay) {
1087 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1088 isWideColorMode);
1089 } else {
1090 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1091 }
Michael Wright28f24d02016-07-12 13:30:53 -07001092
1093 return NO_ERROR;
1094}
1095
Daniel Solomon42d04562019-01-20 21:03:19 -08001096status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1097 ui::DisplayPrimaries &primaries) {
1098 if (!displayToken) {
1099 return BAD_VALUE;
1100 }
1101
1102 // Currently we only support this API for a single internal display.
1103 if (getInternalDisplayToken() != displayToken) {
1104 return BAD_VALUE;
1105 }
1106
1107 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1108 return NO_ERROR;
1109}
1110
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1112 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001113 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001114 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001115 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001119 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120 Vector<ColorMode> modes;
1121 getDisplayColorModes(displayToken, &modes);
1122 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1123 if (mode < ColorMode::NATIVE || !exists) {
1124 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001127 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const auto display = getDisplayDevice(displayToken);
1129 if (!display) {
1130 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1131 decodeColorMode(mode).c_str(), mode, displayToken.get());
1132 } else if (display->isVirtual()) {
1133 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1134 decodeColorMode(mode).c_str(), mode);
1135 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001136 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
Lloyd Piquef5275482019-01-29 18:42:42 -08001137 RenderIntent::COLORIMETRIC,
1138 Dataspace::UNKNOWN);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139 }
1140 }));
1141
Michael Wright28f24d02016-07-12 13:30:53 -07001142 return NO_ERROR;
1143}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001144
Svetoslavd85084b2014-03-20 10:28:31 -07001145status_t SurfaceFlinger::clearAnimationFrameStats() {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.clearStats();
1148 return NO_ERROR;
1149}
1150
1151status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1152 Mutex::Autolock _l(mStateLock);
1153 mAnimFrameTracker.getStats(outStats);
1154 return NO_ERROR;
1155}
1156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1158 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001159 Mutex::Autolock _l(mStateLock);
1160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161 const auto display = getDisplayDeviceLocked(displayToken);
1162 if (!display) {
1163 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001164 return BAD_VALUE;
1165 }
1166
Peiyong Linfb069302018-04-25 14:34:31 -07001167 // At this point the DisplayDeivce should already be set up,
1168 // meaning the luminance information is already queried from
1169 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001170 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001171 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1172 capabilities.getDesiredMaxLuminance(),
1173 capabilities.getDesiredMaxAverageLuminance(),
1174 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001175
1176 return NO_ERROR;
1177}
1178
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001179status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1180 ui::PixelFormat* outFormat,
1181 ui::Dataspace* outDataspace,
1182 uint8_t* outComponentMask) const {
1183 if (!outFormat || !outDataspace || !outComponentMask) {
1184 return BAD_VALUE;
1185 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001186 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001187 if (!display || !display->getId()) {
1188 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1189 return BAD_VALUE;
1190 }
1191 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1192 outDataspace, outComponentMask);
1193}
1194
Kevin DuBois74e53772018-11-19 10:52:38 -08001195status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1196 bool enable, uint8_t componentMask,
1197 uint64_t maxFrames) const {
1198 const auto display = getDisplayDevice(displayToken);
1199 if (!display || !display->getId()) {
1200 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1201 return BAD_VALUE;
1202 }
1203
1204 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1205 componentMask, maxFrames);
1206}
1207
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001208status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1209 uint64_t maxFrames, uint64_t timestamp,
1210 DisplayedFrameStats* outStats) const {
1211 const auto display = getDisplayDevice(displayToken);
1212 if (!display || !display->getId()) {
1213 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1214 return BAD_VALUE;
1215 }
1216
1217 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1218 outStats);
1219}
1220
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001221status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1222 if (!outSupported) {
1223 return BAD_VALUE;
1224 }
1225 *outSupported = getRenderEngine().supportsProtectedContent();
1226 return NO_ERROR;
1227}
1228
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001229status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1230 bool* outIsWideColorDisplay) const {
1231 if (!displayToken || !outIsWideColorDisplay) {
1232 return BAD_VALUE;
1233 }
1234 Mutex::Autolock _l(mStateLock);
1235 const auto display = getDisplayDeviceLocked(displayToken);
1236 if (!display) {
1237 return BAD_VALUE;
1238 }
Peiyong Linff84a152019-05-17 18:36:19 -07001239
1240 // Use hasWideColorDisplay to override built-in display.
1241 const auto displayId = display->getId();
1242 if (displayId && displayId == getInternalDisplayIdLocked()) {
1243 *outIsWideColorDisplay = hasWideColorDisplay;
1244 return NO_ERROR;
1245 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001246 *outIsWideColorDisplay = display->hasWideColorGamut();
1247 return NO_ERROR;
1248}
1249
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001250status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001251 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001253
Chia-I Wu90f669f2017-10-05 14:24:41 -07001254 if (mInjectVSyncs == enable) {
1255 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001256 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001257
Ana Krulecc2870422019-01-29 19:00:58 -08001258 auto resyncCallback =
1259 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001260
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001261 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001262 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001263 if (enable) {
1264 ALOGV("VSync Injections enabled");
1265 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001266 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001267 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001268 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001269 impl::EventThread::InterceptVSyncsCallback(),
1270 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001272 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001273 } else {
1274 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001275 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1276 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277 }
1278
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001279 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001280 }));
1281
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001282 return NO_ERROR;
1283}
1284
1285status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001286 Mutex::Autolock _l(mStateLock);
1287
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001288 if (!mInjectVSyncs) {
1289 ALOGE("VSync Injections not enabled");
1290 return BAD_VALUE;
1291 }
1292 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1293 ALOGV("Injecting VSync inside SurfaceFlinger");
1294 mVSyncInjector->onInjectSyncEvent(when);
1295 }
1296 return NO_ERROR;
1297}
1298
Lloyd Pique755e3192018-01-31 16:46:15 -08001299status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1300 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001301 // Try to acquire a lock for 1s, fail gracefully
1302 const status_t err = mStateLock.timedLock(s2ns(1));
1303 const bool locked = (err == NO_ERROR);
1304 if (!locked) {
1305 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1306 return TIMED_OUT;
1307 }
1308
1309 outLayers->clear();
1310 mCurrentState.traverseInZOrder([&](Layer* layer) {
1311 outLayers->push_back(layer->getLayerDebugInfo());
1312 });
1313
1314 mStateLock.unlock();
1315 return NO_ERROR;
1316}
1317
Peiyong Linc6780972018-10-28 15:24:08 -07001318status_t SurfaceFlinger::getCompositionPreference(
1319 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1320 Dataspace* outWideColorGamutDataspace,
1321 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001322 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001323 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001324 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001325 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001326 return NO_ERROR;
1327}
1328
Dan Stozaec460082018-12-17 15:35:09 -08001329status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1330 const sp<IBinder>& stopLayerHandle,
1331 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001332 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001333 return BAD_VALUE;
1334 }
1335 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001336 return NO_ERROR;
1337}
1338
Dan Stozaec460082018-12-17 15:35:09 -08001339status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001340 if (!listener) {
1341 return BAD_VALUE;
1342 }
Dan Stozaec460082018-12-17 15:35:09 -08001343 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001344 return NO_ERROR;
1345}
Dan Gittik57e63c52019-01-18 16:37:54 +00001346
1347status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1348 bool* outSupport) const {
1349 if (!displayToken || !outSupport) {
1350 return BAD_VALUE;
1351 }
1352 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1353 if (!displayId) {
1354 return NAME_NOT_FOUND;
1355 }
1356 *outSupport =
1357 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1358 return NO_ERROR;
1359}
1360
1361status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1362 float brightness) const {
1363 if (!displayToken) {
1364 return BAD_VALUE;
1365 }
1366 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1367 if (!displayId) {
1368 return NAME_NOT_FOUND;
1369 }
1370 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1371}
1372
Ady Abraham8532d012019-05-08 14:50:56 -07001373status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1374 PowerHint powerHint = static_cast<PowerHint>(hintId);
1375
1376 if (powerHint == PowerHint::INTERACTION) {
1377 mScheduler->notifyTouchEvent();
1378 }
1379
1380 return NO_ERROR;
1381}
1382
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001383// ----------------------------------------------------------------------------
1384
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001385sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001386 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001387 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001388 Mutex::Autolock lock(mStateLock);
1389 return getVsyncPeriod();
1390 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001391
Ana Krulecc2870422019-01-29 19:00:58 -08001392 const auto& handle =
1393 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001394
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001395 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1396 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001397}
1398
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001399// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001400
1401void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001402 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001403}
1404
1405void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001406 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001407 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001408}
1409
1410void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001411 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001412 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001413}
1414
1415void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001416 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001417 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001418}
1419
1420status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001421 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001422 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423}
1424
1425status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001426 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001427 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428 if (res == NO_ERROR) {
1429 msg->wait();
1430 }
1431 return res;
1432}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001433
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001434void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001435 do {
1436 waitForEvent();
1437 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001438}
1439
Dominik Laskowski83b88212018-12-11 13:34:06 -08001440nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001441 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001442 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1443 return 0;
1444 }
1445
1446 const auto config = getHwComposer().getActiveConfig(*displayId);
1447 return config ? config->getVsyncPeriod() : 0;
1448}
1449
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001450void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1451 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001452 ATRACE_NAME("SF onVsync");
1453
Steven Thomas3cfac282017-02-06 12:29:30 -08001454 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001456 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 return;
1458 }
1459
Dominik Laskowski075d3172018-05-24 15:50:06 -07001460 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001461 return;
1462 }
1463
Dominik Laskowski075d3172018-05-24 15:50:06 -07001464 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001465 // For now, we don't do anything with external display vsyncs.
1466 return;
1467 }
1468
Alec Mourif8e689c2019-05-20 18:32:22 -07001469 bool periodFlushed = false;
1470 mScheduler->addResyncSample(timestamp, &periodFlushed);
1471 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001472 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001473 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001474}
1475
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001476void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001477 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1478 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479}
1480
Ady Abraham261614e2019-07-10 17:53:12 -07001481bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001482 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001483}
1484
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001485void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001486 const auto display = getDefaultDisplayDeviceLocked();
1487 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001488 return;
1489 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001490 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001491
Ana Krulec7d1d6832018-12-27 11:10:09 -08001492 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001493 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001494 if (!refreshRateConfig) {
1495 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001496 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001497 }
Ady Abraham1902d072019-03-01 17:18:59 -08001498
Alec Mouri0a1cc962019-03-14 12:33:02 -07001499 const int desiredConfigId = refreshRateConfig->configId;
1500
Dominik Laskowski22488f62019-03-28 09:53:04 -07001501 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001502 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1503 return;
1504 }
1505
Dominik Laskowski22488f62019-03-28 09:53:04 -07001506 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001507}
1508
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001509void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001510 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001511 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001512 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001513
Lloyd Piqueba04e622017-12-14 17:11:26 -08001514 // Ignore events that do not have the right sequenceId.
1515 if (sequenceId != getBE().mComposerSequenceId) {
1516 return;
1517 }
1518
Steven Thomasb02664d2017-07-26 18:48:28 -07001519 // Only lock if we're not on the main thread. This function is normally
1520 // called on a hwbinder thread, but for the primary display it's called on
1521 // the main thread with the state lock already held, so don't attempt to
1522 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001523 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001524
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001525 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001526
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001527 if (std::this_thread::get_id() == mMainThreadId) {
1528 // Process all pending hot plug events immediately if we are on the main thread.
1529 processDisplayHotplugEventsLocked();
1530 }
1531
Lloyd Piqueba04e622017-12-14 17:11:26 -08001532 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001533}
1534
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001535void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001536 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001537 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001538 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001539 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001540 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001541}
1542
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001543void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001544 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001545
1546 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1547 // display power state.
1548 postMessageAsync(new LambdaMessage(
1549 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1550}
1551
1552void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1553 ATRACE_CALL();
1554
Ady Abraham27c70212019-06-11 10:52:26 -07001555 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1556
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001557 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001558 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1559 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001560 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001561 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001562 }
Mathias Agopian86303202012-07-24 22:46:10 -07001563}
1564
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001566void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001567 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001568 // Clear the drawing state so that the logic inside of
1569 // handleTransactionLocked will fire. It will determine the delta between
1570 // mCurrentState and mDrawingState and re-apply all changes when we make the
1571 // transition.
1572 mDrawingState.displays.clear();
1573 mDisplays.clear();
1574}
1575
Steven Thomas050b2c82017-03-06 11:45:16 -08001576void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001577 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001578 if (!mVrFlinger)
1579 return;
1580 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001581 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001582 return;
1583 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001584
Lloyd Pique441d5042018-10-18 16:49:51 -07001585 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001586 ALOGE("Vr flinger is only supported for remote hardware composer"
1587 " service connections. Ignoring request to transition to vr"
1588 " flinger.");
1589 mVrFlingerRequestsDisplay = false;
1590 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001591 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001593 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001594
Steven Thomas0123ac62018-07-12 11:32:34 -07001595 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001596 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001597
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001598 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001599
1600 // Clear out all the output layers from the composition engine for all
1601 // displays before destroying the hardware composer interface. This ensures
1602 // any HWC layers are destroyed through that interface before it becomes
1603 // invalid.
1604 for (const auto& [token, displayDevice] : mDisplays) {
1605 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1606 compositionengine::Output::OutputLayers());
1607 }
1608
Steven Thomas0123ac62018-07-12 11:32:34 -07001609 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1610 // called below. Clear the reference now so we don't accidentally use it
1611 // later.
1612 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001613
Steven Thomasb02664d2017-07-26 18:48:28 -07001614 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001615 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001617
Steven Thomasb02664d2017-07-26 18:48:28 -07001618 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001619 // Delete the current instance before creating the new one
1620 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1621 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1622 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1623 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001624
Lloyd Pique441d5042018-10-18 16:49:51 -07001625 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001626 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001627
1628 if (vrFlingerRequestsDisplay) {
1629 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631
1632 mVisibleRegionsDirty = true;
1633 invalidateHwcGeometry();
1634
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001635 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001636 display = getDefaultDisplayDeviceLocked();
1637 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001638 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001639
Steven Thomasb02664d2017-07-26 18:48:28 -07001640 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001641 const nsecs_t vsyncPeriod = getVsyncPeriod();
1642 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001643
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001644 // The present fences returned from vr_hwc are not an accurate
1645 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001646 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001647
Steven Thomasb02664d2017-07-26 18:48:28 -07001648 // Use phase of 0 since phase is not known.
1649 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001650 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001651 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001652
Ana Krulecc2870422019-01-29 19:00:58 -08001653 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001654
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001655 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001656 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001657}
1658
Ady Abrahambe0f9482019-04-24 15:41:53 -07001659bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1660 // We are storing the last 2 present fences. If sf's phase offset is to be
1661 // woken up before the actual vsync but targeting the next vsync, we need to check
1662 // fence N-2
1663 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001664 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001665 ? mPreviousPresentFences[0]
1666 : mPreviousPresentFences[1];
1667
1668 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1669}
1670
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001671void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001672 DisplayStatInfo stats;
1673 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001674 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001675 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001676 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001677 mPhaseOffsets->getOffsetThresholdForNextVsync()
1678 ? presentTime
1679 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001680}
1681
Dominik Laskowski22488f62019-03-28 09:53:04 -07001682void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001683 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001684 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001685 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001686 // calculate the expected present time once and use the cached
1687 // value throughout this frame to make sure all layers are
1688 // seeing this same value.
1689 populateExpectedPresentTime();
1690
Ady Abraham50204dd2019-07-19 15:47:11 -07001691 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1692 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1693 mHadDeviceComposition && frameMissed};
1694 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1695 mHadClientComposition && frameMissed};
1696
Alec Mouricc0fc602019-02-26 21:45:19 -08001697 if (frameMissed) {
1698 mFrameMissedCount++;
1699 mTimeStats->incrementMissedFrames();
1700 }
1701
Alec Mouri40189b02019-03-05 15:07:54 -08001702 if (hwcFrameMissed) {
1703 mHwcFrameMissedCount++;
1704 }
1705
1706 if (gpuFrameMissed) {
1707 mGpuFrameMissedCount++;
1708 }
1709
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001710 if (mUseSmart90ForVideo) {
1711 // This call is made each time SF wakes up and creates a new frame. It is part
1712 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001713 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001714 }
1715
Ady Abrahamb838aed2019-02-12 15:30:16 -08001716 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001717 break;
1718 }
1719
Ady Abraham4658e112019-07-22 13:07:26 -07001720 if (frameMissed && mPropagateBackpressure) {
1721 if ((hwcFrameMissed && !gpuFrameMissed) ||
1722 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001723 signalLayerUpdate();
1724 break;
1725 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001726 }
Dan Stoza50182882016-07-08 12:02:20 -07001727
Steven Thomas050b2c82017-03-06 11:45:16 -08001728 // Now that we're going to make it to the handleMessageTransaction()
1729 // call below it's safe to call updateVrFlinger(), which will
1730 // potentially trigger a display handoff.
1731 updateVrFlinger();
1732
Dan Stoza6b9454d2014-11-07 16:00:59 -08001733 bool refreshNeeded = handleMessageTransaction();
1734 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001735
1736 updateCursorAsync();
1737 updateInputFlinger();
1738
Dan Stoza58784442014-12-02 16:58:17 -08001739 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001740 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001741 // Signal a refresh if a transaction modified the window state,
1742 // a new buffer was latched, or if HWC has requested a full
1743 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001744 signalRefresh();
1745 }
1746 break;
1747 }
1748 case MessageQueue::REFRESH: {
1749 handleMessageRefresh();
1750 break;
1751 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001752 }
1753}
1754
Dan Stoza6b9454d2014-11-07 16:00:59 -08001755bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001756 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001757 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001758
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001759 bool flushedATransaction = flushTransactionQueues();
1760
1761 bool runHandleTransaction = transactionFlags &&
1762 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1763
1764 if (runHandleTransaction) {
1765 handleTransaction(eTransactionMask);
1766 } else {
1767 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001768 }
1769
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001770 if (transactionFlushNeeded()) {
1771 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001772 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001773
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001774 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775}
1776
Mathias Agopian4fec8732012-06-29 14:12:52 -07001777void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001778 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001779
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001780 mRefreshPending = false;
1781
Lloyd Piqueab039b52019-02-13 14:22:42 -08001782 compositionengine::CompositionRefreshArgs refreshArgs;
1783 for (const auto& [_, display] : mDisplays) {
1784 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1785 }
1786 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1787 auto compositionLayer = layer->getCompositionLayer();
1788 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1789 });
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001790 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
1791 if (mDebugRegion != 0) {
1792 refreshArgs.devOptFlashDirtyRegionsDelay =
1793 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1794 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001795
Lloyd Piqueab039b52019-02-13 14:22:42 -08001796 mCompositionEngine->preComposition(refreshArgs);
Lloyd Pique074e8122018-07-26 12:57:23 -07001797 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001798 calculateWorkingSet();
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001799 for (const auto& [token, displayDevice] : mDisplays) {
1800 auto display = displayDevice->getCompositionDisplay();
1801 display->beginFrame();
1802 display->prepareFrame();
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001803 display->devOptRepaintFlash(refreshArgs);
1804 doComposition(displayDevice, refreshArgs.repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001805 }
1806
David Sodmanfa9b2af2017-12-24 13:28:59 -08001807 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001808 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001809
Lloyd Pique66d68602019-02-13 14:23:31 -08001810 mHadClientComposition =
1811 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1812 auto& displayDevice = tokenDisplayPair.second;
1813 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1814 });
1815 mHadDeviceComposition =
1816 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1817 auto& displayDevice = tokenDisplayPair.second;
1818 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1819 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001820
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001821 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001822
David Sodman7e4ae112018-02-09 15:02:28 -08001823 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001824 if (mVisibleRegionsDirty) {
1825 mVisibleRegionsDirty = false;
1826 if (mTracingEnabled) {
1827 mTracing.notify("visibleRegionsDirty");
1828 }
1829 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001830
1831 if (mCompositionEngine->needsAnotherUpdate()) {
1832 signalLayerUpdate();
1833 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001834}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835
David Sodmanfa9b2af2017-12-24 13:28:59 -08001836
1837bool SurfaceFlinger::handleMessageInvalidate() {
1838 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001839 bool refreshNeeded = handlePageFlip();
1840
Vishnu Nair4351ad52019-02-11 14:13:02 -08001841 if (mVisibleRegionsDirty) {
1842 computeLayerBounds();
1843 }
1844
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001845 for (auto& layer : mLayersPendingRefresh) {
1846 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001847 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001848 invalidateLayerStack(layer, visibleReg);
1849 }
1850 mLayersPendingRefresh.clear();
1851 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001852}
1853
David Sodman79bba0e2018-08-05 18:07:49 -07001854void SurfaceFlinger::calculateWorkingSet() {
1855 ATRACE_CALL();
1856 ALOGV(__FUNCTION__);
1857
Lloyd Piquef5275482019-01-29 18:42:42 -08001858 const bool updatingGeometryThisFrame = mGeometryInvalid;
1859 mGeometryInvalid = false;
1860
Lloyd Pique05ed22e2019-08-09 12:20:51 -07001861 // Latch the frontend layer composition state for each layer being
1862 // composed.
1863 for (const auto& [token, displayDevice] : mDisplays) {
1864 auto display = displayDevice->getCompositionDisplay();
1865 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1866 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1867 updatingGeometryThisFrame);
Lloyd Piquef5275482019-01-29 18:42:42 -08001868 }
1869 }
1870
1871 if (CC_UNLIKELY(updatingGeometryThisFrame)) {
1872 for (const auto& [token, displayDevice] : mDisplays) {
1873 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquea83776c2019-01-29 18:42:32 -08001874 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001875
Lloyd Piquea83776c2019-01-29 18:42:32 -08001876 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquef5275482019-01-29 18:42:42 -08001877 // Assign a simple Z order sequence to each visible layer.
1878 layer->editState().z = zOrder++;
David Sodman79bba0e2018-08-05 18:07:49 -07001879 }
1880 }
1881 }
1882
Lloyd Piquef5275482019-01-29 18:42:42 -08001883 // Determine the color configuration of each output
Lloyd Pique32cbe282018-10-19 13:09:22 -07001884 for (const auto& [token, displayDevice] : mDisplays) {
1885 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001886
Lloyd Piquef5275482019-01-29 18:42:42 -08001887 ColorMode colorMode = ColorMode::NATIVE;
1888 Dataspace dataspace = Dataspace::UNKNOWN;
1889 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1890 if (useColorManagement) {
1891 pickColorMode(displayDevice, &colorMode, &dataspace, &renderIntent);
1892 }
1893 display->setColorMode(colorMode, dataspace, renderIntent, mColorSpaceAgnosticDataspace);
1894 }
1895
1896 for (const auto& [token, displayDevice] : mDisplays) {
1897 auto display = displayDevice->getCompositionDisplay();
1898
1899 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquec358b522019-08-09 12:21:21 -07001900 if (mDebugDisableHWC || mDebugRegion) {
1901 layer->editState().forceClientComposition = true;
1902 }
1903
Lloyd Piquef5275482019-01-29 18:42:42 -08001904 // Update the composition state of the output layer, as needed
1905 // recomputing it from the state given by the front-end layer.
1906 layer->updateCompositionState(updatingGeometryThisFrame);
Lloyd Piquef5275482019-01-29 18:42:42 -08001907
Lloyd Piquef5275482019-01-29 18:42:42 -08001908 // Send the updated state to the HWC, if appropriate.
1909 layer->writeStateToHWC(updatingGeometryThisFrame);
1910 }
1911 }
1912
1913 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1914 for (const auto& [token, displayDevice] : mDisplays) {
1915 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001916 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001917 }
Lloyd Piquef5275482019-01-29 18:42:42 -08001918 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001919 }
David Sodman79bba0e2018-08-05 18:07:49 -07001920}
1921
Ana Krulece588e312018-09-18 12:32:24 -07001922void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1923 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001924 // Update queue of past composite+present times and determine the
1925 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001926 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001927 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001928 while (!getBE().mCompositePresentTimes.empty()) {
1929 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930 // Cached values should have been updated before calling this method,
1931 // which helps avoid duplicate syscalls.
1932 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1933 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1934 break;
1935 }
1936 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001937 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 }
1939
1940 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001941 while (getBE().mCompositePresentTimes.size() > 16) {
1942 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001943 }
1944
Ana Krulece588e312018-09-18 12:32:24 -07001945 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001946}
1947
Ana Krulece588e312018-09-18 12:32:24 -07001948void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1949 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001950 // Integer division and modulo round toward 0 not -inf, so we need to
1951 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001952 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1953 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1954 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001955
Ana Krulec757f63a2019-01-25 10:46:18 -08001956 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001957 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001958 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001959 }
1960
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001961 // Snap the latency to a value that removes scheduling jitter from the
1962 // composition and present times, which often have >1ms of jitter.
1963 // Reducing jitter is important if an app attempts to extrapolate
1964 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001965 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001967 nsecs_t bias = stats.vsyncPeriod / 2;
1968 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1969 nsecs_t snappedCompositeToPresentLatency =
1970 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001971
David Sodman99974d22017-11-28 12:04:33 -08001972 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001973 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1974 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001975 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976}
1977
David Sodman2b406362017-12-15 13:33:47 -08001978void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 ATRACE_CALL();
1981 ALOGV("postComposition");
1982
Brian Anderson3546a3f2016-07-14 11:51:14 -07001983 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001984 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001985 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001986 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001987 }
1988
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001989 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001990 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001991
David Sodman73beded2017-11-15 11:56:06 -08001992 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001993 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001994 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001995 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001996 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1997 ->getRenderSurface()
1998 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001999 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002000 } else {
2001 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2002 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002003
David Sodman73beded2017-11-15 11:56:06 -08002004 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002005 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2006 mPreviousPresentFences[0] = displayDevice
2007 ? getHwComposer().getPresentFence(*displayDevice->getId())
2008 : Fence::NO_FENCE;
2009 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002010 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011
Ana Krulece588e312018-09-18 12:32:24 -07002012 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002013 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002014
Lloyd Piqueab039b52019-02-13 14:22:42 -08002015 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2016 // be sampled a little later than when we started doing work for this frame,
2017 // but that should be okay since updateCompositorTiming has snapping logic.
2018 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2019 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002020 CompositorTiming compositorTiming;
2021 {
David Sodman99974d22017-11-28 12:04:33 -08002022 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2023 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002024 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002025
Robert Carr2047fae2016-11-28 14:09:09 -08002026 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002027 bool frameLatched =
2028 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2029 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002030 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002031 recordBufferingStats(layer->getName().string(),
2032 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002033 }
Robert Carr2047fae2016-11-28 14:09:09 -08002034 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002035
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002036 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002037 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002038 }
2039
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002040 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002041 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2042 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002043 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002044 }
2045 }
2046
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002047 if (mAnimCompositionPending) {
2048 mAnimCompositionPending = false;
2049
Brian Anderson4e606e32017-03-16 15:34:57 -07002050 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002052 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002053 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002054 // The HWC doesn't support present fences, so use the refresh
2055 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002056 const nsecs_t presentTime =
2057 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002058 mAnimFrameTracker.setActualPresentTime(presentTime);
2059 }
2060 mAnimFrameTracker.advanceFrame();
2061 }
Dan Stozab90cf072015-03-05 11:05:59 -08002062
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002063 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002064 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002065 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002066 }
2067
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002068 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002069
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2071 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002072 return;
2073 }
2074
2075 nsecs_t currentTime = systemTime();
2076 if (mHasPoweredOff) {
2077 mHasPoweredOff = false;
2078 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002079 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002080 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002081 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2082 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002083 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002084 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002085 }
David Sodman4a36e932017-11-07 14:29:47 -08002086 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002087 }
David Sodman4a36e932017-11-07 14:29:47 -08002088 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002089
2090 {
2091 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002092 if (mTexturePool.size() < mTexturePoolSize) {
2093 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002094 const size_t offset = mTexturePool.size();
2095 mTexturePool.resize(mTexturePoolSize);
2096 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2097 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002098 } else if (mTexturePool.size() > mTexturePoolSize) {
2099 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2100 const size_t offset = mTexturePoolSize;
2101 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2102 mTexturePool.resize(mTexturePoolSize);
2103 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002104 }
2105 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002106
Ady Abrahambe0f9482019-04-24 15:41:53 -07002107 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002108 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002109
Kevin DuBois413287f2019-02-25 08:46:47 -08002110 if (mLumaSampling && mRegionSamplingThread) {
2111 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002112 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002113
2114 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2115 // side-effect of getTotalSize(), so we check that again here
2116 if (ATRACE_ENABLED()) {
2117 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2118 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002119}
2120
Vishnu Nair4351ad52019-02-11 14:13:02 -08002121void SurfaceFlinger::computeLayerBounds() {
2122 for (const auto& pair : mDisplays) {
2123 const auto& displayDevice = pair.second;
2124 const auto display = displayDevice->getCompositionDisplay();
2125 for (const auto& layer : mDrawingState.layersSortedByZ) {
2126 // only consider the layers on the given layer stack
2127 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002128 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002129 }
2130
2131 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2132 }
2133 }
2134}
2135
Mathias Agopiancd60f992012-08-16 16:28:27 -07002136void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002137 ATRACE_CALL();
2138 ALOGV("rebuildLayerStacks");
2139
Mathias Agopiancd60f992012-08-16 16:28:27 -07002140 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002141 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002142 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002143 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002144
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002145 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002146 const auto& displayDevice = pair.second;
2147 auto display = displayDevice->getCompositionDisplay();
2148 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002149 Region opaqueRegion;
2150 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002151 compositionengine::Output::OutputLayers layersSortedByZ;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002152 compositionengine::Output::ReleasedLayers releasedLayers;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002153 Vector<sp<Layer>> deprecated_layersSortedByZ;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002154 const ui::Transform& tr = displayState.transform;
2155 const Rect bounds = displayState.bounds;
2156 if (displayState.isEnabled) {
2157 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002158
Jeff Sharkey76488112017-02-27 14:15:18 -07002159 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002160 auto compositionLayer = layer->getCompositionLayer();
2161 if (compositionLayer == nullptr) {
2162 return;
2163 }
2164
Lloyd Pique32cbe282018-10-19 13:09:22 -07002165 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002166 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2167 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2168
Lloyd Pique07e33212018-12-18 16:33:37 -08002169 bool needsOutputLayer = false;
2170
Lloyd Piqueef36b002019-01-23 17:52:04 -08002171 if (display->belongsInOutput(layer->getLayerStack(),
2172 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002173 Region drawRegion(tr.transform(
2174 layer->visibleNonTransparentRegion));
2175 drawRegion.andSelf(bounds);
2176 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002177 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002178 }
Chia-I Wu83806892017-11-16 10:50:20 -08002179 }
2180
Lloyd Pique07e33212018-12-18 16:33:37 -08002181 if (needsOutputLayer) {
2182 layersSortedByZ.emplace_back(
2183 display->getOrCreateOutputLayer(displayId, compositionLayer,
2184 layerFE));
2185 deprecated_layersSortedByZ.add(layer);
2186
2187 auto& outputLayerState = layersSortedByZ.back()->editState();
2188 outputLayerState.visibleRegion =
2189 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2190 } else if (displayId) {
2191 // For layers that are being removed from a HWC display,
2192 // and that have queued frames, add them to a a list of
2193 // released layers so we can properly set a fence.
2194 bool hasExistingOutputLayer =
2195 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2196 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2197 mLayersWithQueuedFrames.cend(),
2198 layer) != mLayersWithQueuedFrames.cend();
2199
2200 if (hasExistingOutputLayer && hasQueuedFrames) {
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002201 releasedLayers.push_back(layer);
Chia-I Wu83806892017-11-16 10:50:20 -08002202 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002203 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002204 });
2205 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002206
2207 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002208 display->setReleasedLayers(std::move(releasedLayers));
Lloyd Piquecc01a452018-12-04 17:24:00 -08002209
2210 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002211
2212 Region undefinedRegion{bounds};
2213 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2214
2215 display->editState().undefinedRegion = undefinedRegion;
2216 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002217 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002218 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002219}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002220
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002221// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002222// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002223// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002224// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002225// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002226// The returned HDR data space is one of
2227// - Dataspace::UNKNOWN
2228// - Dataspace::BT2020_HLG
2229// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002230Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2231 Dataspace* outHdrDataSpace,
2232 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002233 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002234 *outHdrDataSpace = Dataspace::UNKNOWN;
2235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002237 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002238 case Dataspace::V0_SCRGB:
2239 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002240 case Dataspace::BT2020:
2241 case Dataspace::BT2020_ITU:
2242 case Dataspace::BT2020_LINEAR:
2243 case Dataspace::DISPLAY_BT2020:
2244 bestDataSpace = Dataspace::DISPLAY_BT2020;
2245 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002246 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002247 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002248 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002249 case Dataspace::BT2020_PQ:
2250 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002251 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002252 *outHdrDataSpace = Dataspace::BT2020_PQ;
Lloyd Piquef5275482019-01-29 18:42:42 -08002253 *outIsHdrClientComposition =
2254 layer->getCompositionLayer()->getState().frontEnd.forceClientComposition;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002255 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002256 case Dataspace::BT2020_HLG:
2257 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002258 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002259 // When there's mixed PQ content and HLG content, we set the HDR
2260 // data space to be BT2020_PQ and convert HLG to PQ.
2261 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2262 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002263 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002264 break;
2265 default:
2266 break;
2267 }
Romain Guy54f154a2017-10-24 21:40:32 +01002268 }
2269
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002270 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002271}
2272
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002273// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2275 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2277 *outMode = ColorMode::NATIVE;
2278 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002279 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002280 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002281 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002282
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002283 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002284 bool isHdrClientComposition = false;
2285 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002286
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002287 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2288
Peiyong Lina3ea5592019-02-10 14:45:00 -08002289 switch (mForceColorMode) {
2290 case ColorMode::SRGB:
2291 bestDataSpace = Dataspace::V0_SRGB;
2292 break;
2293 case ColorMode::DISPLAY_P3:
2294 bestDataSpace = Dataspace::DISPLAY_P3;
2295 break;
2296 default:
2297 break;
2298 }
2299
Peiyong Lindfde5112018-06-05 10:58:41 -07002300 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002301 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2302 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002303 if (isHdr) {
2304 bestDataSpace = hdrDataSpace;
2305 }
2306
Chia-I Wu0d711262018-05-21 15:19:35 -07002307 RenderIntent intent;
2308 switch (mDisplayColorSetting) {
2309 case DisplayColorSetting::MANAGED:
2310 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002311 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002312 break;
2313 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002314 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002315 break;
2316 default: // vendor display color setting
2317 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2318 break;
2319 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002320
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002321 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002322}
2323
Lloyd Pique32cbe282018-10-19 13:09:22 -07002324void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002326 ALOGV("doComposition");
2327
Lloyd Pique32cbe282018-10-19 13:09:22 -07002328 auto display = displayDevice->getCompositionDisplay();
2329 const auto& displayState = display->getState();
2330
2331 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002332 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002333 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002334
David Sodmanfa9b2af2017-12-24 13:28:59 -08002335 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002336 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002337
Lloyd Pique32cbe282018-10-19 13:09:22 -07002338 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002339 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002340 }
Lloyd Pique35fca9d2019-02-13 14:24:11 -08002341 displayDevice->getCompositionDisplay()->postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002342}
2343
David Sodmanfa9b2af2017-12-24 13:28:59 -08002344void SurfaceFlinger::postFrame()
2345{
2346 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002347 const auto display = getDefaultDisplayDeviceLocked();
2348 if (display && getHwComposer().isConnected(*display->getId())) {
2349 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002350 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2351 logFrameStats();
2352 }
2353 }
2354}
2355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357{
Mathias Agopian841cde52012-03-01 15:44:37 -08002358 ATRACE_CALL();
2359
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002360 // here we keep a copy of the drawing state (that is the state that's
2361 // going to be overwritten by handleTransactionLocked()) outside of
2362 // mStateLock so that the side-effects of the State assignment
2363 // don't happen with mStateLock held (which can cause deadlocks).
2364 State drawingState(mDrawingState);
2365
Mathias Agopianca4d3602011-05-19 15:38:14 -07002366 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002367 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002368
Mathias Agopianca4d3602011-05-19 15:38:14 -07002369 // Here we're guaranteed that some transaction flags are set
2370 // so we can call handleTransactionLocked() unconditionally.
2371 // We call getTransactionFlags(), which will also clear the flags,
2372 // with mStateLock held to guarantee that mCurrentState won't change
2373 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002374
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002375 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002376 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002377 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002378
Mathias Agopianca4d3602011-05-19 15:38:14 -07002379 mDebugInTransaction = 0;
2380 invalidateHwcGeometry();
2381 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002382}
2383
Lloyd Piqueba04e622017-12-14 17:11:26 -08002384void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2385 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002386 const std::optional<DisplayIdentificationInfo> info =
2387 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002388
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002390 continue;
2391 }
2392
Lloyd Piqueba04e622017-12-14 17:11:26 -08002393 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002395 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 mPhysicalDisplayTokens[info->id] = new BBinder();
2397 DisplayDeviceState state;
2398 state.displayId = info->id;
2399 state.isSecure = true; // All physical displays are currently considered secure.
2400 state.displayName = info->name;
2401 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2402 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002403 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002404 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002405 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002406
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2408 if (index >= 0) {
2409 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2410 mInterceptor->saveDisplayDeletion(state.sequenceId);
2411 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002412 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002414 }
2415
2416 processDisplayChangesLocked();
2417 }
2418
2419 mPendingHotplugEvents.clear();
2420}
2421
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002422void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002423 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2424 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002425}
2426
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002429 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 const sp<IGraphicBufferProducer>& producer) {
2431 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002432 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002434 creationArgs.isSecure = state.isSecure;
2435 creationArgs.displaySurface = dispSurface;
2436 creationArgs.hasWideColorGamut = false;
2437 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002438 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002439
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002440 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 creationArgs.isPrimary = isInternalDisplay;
2442
2443 if (useColorManagement && displayId) {
2444 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002445 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002446 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002447 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002449
Dominik Laskowski7e045462018-05-30 13:02:02 -07002450 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002452 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453 }
tangrobin6753a022018-08-10 10:58:54 +08002454 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455
Dominik Laskowski075d3172018-05-24 15:50:06 -07002456 if (displayId) {
2457 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002458 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002460 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461
Lloyd Pique90c115d2018-09-18 21:39:42 -07002462 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002464 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002465
Lloyd Pique99d3da52018-01-22 17:48:03 -08002466 // Make sure that composition can never be stalled by a virtual display
2467 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002468 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002469 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2471 }
2472
Dominik Laskowski075d3172018-05-24 15:50:06 -07002473 creationArgs.displayInstallOrientation =
2474 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002475
Lloyd Pique99d3da52018-01-22 17:48:03 -08002476 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002477 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478
Lloyd Pique90c115d2018-09-18 21:39:42 -07002479 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002480
2481 if (maxFrameBufferAcquiredBuffers >= 3) {
2482 nativeWindowSurface->preallocateBuffers();
2483 }
2484
2485 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002486 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002487 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002489 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002491 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
Lloyd Piquef5275482019-01-29 18:42:42 -08002492 RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 if (!state.isVirtual()) {
2494 LOG_ALWAYS_FATAL_IF(!displayId);
2495 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002496 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 display->setLayerStack(state.layerStack);
2499 display->setProjection(state.orientation, state.viewport, state.frame);
2500 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002501
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002503}
2504
Lloyd Pique347200f2017-12-14 17:00:15 -08002505void SurfaceFlinger::processDisplayChangesLocked() {
2506 // here we take advantage of Vector's copy-on-write semantics to
2507 // improve performance by skipping the transaction entirely when
2508 // know that the lists are identical
2509 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2510 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2511 if (!curr.isIdenticalTo(draw)) {
2512 mVisibleRegionsDirty = true;
2513 const size_t cc = curr.size();
2514 size_t dc = draw.size();
2515
2516 // find the displays that were removed
2517 // (ie: in drawing state but not in current state)
2518 // also handle displays that changed
2519 // (ie: displays that are in both lists)
2520 for (size_t i = 0; i < dc;) {
2521 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2522 if (j < 0) {
2523 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002524 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002525 // Save display ID before disconnecting.
2526 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002527 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002528
2529 if (!display->isVirtual()) {
2530 LOG_ALWAYS_FATAL_IF(!displayId);
2531 dispatchDisplayHotplugEvent(displayId->value, false);
2532 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002533 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002534
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002535 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002536 } else {
2537 // this display is in both lists. see if something changed.
2538 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002539 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2541 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2542 if (state_binder != draw_binder) {
2543 // changing the surface is like destroying and
2544 // recreating the DisplayDevice, so we just remove it
2545 // from the drawing state, so that it get re-added
2546 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002547 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002548 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002549 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002550 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002551 mDrawingState.displays.removeItemsAt(i);
2552 dc--;
2553 // at this point we must loop to the next item
2554 continue;
2555 }
2556
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002557 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002558 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002559 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002560 }
2561 if ((state.orientation != draw[i].orientation) ||
2562 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002563 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002564 }
2565 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002566 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 }
2568 }
2569 }
2570 ++i;
2571 }
2572
2573 // find displays that were added
2574 // (ie: in current state but not in drawing state)
2575 for (size_t i = 0; i < cc; i++) {
2576 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2577 const DisplayDeviceState& state(curr[i]);
2578
Lloyd Pique542307f2018-10-19 13:24:08 -07002579 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 sp<IGraphicBufferProducer> producer;
2581 sp<IGraphicBufferProducer> bqProducer;
2582 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002583 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002584
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002586 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002587 // Virtual displays without a surface are dormant:
2588 // they have external state (layer stack, projection,
2589 // etc.) but no internal state (i.e. a DisplayDevice).
2590 if (state.surface != nullptr) {
2591 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002592 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002593 int width = 0;
2594 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2595 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2596 int height = 0;
2597 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2598 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2599 int intFormat = 0;
2600 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2601 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002602 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002603
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 displayId =
2605 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 }
2607
2608 // TODO: Plumb requested format back up to consumer
2609
2610 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002612 bqProducer, bqConsumer,
2613 state.displayName);
2614
2615 dispSurface = vds;
2616 producer = vds;
2617 }
2618 } else {
2619 ALOGE_IF(state.surface != nullptr,
2620 "adding a supported display, but rendering "
2621 "surface is provided (%p), ignoring it",
2622 state.surface.get());
2623
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 displayId = state.displayId;
2625 LOG_ALWAYS_FATAL_IF(!displayId);
2626 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002627 producer = bqProducer;
2628 }
2629
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002630 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002631 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002632 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002633 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002634 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002635 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002636 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002637 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 }
2639 }
2640 }
2641 }
2642 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002643
2644 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002645}
2646
Mathias Agopian87baae12012-07-31 12:38:26 -07002647void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002648{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002649 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2650
Dan Stoza7dde5992015-05-22 09:51:44 -07002651 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002652 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2653 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002654 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002655
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 /*
2657 * Traversal of the children
2658 * (perform the transaction for each of them if needed)
2659 */
2660
Marissa Wall06255332019-03-27 13:48:27 -07002661 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002662 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002664 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
2666 const uint32_t flags = layer->doTransaction(0);
2667 if (flags & Layer::eVisibleRegion)
2668 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002669
2670 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002671 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002672 }
Robert Carr2047fae2016-11-28 14:09:09 -08002673 });
Marissa Wall06255332019-03-27 13:48:27 -07002674 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 }
2676
2677 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002678 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002679 */
2680
Mathias Agopiane57f2922012-08-09 16:29:12 -07002681 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002682 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002683 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002685
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002686 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002687 // The transform hint might have changed for some layers
2688 // (either because a display has changed, or because a layer
2689 // as changed).
2690 //
2691 // Walk through all the layers in currentLayers,
2692 // and update their transform hint.
2693 //
2694 // If a layer is visible only on a single display, then that
2695 // display is used to calculate the hint, otherwise we use the
2696 // default display.
2697 //
2698 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2699 // the hint is set before we acquire a buffer from the surface texture.
2700 //
2701 // NOTE: layer transactions have taken place already, so we use their
2702 // drawing state. However, SurfaceFlinger's own transaction has not
2703 // happened yet, so we must use the current state layer list
2704 // (soon to become the drawing state list).
2705 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002707 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002708 bool first = true;
2709 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002710 // NOTE: we rely on the fact that layers are sorted by
2711 // layerStack first (so we don't have to traverse the list
2712 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002713 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002714 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002715 currentlayerStack = layerStack;
2716 // figure out if this layerstack is mirrored
2717 // (more than one display) if so, pick the default display,
2718 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002719 hintDisplay = nullptr;
2720 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002721 if (display->getCompositionDisplay()
2722 ->belongsInOutput(layer->getLayerStack(),
2723 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002724 if (hintDisplay) {
2725 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002726 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002727 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002728 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002729 }
2730 }
2731 }
2732 }
Chet Haase91d25932013-04-11 15:24:55 -07002733
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002734 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002735 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2736 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002737
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002738 // could be null when this layer is using a layerStack
2739 // that is not visible on any display. Also can occur at
2740 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002741 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002742 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002743
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002744 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002745 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 if (hintDisplay) {
2747 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002748 }
Robert Carr2047fae2016-11-28 14:09:09 -08002749
2750 first = false;
2751 });
Mathias Agopian84300952012-11-21 16:02:13 -08002752 }
2753
2754
Mathias Agopian3559b072012-08-15 13:46:03 -07002755 /*
2756 * Perform our own transaction if needed
2757 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758
2759 if (mLayersAdded) {
2760 mLayersAdded = false;
2761 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002762 mVisibleRegionsDirty = true;
2763 }
2764
2765 // some layers might have been removed, so
2766 // we need to update the regions they're exposing.
2767 if (mLayersRemoved) {
2768 mLayersRemoved = false;
2769 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002770 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002771 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002772 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002773 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002774 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002775 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002776 }
Robert Carr2047fae2016-11-28 14:09:09 -08002777 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 }
2779
Vishnu Nairec0ab382019-02-13 15:32:56 -08002780 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002782}
2783
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002784void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002785 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002786 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002787 return;
2788 }
2789
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002790 if (mVisibleRegionsDirty || mInputInfoChanged) {
2791 mInputInfoChanged = false;
2792 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002793 } else if (mInputWindowCommands.syncInputWindows) {
2794 // If the caller requested to sync input windows, but there are no
2795 // changes to input windows, notify immediately.
2796 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002797 }
2798
2799 executeInputWindowCommands();
2800}
2801
2802void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002803 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002804
2805 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2806 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002807 // When calculating the screen bounds we ignore the transparent region since it may
2808 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002809 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002810 }
2811 });
chaviw291d88a2019-02-14 10:33:58 -08002812
2813 mInputFlinger->setInputWindows(inputHandles,
2814 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2815 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002816}
2817
Vishnu Nairec0ab382019-02-13 15:32:56 -08002818void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002819 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002820 mPendingInputWindowCommands.clear();
2821}
2822
chaviwfbe5d9c2018-12-26 12:23:37 -08002823void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002824 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2825 if (transferTouchFocusCommand.fromToken != nullptr &&
2826 transferTouchFocusCommand.toToken != nullptr &&
2827 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2828 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2829 transferTouchFocusCommand.toToken);
2830 }
2831 }
2832
2833 mInputWindowCommands.clear();
2834}
2835
Riley Andrews03414a12014-07-01 14:22:59 -07002836void SurfaceFlinger::updateCursorAsync()
2837{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002839 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002840 continue;
2841 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002842
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2844 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002845 }
2846 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847}
2848
2849void SurfaceFlinger::commitTransaction()
2850{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002851 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002852 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002853 for (const auto& l : mLayersPendingRemoval) {
2854 recordBufferingStats(l->getName().string(),
2855 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002856
Lloyd Pique07e33212018-12-18 16:33:37 -08002857 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07002858 if (l->isRemovedFromCurrentState()) {
chaviw49a108c2019-08-12 11:23:06 -07002859 l->latchAndReleaseBuffer();
Robert Carr2e102c92018-10-23 12:11:15 -07002860 }
chaviw74d90ad2019-04-26 14:45:26 -07002861
2862 // If the layer has been removed and has no parent, then it will not be reachable
2863 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2864 // ensure we can copy its current to drawing state.
2865 if (!l->getParent()) {
2866 mOffscreenLayers.emplace(l.get());
2867 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002868 }
2869 mLayersPendingRemoval.clear();
2870 }
2871
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002872 // If this transaction is part of a window animation then the next frame
2873 // we composite should be considered an animation as well.
2874 mAnimCompositionPending = mAnimTransactionPending;
2875
Nataniel Borges2b796da2019-02-15 13:32:18 -08002876 withTracingLock([&]() {
2877 mDrawingState = mCurrentState;
2878 // clear the "changed" flags in current state
2879 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002880
chaviw74d90ad2019-04-26 14:45:26 -07002881 mDrawingState.traverseInZOrder([&](Layer* layer) {
2882 layer->commitChildList();
2883
2884 // If the layer can be reached when traversing mDrawingState, then the layer is no
2885 // longer offscreen. Remove the layer from the offscreenLayer set.
2886 if (mOffscreenLayers.count(layer)) {
2887 mOffscreenLayers.erase(layer);
2888 }
2889 });
2890
2891 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002892 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002893
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002894 mTransactionPending = false;
2895 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002896 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897}
2898
Nataniel Borges2b796da2019-02-15 13:32:18 -08002899void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2900 if (mTracingEnabledChanged) {
2901 mTracingEnabled = mTracing.isEnabled();
2902 mTracingEnabledChanged = false;
2903 }
2904
2905 // Synchronize with Tracing thread
2906 std::unique_lock<std::mutex> lock;
2907 if (mTracingEnabled) {
2908 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2909 }
2910
2911 lockedOperation();
2912
2913 // Synchronize with Tracing thread
2914 if (mTracingEnabled) {
2915 lock.unlock();
2916 }
2917}
2918
chaviw74d90ad2019-04-26 14:45:26 -07002919void SurfaceFlinger::commitOffscreenLayers() {
2920 for (Layer* offscreenLayer : mOffscreenLayers) {
2921 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2922 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2923 if (!trFlags) return;
2924
2925 layer->doTransaction(0);
2926 layer->commitChildList();
2927 });
2928 }
2929}
2930
Lloyd Pique32cbe282018-10-19 13:09:22 -07002931void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002932 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002933 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002934 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002935
Lloyd Pique32cbe282018-10-19 13:09:22 -07002936 auto display = displayDevice->getCompositionDisplay();
2937
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002938 Region aboveOpaqueLayers;
2939 Region aboveCoveredLayers;
2940 Region dirty;
2941
Mathias Agopian87baae12012-07-31 12:38:26 -07002942 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943
Robert Carr2047fae2016-11-28 14:09:09 -08002944 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002945 // start with the whole surface at its current location
2946 const Layer::State& s(layer->getDrawingState());
2947
Jesse Hall01e29052013-02-19 16:13:35 -08002948 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08002949 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002950 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002951 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002952
Mathias Agopianab028732010-03-16 16:41:46 -07002953 /*
2954 * opaqueRegion: area of a surface that is fully opaque.
2955 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002957
2958 /*
2959 * visibleRegion: area of a surface that is visible on screen
2960 * and not fully transparent. This is essentially the layer's
2961 * footprint minus the opaque regions above it.
2962 * Areas covered by a translucent surface are considered visible.
2963 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002965
2966 /*
2967 * coveredRegion: area of a surface that is covered by all
2968 * visible regions above it (which includes the translucent areas).
2969 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002970 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002971
Jesse Halla8026d22012-09-25 13:25:04 -07002972 /*
2973 * transparentRegion: area of a surface that is hinted to be completely
2974 * transparent. This is only used to tell when the layer has no visible
2975 * non-transparent regions and can be removed from the layer list. It
2976 * does not affect the visibleRegion of this layer or any layers
2977 * beneath it. The hint may not be correct if apps don't respect the
2978 * SurfaceView restrictions (which, sadly, some don't).
2979 */
2980 Region transparentRegion;
2981
Mathias Agopianab028732010-03-16 16:41:46 -07002982
2983 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002984 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002985 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002986 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002987
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002989 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002990 if (!visibleRegion.isEmpty()) {
2991 // Remove the transparent area from the visible region
2992 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002993 if (tr.preserveRects()) {
2994 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002995 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002997 // transformation too complex, can't do the
2998 // transparent region optimization.
2999 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003000 }
Mathias Agopianab028732010-03-16 16:41:46 -07003001 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002
Mathias Agopianab028732010-03-16 16:41:46 -07003003 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003004 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003005 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003006 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003007 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003008 // the opaque region is the layer's footprint
3009 opaqueRegion = visibleRegion;
3010 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011 }
3012 }
3013
Robert Carre5f4f692018-01-12 13:12:28 -08003014 if (visibleRegion.isEmpty()) {
3015 layer->clearVisibilityRegions();
3016 return;
3017 }
3018
Mathias Agopianab028732010-03-16 16:41:46 -07003019 // Clip the covered region to the visible region
3020 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3021
3022 // Update aboveCoveredLayers for next (lower) layer
3023 aboveCoveredLayers.orSelf(visibleRegion);
3024
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025 // subtract the opaque region covered by the layers above us
3026 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003027
3028 // compute this layer's dirty region
3029 if (layer->contentDirty) {
3030 // we need to invalidate the whole region
3031 dirty = visibleRegion;
3032 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003033 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003034 layer->contentDirty = false;
3035 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003036 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003037 * the exposed region consists of two components:
3038 * 1) what's VISIBLE now and was COVERED before
3039 * 2) what's EXPOSED now less what was EXPOSED before
3040 *
3041 * note that (1) is conservative, we start with the whole
3042 * visible region but only keep what used to be covered by
3043 * something -- which mean it may have been exposed.
3044 *
3045 * (2) handles areas that were not covered by anything but got
3046 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003047 */
Mathias Agopianab028732010-03-16 16:41:46 -07003048 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003049 const Region oldVisibleRegion = layer->visibleRegion;
3050 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003051 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3052 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053 }
3054 dirty.subtractSelf(aboveOpaqueLayers);
3055
3056 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003057 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003058
Mathias Agopianab028732010-03-16 16:41:46 -07003059 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003061
Jesse Halla8026d22012-09-25 13:25:04 -07003062 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063 layer->setVisibleRegion(visibleRegion);
3064 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003065 layer->setVisibleNonTransparentRegion(
3066 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003067 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068
Mathias Agopian87baae12012-07-31 12:38:26 -07003069 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070}
3071
Chia-I Wuab0c3192017-08-01 11:29:00 -07003072void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003073 for (const auto& [token, displayDevice] : mDisplays) {
3074 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003075 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003076 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003077 }
3078 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003079}
3080
Dan Stoza6b9454d2014-11-07 16:00:59 -08003081bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082{
Ady Abraham09bd3922019-04-08 10:44:56 -07003083 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003084 ALOGV("handlePageFlip");
3085
Brian Andersond6927fb2016-07-23 23:37:30 -07003086 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003087
Mathias Agopian4fec8732012-06-29 14:12:52 -07003088 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003090 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003091
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003092 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3093
Eric Penner51c59cd2014-07-28 19:51:58 -07003094 // Store the set of layers that need updates. This set must not change as
3095 // buffers are being latched, as this could result in a deadlock.
3096 // Example: Two producers share the same command stream and:
3097 // 1.) Layer 0 is latched
3098 // 2.) Layer 0 gets a new frame
3099 // 2.) Layer 1 gets a new frame
3100 // 3.) Layer 1 is latched.
3101 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3102 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003103 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003104 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003106 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003107 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003108 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003109 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003110 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003111 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003112 } else {
3113 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003114 }
Robert Carr2047fae2016-11-28 14:09:09 -08003115 });
3116
chaviw49a108c2019-08-12 11:23:06 -07003117 // The client can continue submitting buffers for offscreen layers, but they will not
3118 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3119 // layers to ensure dequeueBuffer doesn't block indefinitely.
3120 for (Layer* offscreenLayer : mOffscreenLayers) {
3121 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
3122 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3123 }
3124
Lloyd Piquef2c79392018-12-20 16:23:33 -08003125 if (!mLayersWithQueuedFrames.empty()) {
3126 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3127 // writes to Layer current state. See also b/119481871
3128 Mutex::Autolock lock(mStateLock);
3129
3130 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003131 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003132 mLayersPendingRefresh.push_back(layer);
3133 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003134 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003135 if (layer->isBufferLatched()) {
3136 newDataLatched = true;
3137 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003138 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003139 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003140
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003141 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003142
3143 // If we will need to wake up at some time in the future to deal with a
3144 // queued frame that shouldn't be displayed during this vsync period, wake
3145 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003146 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003147 signalLayerUpdate();
3148 }
3149
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003150 // enter boot animation on first buffer latch
3151 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3152 ALOGI("Enter boot animation");
3153 mBootStage = BootStage::BOOTANIMATION;
3154 }
3155
Dan Stoza6b9454d2014-11-07 16:00:59 -08003156 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003157 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158}
3159
Mathias Agopianad456f92011-01-13 17:53:01 -08003160void SurfaceFlinger::invalidateHwcGeometry()
3161{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003162 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003163}
3164
Lloyd Pique32cbe282018-10-19 13:09:22 -07003165void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003166 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003167 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003168 // We only need to actually compose the display if:
3169 // 1) It is being handled by hardware composer, which may need this to
3170 // keep its virtual display state machine in sync, or
3171 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003172 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003173 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003174 return;
3175 }
3176
Dan Stoza9e56aa02015-11-02 13:00:03 -08003177 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003178 base::unique_fd readyFence;
Lloyd Pique688abd42019-02-15 15:42:24 -08003179 if (!display->composeSurfaces(Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003180
3181 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003182 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183}
3184
Robert Carrc0df3122019-04-11 13:18:21 -07003185status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3186 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3187 const sp<IBinder>& parentHandle,
3188 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003189 // add this layer to the current state list
3190 {
3191 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003192 sp<Layer> parent;
3193 if (parentHandle != nullptr) {
3194 parent = fromHandle(parentHandle);
3195 if (parent == nullptr) {
3196 return NAME_NOT_FOUND;
3197 }
3198 } else {
3199 parent = parentLayer;
3200 }
3201
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003203 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003204 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003205 return NO_MEMORY;
3206 }
Robert Carrc0df3122019-04-11 13:18:21 -07003207
3208 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3209
Robert Carrb89ea9d2018-12-10 13:01:14 -08003210 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003212 } else if (parent == nullptr) {
3213 lbc->onRemovedFromCurrentState();
3214 } else if (parent->isRemovedFromCurrentState()) {
3215 parent->addChild(lbc);
3216 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003217 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003218 parent->addChild(lbc);
3219 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003220
Yiwei Zhang243b3782018-05-15 17:40:04 -07003221 if (gbc != nullptr) {
3222 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3223 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3224 mMaxGraphicBufferProducerListSize,
3225 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3226 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003227 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003228 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003229 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003230 }
3231
Mathias Agopian96f08192010-06-02 23:28:45 -07003232 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003233 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003234
Dan Stoza7d89d062015-04-30 13:29:25 -07003235 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003236}
3237
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003238uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003239 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003240}
3241
Mathias Agopian3f844832013-08-07 21:24:32 -07003242uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003243 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244}
3245
Mathias Agopian3f844832013-08-07 21:24:32 -07003246uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003247 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003248}
3249
3250uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003251 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003252 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003253 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003254 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003255 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003256 }
3257 return old;
3258}
3259
Marissa Wall713b63f2018-10-17 15:42:43 -07003260bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003261 // to prevent onHandleDestroyed from being called while the lock is held,
3262 // we must keep a copy of the transactions (specifically the composer
3263 // states) around outside the scope of the lock
3264 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003265 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003266 {
3267 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003268
Valerie Haufce31b82019-04-30 16:41:14 -07003269 auto it = mTransactionQueues.begin();
3270 while (it != mTransactionQueues.end()) {
3271 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003272
Valerie Haufce31b82019-04-30 16:41:14 -07003273 while (!transactionQueue.empty()) {
3274 const auto& transaction = transactionQueue.front();
3275 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003276 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003277 transaction.states)) {
3278 setTransactionFlags(eTransactionFlushNeeded);
3279 break;
3280 }
3281 transactions.push_back(transaction);
3282 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3283 mPendingInputWindowCommands, transaction.desiredPresentTime,
3284 transaction.buffer, transaction.callback,
3285 transaction.postTime, transaction.privileged,
3286 /*isMainThread*/ true);
3287 transactionQueue.pop();
3288 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003289 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003290
Valerie Haufce31b82019-04-30 16:41:14 -07003291 if (transactionQueue.empty()) {
3292 it = mTransactionQueues.erase(it);
3293 mTransactionCV.broadcast();
3294 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003295 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003296 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003297 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003298 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003299 return flushedATransaction;
3300}
3301
3302bool SurfaceFlinger::transactionFlushNeeded() {
3303 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003304}
3305
chaviwca27f252018-02-06 16:46:39 -08003306
Marissa Wall17b4e452018-12-26 16:32:34 -08003307bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003308 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003309 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003310 if (!useCachedExpectedPresentTime)
3311 populateExpectedPresentTime();
3312
3313 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003314 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3315 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3316 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3317 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3318 return false;
3319 }
3320
Marissa Wall713b63f2018-10-17 15:42:43 -07003321 for (const ComposerState& state : states) {
3322 const layer_state_t& s = state.state;
3323 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3324 continue;
3325 }
3326 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003327 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003328 }
3329 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003330 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003331}
3332
3333void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3334 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003335 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003336 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003337 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003338 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003339 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003340 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003341
Valerie Haubc6ddb12019-03-08 11:10:15 -08003342 const int64_t postTime = systemTime();
3343
Robert Carr14167e02019-02-13 13:50:55 -08003344 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3345
Mathias Agopian698c0872011-06-28 19:09:31 -07003346 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003347
Marissa Wall713b63f2018-10-17 15:42:43 -07003348 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003349 auto itr = mTransactionQueues.find(applyToken);
3350 // if this is an animation frame, wait until prior animation frame has
3351 // been applied by SF
3352 if (flags & eAnimation) {
3353 while (itr != mTransactionQueues.end()) {
3354 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3355 if (CC_UNLIKELY(err != NO_ERROR)) {
3356 ALOGW_IF(err == TIMED_OUT,
3357 "setTransactionState timed out "
3358 "waiting for animation frame to apply");
3359 break;
3360 }
3361 itr = mTransactionQueues.find(applyToken);
3362 }
3363 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003364
3365 // Expected present time is computed and cached on invalidate, so it may be stale.
3366 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3367 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003368 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003369 uncacheBuffer, listenerCallbacks, postTime,
3370 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003371 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003372 return;
3373 }
3374
Valerie Haubc6ddb12019-03-08 11:10:15 -08003375 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003376 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003377}
3378
3379void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003380 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003381 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003382 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003383 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003384 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003385 const int64_t postTime, bool privileged,
3386 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003387 uint32_t transactionFlags = 0;
3388
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003389 if (flags & eAnimation) {
3390 // For window updates that are part of an animation we must wait for
3391 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003392 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003393 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003394 if (CC_UNLIKELY(err != NO_ERROR)) {
3395 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003396 // caller after a few seconds.
3397 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3398 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003399 mAnimTransactionPending = false;
3400 break;
3401 }
3402 }
3403 }
3404
chaviwca27f252018-02-06 16:46:39 -08003405 for (const DisplayState& display : displays) {
3406 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003407 }
3408
Marissa Walld600d572019-03-26 15:38:50 -07003409 // In case the client has sent a Transaction that should receive callbacks but without any
3410 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3411 // to the callback thread so it can send an empty callback
3412 if (!listenerCallbacks.empty()) {
3413 mTransactionCompletedThread.run();
3414 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003415 for (const auto& listenerCallback : listenerCallbacks) {
3416 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003417 }
3418
Marissa Walle2ffb422018-10-12 11:33:52 -07003419 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003420 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003421 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3422 postTime, privileged);
3423 }
3424
Marissa Wallefb71af2019-06-27 14:45:53 -07003425 for (const auto& listenerCallback : listenerCallbacks) {
3426 mTransactionCompletedThread.endRegistration(listenerCallback);
3427 }
3428
Marissa Walle2ffb422018-10-12 11:33:52 -07003429 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003430 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003431 mTransactionCompletedThread.sendCallbacks();
3432 }
3433 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003434
chaviw273171b2018-12-26 11:46:30 -08003435 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3436
Marissa Wall947d34e2019-03-29 14:03:53 -07003437 if (uncacheBuffer.isValid()) {
3438 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003439 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003440 }
3441
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003442 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3443 // anyway. This can be used as a flush mechanism for previous async transactions.
3444 // Empty animation transaction can be used to simulate back-pressure, so also force a
3445 // transaction for empty animation transactions.
3446 if (transactionFlags == 0 &&
3447 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003448 transactionFlags = eTransactionNeeded;
3449 }
3450
Marissa Wall06255332019-03-27 13:48:27 -07003451 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3452 // so we don't have to wake up again next frame to preform an uneeded traversal.
3453 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3454 transactionFlags = transactionFlags & (~eTraversalNeeded);
3455 mTraversalNeededMainThread = true;
3456 }
3457
Mathias Agopian386aa982011-11-07 21:58:03 -08003458 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003459 if (mInterceptor->isEnabled()) {
3460 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003461 }
Irvel468051e2016-06-13 16:44:44 -07003462
Mathias Agopian386aa982011-11-07 21:58:03 -08003463 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003464 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3465 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003466 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003467
3468 // if this is a synchronous transaction, wait for it to take effect
3469 // before returning.
3470 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003471 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003472 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003473 if (flags & eAnimation) {
3474 mAnimTransactionPending = true;
3475 }
chaviw4fe36852019-04-15 16:25:49 -07003476 if (mPendingInputWindowCommands.syncInputWindows) {
3477 mPendingSyncInputWindows = true;
3478 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003479
3480 // applyTransactionState can be called by either the main SF thread or by
3481 // another process through setTransactionState. While a given process may wish
3482 // to wait on synchronous transactions, the main SF thread should never
3483 // be blocked. Therefore, we only wait if isMainThread is false.
3484 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003485 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3486 if (CC_UNLIKELY(err != NO_ERROR)) {
3487 // just in case something goes wrong in SF, return to the
3488 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003489 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3490 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003491 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003492 break;
3493 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003494 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003495 }
3496}
3497
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003498uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3499 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3500 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003501
Mathias Agopiane57f2922012-08-09 16:29:12 -07003502 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003503 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3504
3505 const uint32_t what = s.what;
3506 if (what & DisplayState::eSurfaceChanged) {
3507 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3508 state.surface = s.surface;
3509 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003510 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003511 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003512 if (what & DisplayState::eLayerStackChanged) {
3513 if (state.layerStack != s.layerStack) {
3514 state.layerStack = s.layerStack;
3515 flags |= eDisplayTransactionNeeded;
3516 }
3517 }
3518 if (what & DisplayState::eDisplayProjectionChanged) {
3519 if (state.orientation != s.orientation) {
3520 state.orientation = s.orientation;
3521 flags |= eDisplayTransactionNeeded;
3522 }
3523 if (state.frame != s.frame) {
3524 state.frame = s.frame;
3525 flags |= eDisplayTransactionNeeded;
3526 }
3527 if (state.viewport != s.viewport) {
3528 state.viewport = s.viewport;
3529 flags |= eDisplayTransactionNeeded;
3530 }
3531 }
3532 if (what & DisplayState::eDisplaySizeChanged) {
3533 if (state.width != s.width) {
3534 state.width = s.width;
3535 flags |= eDisplayTransactionNeeded;
3536 }
3537 if (state.height != s.height) {
3538 state.height = s.height;
3539 flags |= eDisplayTransactionNeeded;
3540 }
3541 }
3542
Mathias Agopiane57f2922012-08-09 16:29:12 -07003543 return flags;
3544}
3545
Robert Carr14167e02019-02-13 13:50:55 -08003546bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003547 IPCThreadState* ipc = IPCThreadState::self();
3548 const int pid = ipc->getCallingPid();
3549 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003550 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003551 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003552 return false;
3553 }
3554 return true;
3555}
3556
Marissa Wall3dad52d2019-03-22 14:03:19 -07003557uint32_t SurfaceFlinger::setClientStateLocked(
3558 const ComposerState& composerState, int64_t desiredPresentTime,
3559 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3560 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003561 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003562
Vishnu Nairf03652d2019-07-16 17:56:56 -07003563 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003564 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003565 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003566 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003567 new CallbackHandle(listenerCallback.transactionCompletedListener,
3568 listenerCallback.callbackIds, s.surface));
3569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 return 0;
3571 }
3572
chaviw8b3871a2017-11-01 17:41:01 -07003573 uint32_t flags = 0;
3574
Garfield Tan8a3083e2018-12-03 13:21:07 -08003575 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003576 bool geometryAppliesWithResize =
3577 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003578
3579 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3580 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003581 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003582 layer->pushPendingState();
3583 }
3584
chaviw8b3871a2017-11-01 17:41:01 -07003585 if (what & layer_state_t::ePositionChanged) {
3586 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3587 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003588 }
chaviw8b3871a2017-11-01 17:41:01 -07003589 }
3590 if (what & layer_state_t::eLayerChanged) {
3591 // NOTE: index needs to be calculated before we update the state
3592 const auto& p = layer->getParent();
3593 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003594 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003595 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003596 mCurrentState.layersSortedByZ.removeAt(idx);
3597 mCurrentState.layersSortedByZ.add(layer);
3598 // we need traversal (state changed)
3599 // AND transaction (list changed)
3600 flags |= eTransactionNeeded|eTraversalNeeded;
3601 }
chaviw8b3871a2017-11-01 17:41:01 -07003602 } else {
3603 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003604 flags |= eTransactionNeeded|eTraversalNeeded;
3605 }
3606 }
chaviw8b3871a2017-11-01 17:41:01 -07003607 }
3608 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003609 // NOTE: index needs to be calculated before we update the state
3610 const auto& p = layer->getParent();
3611 if (p == nullptr) {
3612 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3613 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3614 mCurrentState.layersSortedByZ.removeAt(idx);
3615 mCurrentState.layersSortedByZ.add(layer);
3616 // we need traversal (state changed)
3617 // AND transaction (list changed)
3618 flags |= eTransactionNeeded|eTraversalNeeded;
3619 }
3620 } else {
3621 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3622 flags |= eTransactionNeeded|eTraversalNeeded;
3623 }
chaviw8b3871a2017-11-01 17:41:01 -07003624 }
3625 }
3626 if (what & layer_state_t::eSizeChanged) {
3627 if (layer->setSize(s.w, s.h)) {
3628 flags |= eTraversalNeeded;
3629 }
3630 }
3631 if (what & layer_state_t::eAlphaChanged) {
3632 if (layer->setAlpha(s.alpha))
3633 flags |= eTraversalNeeded;
3634 }
3635 if (what & layer_state_t::eColorChanged) {
3636 if (layer->setColor(s.color))
3637 flags |= eTraversalNeeded;
3638 }
Peiyong Lind3788632018-09-18 16:01:31 -07003639 if (what & layer_state_t::eColorTransformChanged) {
3640 if (layer->setColorTransform(s.colorTransform)) {
3641 flags |= eTraversalNeeded;
3642 }
3643 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003644 if (what & layer_state_t::eBackgroundColorChanged) {
3645 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3646 flags |= eTraversalNeeded;
3647 }
3648 }
chaviw8b3871a2017-11-01 17:41:01 -07003649 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003650 // TODO: b/109894387
3651 //
3652 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3653 // rotation. To see the problem observe that if we have a square parent, and a child
3654 // of the same size, then we rotate the child 45 degrees around it's center, the child
3655 // must now be cropped to a non rectangular 8 sided region.
3656 //
3657 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3658 // private API, and the WindowManager only uses rotation in one case, which is on a top
3659 // level layer in which cropping is not an issue.
3660 //
3661 // However given that abuse of rotation matrices could lead to surfaces extending outside
3662 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3663 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3664 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003665 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003666 flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eTransparentRegionChanged) {
3669 if (layer->setTransparentRegionHint(s.transparentRegion))
3670 flags |= eTraversalNeeded;
3671 }
3672 if (what & layer_state_t::eFlagsChanged) {
3673 if (layer->setFlags(s.flags, s.mask))
3674 flags |= eTraversalNeeded;
3675 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003676 if (what & layer_state_t::eCropChanged_legacy) {
3677 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003678 flags |= eTraversalNeeded;
3679 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003680 if (what & layer_state_t::eCornerRadiusChanged) {
3681 if (layer->setCornerRadius(s.cornerRadius))
3682 flags |= eTraversalNeeded;
3683 }
chaviw8b3871a2017-11-01 17:41:01 -07003684 if (what & layer_state_t::eLayerStackChanged) {
3685 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3686 // We only allow setting layer stacks for top level layers,
3687 // everything else inherits layer stack from its parent.
3688 if (layer->hasParent()) {
3689 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3690 layer->getName().string());
3691 } else if (idx < 0) {
3692 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3693 "that also does not appear in the top level layer list. Something"
3694 " has gone wrong.", layer->getName().string());
3695 } else if (layer->setLayerStack(s.layerStack)) {
3696 mCurrentState.layersSortedByZ.removeAt(idx);
3697 mCurrentState.layersSortedByZ.add(layer);
3698 // we need traversal (state changed)
3699 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003700 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003701 }
3702 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003703 if (what & layer_state_t::eDeferTransaction_legacy) {
3704 if (s.barrierHandle_legacy != nullptr) {
3705 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3706 } else if (s.barrierGbp_legacy != nullptr) {
3707 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003708 if (authenticateSurfaceTextureLocked(gbp)) {
3709 const auto& otherLayer =
3710 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003711 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003712 } else {
3713 ALOGE("Attempt to defer transaction to to an"
3714 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003715 }
3716 }
chaviw8b3871a2017-11-01 17:41:01 -07003717 // We don't trigger a traversal here because if no other state is
3718 // changed, we don't want this to cause any more work
3719 }
chaviw8b3871a2017-11-01 17:41:01 -07003720 if (what & layer_state_t::eReparentChildren) {
3721 if (layer->reparentChildren(s.reparentHandle)) {
3722 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003723 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003724 }
chaviw8b3871a2017-11-01 17:41:01 -07003725 if (what & layer_state_t::eDetachChildren) {
3726 layer->detachChildren();
3727 }
3728 if (what & layer_state_t::eOverrideScalingModeChanged) {
3729 layer->setOverrideScalingMode(s.overrideScalingMode);
3730 // We don't trigger a traversal here because if no other state is
3731 // changed, we don't want this to cause any more work
3732 }
Marissa Wall61c58622018-07-18 10:12:20 -07003733 if (what & layer_state_t::eTransformChanged) {
3734 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3735 }
3736 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3737 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3738 flags |= eTraversalNeeded;
3739 }
3740 if (what & layer_state_t::eCropChanged) {
3741 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3742 }
Marissa Wall861616d2018-10-22 12:52:23 -07003743 if (what & layer_state_t::eFrameChanged) {
3744 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3745 }
Marissa Wall61c58622018-07-18 10:12:20 -07003746 if (what & layer_state_t::eAcquireFenceChanged) {
3747 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3748 }
3749 if (what & layer_state_t::eDataspaceChanged) {
3750 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3751 }
3752 if (what & layer_state_t::eHdrMetadataChanged) {
3753 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3754 }
3755 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3756 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3757 }
3758 if (what & layer_state_t::eApiChanged) {
3759 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3760 }
3761 if (what & layer_state_t::eSidebandStreamChanged) {
3762 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3763 }
Robert Carr720e5062018-07-30 17:45:14 -07003764 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003765 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003766 layer->setInputInfo(s.inputInfo);
3767 flags |= eTraversalNeeded;
3768 } else {
3769 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3770 }
Robert Carr720e5062018-07-30 17:45:14 -07003771 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003772 if (what & layer_state_t::eMetadataChanged) {
3773 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3774 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003775 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3776 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3777 flags |= eTraversalNeeded;
3778 }
3779 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003780 // This has to happen after we reparent children because when we reparent to null we remove
3781 // child layers from current state and remove its relative z. If the children are reparented in
3782 // the same transaction, then we have to make sure we reparent the children first so we do not
3783 // lose its relative z order.
3784 if (what & layer_state_t::eReparent) {
3785 bool hadParent = layer->hasParent();
3786 if (layer->reparent(s.parentHandleForChild)) {
3787 if (!hadParent) {
3788 mCurrentState.layersSortedByZ.remove(layer);
3789 }
3790 flags |= eTransactionNeeded | eTraversalNeeded;
3791 }
3792 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003793 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07003794 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003795 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003796 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3797 }
3798 }
Marissa Wall78b72202019-03-15 14:58:34 -07003799 bool bufferChanged = what & layer_state_t::eBufferChanged;
3800 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3801 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003802 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003803 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003804 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3805 if (success) {
3806 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3807 success = ClientCache::getInstance()
3808 .registerErasedRecipient(s.cachedBuffer,
3809 wp<ClientCache::ErasedRecipient>(this));
3810 if (!success) {
3811 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3812 }
3813 }
Marissa Wall78b72202019-03-15 14:58:34 -07003814 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003815 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003816 } else if (bufferChanged) {
3817 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003818 }
Marissa Wall78b72202019-03-15 14:58:34 -07003819 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003820 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003821 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003822 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003823 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003824 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3825 // Do not put anything that updates layer state or modifies flags after
3826 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003827 return flags;
3828}
3829
chaviw273171b2018-12-26 11:46:30 -08003830uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3831 uint32_t flags = 0;
3832 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3833 flags |= eTraversalNeeded;
3834 }
3835
chaviwa911b102019-02-14 10:18:33 -08003836 if (inputWindowCommands.syncInputWindows) {
3837 flags |= eTraversalNeeded;
3838 }
3839
Vishnu Nairec0ab382019-02-13 15:32:56 -08003840 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003841 return flags;
3842}
3843
Marissa Wall2d814fb2019-04-09 18:52:57 +00003844status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3845 uint32_t h, PixelFormat format, uint32_t flags,
3846 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003847 sp<IGraphicBufferProducer>* gbp,
3848 const sp<IBinder>& parentHandle,
3849 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003850 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003851 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003852 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003853 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003854 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003855
Robert Carrc0df3122019-04-11 13:18:21 -07003856 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3857 "Expected only one of parentLayer or parentHandle to be non-null. "
3858 "Programmer error?");
3859
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003860 status_t result = NO_ERROR;
3861
3862 sp<Layer> layer;
3863
Cody Northropbc755282017-03-31 12:00:08 -06003864 String8 uniqueName = getUniqueLayerName(name);
3865
Evan Roskya1f1e152019-01-24 16:17:46 -08003866 bool primaryDisplayOnly = false;
3867
3868 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3869 // TODO b/64227542
3870 if (metadata.has(METADATA_WINDOW_TYPE)) {
3871 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3872 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003873 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003874 primaryDisplayOnly = true;
3875 }
3876 }
3877
Mathias Agopian3165cc22012-08-08 19:42:09 -07003878 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003879 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003880 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3881 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003882
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003883 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003884 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003885 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3886 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003887 break;
chaviw13fdc492017-06-27 12:40:18 -07003888 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003889 // check if buffer size is set for color layer.
3890 if (w > 0 || h > 0) {
3891 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3892 int(w), int(h));
3893 return BAD_VALUE;
3894 }
3895
Evan Roskya1f1e152019-01-24 16:17:46 -08003896 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3897 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003898 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003899 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003900 // check if buffer size is set for container layer.
3901 if (w > 0 || h > 0) {
3902 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3903 int(w), int(h));
3904 return BAD_VALUE;
3905 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003906 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3907 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003908 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003909 default:
3910 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003911 break;
3912 }
3913
Dan Stoza7d89d062015-04-30 13:29:25 -07003914 if (result != NO_ERROR) {
3915 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003916 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003917
Evan Roskya1f1e152019-01-24 16:17:46 -08003918 if (primaryDisplayOnly) {
3919 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003920 }
3921
Robert Carrb89ea9d2018-12-10 13:01:14 -08003922 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003923 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3924 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003925 if (result != NO_ERROR) {
3926 return result;
3927 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003928 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003929
3930 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003931 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932}
3933
Cody Northropbc755282017-03-31 12:00:08 -06003934String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3935{
3936 bool matchFound = true;
3937 uint32_t dupeCounter = 0;
3938
3939 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3940 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3941
Dan Stoza436ccf32018-06-21 12:10:12 -07003942 // Grab the state lock since we're accessing mCurrentState
3943 Mutex::Autolock lock(mStateLock);
3944
Cody Northropbc755282017-03-31 12:00:08 -06003945 // Loop over layers until we're sure there is no matching name
3946 while (matchFound) {
3947 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003948 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003949 if (layer->getName() == uniqueName) {
3950 matchFound = true;
3951 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3952 }
3953 });
3954 }
3955
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003956 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3957 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003958
3959 return uniqueName;
3960}
3961
Marissa Wallfd668622018-05-10 10:21:13 -07003962status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3963 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003964 LayerMetadata metadata, PixelFormat& format,
3965 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003966 sp<IGraphicBufferProducer>* gbp,
3967 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003968 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003969 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003970 case PIXEL_FORMAT_TRANSPARENT:
3971 case PIXEL_FORMAT_TRANSLUCENT:
3972 format = PIXEL_FORMAT_RGBA_8888;
3973 break;
3974 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003975 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003976 break;
3977 }
3978
Evan Roskya1f1e152019-01-24 16:17:46 -08003979 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
3980 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07003981 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003982 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003983 *handle = layer->getHandle();
3984 *gbp = layer->getProducer();
3985 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003986 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003987
Marissa Wallfd668622018-05-10 10:21:13 -07003988 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003989 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990}
3991
Marissa Wall61c58622018-07-18 10:12:20 -07003992status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3993 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003994 LayerMetadata metadata, sp<IBinder>* handle,
3995 sp<Layer>* outLayer) {
3996 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
3997 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07003998 *handle = layer->getHandle();
3999 *outLayer = layer;
4000
4001 return NO_ERROR;
4002}
4003
Evan Roskya1f1e152019-01-24 16:17:46 -08004004status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4005 uint32_t h, uint32_t flags, LayerMetadata metadata,
4006 sp<IBinder>* handle, sp<Layer>* outLayer) {
4007 *outLayer = getFactory().createColorLayer(
4008 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004009 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004010 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004011}
4012
Evan Roskya1f1e152019-01-24 16:17:46 -08004013status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4014 uint32_t w, uint32_t h, uint32_t flags,
4015 LayerMetadata metadata, sp<IBinder>* handle,
4016 sp<Layer>* outLayer) {
4017 *outLayer = getFactory().createContainerLayer(
4018 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004019 *handle = (*outLayer)->getHandle();
4020 return NO_ERROR;
4021}
4022
4023
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004024void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004025 mLayersPendingRemoval.add(layer);
4026 mLayersRemoved = true;
4027 setTransactionFlags(eTransactionNeeded);
4028}
4029
Robert Carr695d5282018-12-18 15:27:58 -08004030void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004031{
Robert Carr2e102c92018-10-23 12:11:15 -07004032 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004033 // If a layer has a parent, we allow it to out-live it's handle
4034 // with the idea that the parent holds a reference and will eventually
4035 // be cleaned up. However no one cleans up the top-level so we do so
4036 // here.
4037 if (layer->getParent() == nullptr) {
4038 mCurrentState.layersSortedByZ.remove(layer);
4039 }
4040 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004041
4042 auto it = mLayersByLocalBinderToken.begin();
4043 while (it != mLayersByLocalBinderToken.end()) {
4044 if (it->second == layer) {
4045 it = mLayersByLocalBinderToken.erase(it);
4046 } else {
4047 it++;
4048 }
4049 }
4050
Robert Carr695d5282018-12-18 15:27:58 -08004051 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004052}
4053
Mathias Agopianb60314a2012-04-10 22:09:54 -07004054// ---------------------------------------------------------------------------
4055
Andy McFadden13a082e2012-08-24 10:16:42 -07004056void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004057 const auto display = getDefaultDisplayDeviceLocked();
4058 if (!display) return;
4059
4060 const sp<IBinder> token = display->getDisplayToken().promote();
4061 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004062
Jesse Hall01e29052013-02-19 16:13:35 -08004063 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004064 Vector<ComposerState> state;
4065 Vector<DisplayState> displays;
4066 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004067 d.what = DisplayState::eDisplayProjectionChanged |
4068 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004069 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004070 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004071 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004072 d.frame.makeInvalid();
4073 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004074 d.width = 0;
4075 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004076 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004077 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004078
Dominik Laskowskie9774092018-12-11 10:04:24 -08004079 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004080
Dominik Laskowski83b88212018-12-11 13:34:06 -08004081 const nsecs_t vsyncPeriod = getVsyncPeriod();
4082 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004083
Brian Andersond0010582017-03-07 13:20:31 -08004084 // Use phase of 0 since phase is not known.
4085 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004086 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004087 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004088}
4089
4090void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004091 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004092 postMessageAsync(
4093 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004094}
4095
Ady Abraham27c70212019-06-11 10:52:26 -07004096void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4097 if (mHWCVsyncState != enabled) {
4098 getHwComposer().setVsyncEnabled(displayId, enabled);
4099 mHWCVsyncState = enabled;
4100 }
4101}
4102
Dominik Laskowskie9774092018-12-11 10:04:24 -08004103void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 if (display->isVirtual()) {
4105 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004106 return;
4107 }
4108
Dominik Laskowski075d3172018-05-24 15:50:06 -07004109 const auto displayId = display->getId();
4110 LOG_ALWAYS_FATAL_IF(!displayId);
4111
Dominik Laskowski34157762018-10-31 13:07:19 -07004112 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004113
4114 int currentMode = display->getPowerMode();
4115 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004116 return;
4117 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004119 display->setPowerMode(mode);
4120
Lloyd Pique4dccc412018-01-22 17:21:36 -08004121 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004122 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004123 }
4124
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004125 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004126 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004128 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004129 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004130 mScheduler->onScreenAcquired(mAppConnectionHandle);
4131 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004132 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004133
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004134 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004135 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004136 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004137
4138 struct sched_param param = {0};
4139 param.sched_priority = 1;
4140 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4141 ALOGW("Couldn't set SCHED_FIFO on display on");
4142 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004143 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004144 // Turn off the display
4145 struct sched_param param = {0};
4146 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4147 ALOGW("Couldn't set SCHED_OTHER on display off");
4148 }
4149
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004150 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004151 mScheduler->disableHardwareVsync(true);
4152 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004153 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004154
Ady Abraham27c70212019-06-11 10:52:26 -07004155 // Make sure HWVsync is disabled before turning off the display
4156 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4157
Dominik Laskowski075d3172018-05-24 15:50:06 -07004158 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004159 mVisibleRegionsDirty = true;
4160 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004161 } else if (mode == HWC_POWER_MODE_DOZE ||
4162 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004163 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004164 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004165 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004166 mScheduler->onScreenAcquired(mAppConnectionHandle);
4167 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004168 }
4169 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4170 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004172 mScheduler->disableHardwareVsync(true);
4173 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004174 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004175 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004176 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004177 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004178 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004179 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004180
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004181 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004182 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004183 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004184 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004185 }
4186
Dominik Laskowski34157762018-10-31 13:07:19 -07004187 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004188}
4189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004190void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004191 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004192 const auto display = getDisplayDevice(displayToken);
4193 if (!display) {
4194 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4195 displayToken.get());
4196 } else if (display->isVirtual()) {
4197 ALOGW("Attempt to set power mode %d for virtual display", mode);
4198 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004199 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004200 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004201 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004202}
4203
4204// ---------------------------------------------------------------------------
4205
Dominik Laskowskic2867142019-01-21 11:33:38 -08004206status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4207 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004208 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004209
Mathias Agopianbd115332013-04-18 16:41:04 -07004210 IPCThreadState* ipc = IPCThreadState::self();
4211 const int pid = ipc->getCallingPid();
4212 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004213
Mathias Agopianbd115332013-04-18 16:41:04 -07004214 if ((uid != AID_SHELL) &&
4215 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004216 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4217 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004218 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004219 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004220 // (this would indicate SF is stuck, but we want to be able to
4221 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004222 status_t err = mStateLock.timedLock(s2ns(1));
4223 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004224 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004225 StringAppendF(&result,
4226 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4227 "(no locks held)\n",
4228 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004229 }
4230
Dominik Laskowskic2867142019-01-21 11:33:38 -08004231 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004232
Dominik Laskowskic2867142019-01-21 11:33:38 -08004233 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004234 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004235 {"--dispsync"s,
4236 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004237 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4238 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4239 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4240 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4241 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4242 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004243 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004244 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4245 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004246
Dominik Laskowskic2867142019-01-21 11:33:38 -08004247 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004248
Dominik Laskowski46470112019-08-02 13:13:11 -07004249 const auto it = dumpers.find(flag);
4250 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004251 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004252 } else if (!asProto) {
4253 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004254 }
4255
Mathias Agopian9795c422009-08-26 16:36:26 -07004256 if (locked) {
4257 mStateLock.unlock();
4258 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004259
Dominik Laskowski46470112019-08-02 13:13:11 -07004260 if (it == dumpers.end()) {
4261 const LayersProto layersProto = dumpProtoFromMainThread();
4262 if (asProto) {
4263 result.append(layersProto.SerializeAsString());
4264 } else {
4265 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4266 result.append(LayerProtoParser::layerTreeToString(layerTree));
4267 result.append("\n");
4268 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004269 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004270 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004271 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004272 return NO_ERROR;
4273}
4274
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004275status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4276 if (asProto && mTracing.isEnabled()) {
4277 mTracing.writeToFileAsync();
4278 }
4279
4280 return doDump(fd, DumpArgs(), asProto);
4281}
4282
Dominik Laskowskic2867142019-01-21 11:33:38 -08004283void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004284 mCurrentState.traverseInZOrder(
4285 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004286}
4287
Dominik Laskowskic2867142019-01-21 11:33:38 -08004288void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004289 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004290
Dominik Laskowskic2867142019-01-21 11:33:38 -08004291 if (args.size() > 1) {
4292 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004293 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004294 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004295 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004296 }
Robert Carr2047fae2016-11-28 14:09:09 -08004297 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004298 } else {
4299 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004300 }
4301}
4302
Dominik Laskowskic2867142019-01-21 11:33:38 -08004303void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004304 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004305 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004306 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004307 }
Robert Carr2047fae2016-11-28 14:09:09 -08004308 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004309
Svetoslavd85084b2014-03-20 10:28:31 -07004310 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004311}
4312
Dominik Laskowskic2867142019-01-21 11:33:38 -08004313void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4314 mTimeStats->parseArgs(asProto, args, result);
4315}
4316
Jamie Gennis6547ff42013-07-16 20:12:42 -07004317// This should only be called from the main thread. Otherwise it would need
4318// the lock and should use mCurrentState rather than mDrawingState.
4319void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004320 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004321 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004322 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004323
4324 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4325}
4326
Yiwei Zhang5434a782018-12-05 18:06:32 -08004327void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004328 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004329
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004330 if (isLayerTripleBufferingDisabled())
4331 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004332
Yiwei Zhang5434a782018-12-05 18:06:32 -08004333 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4334 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4335 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4336 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4337 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4338 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004339 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004340}
4341
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004342void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004343 mScheduler->dump(result);
4344 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
4345
4346 mRefreshRateStats.dump(result);
4347 result.append("\n");
4348
Ana Krulec757f63a2019-01-25 10:46:18 -08004349 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004350 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004351 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004352 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004353
Ady Abraham42b3beb2019-07-09 18:09:52 -07004354 StringAppendF(&result, "Allowed Display Configs: ");
Dominik Laskowski98041832019-08-01 18:35:59 -07004355 for (const auto& [type, rate] : mRefreshRateConfigs.getRefreshRates()) {
4356 if (rate && isDisplayConfigAllowed(rate->configId)) {
4357 StringAppendF(&result, "%" PRIu32 " Hz, ", rate->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004358 }
4359 }
4360 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4361 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004362
Ana Krulecc2870422019-01-29 19:00:58 -08004363 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004364}
4365
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4367 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004368 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4369 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004370 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004371 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004372 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004373 }
David Sodman4a36e932017-11-07 14:29:47 -08004374 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004375 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004376 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004377 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4378 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004379}
4380
Dan Stozae77c7662016-05-13 11:37:28 -07004381void SurfaceFlinger::recordBufferingStats(const char* layerName,
4382 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004383 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4384 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004385 for (const auto& segment : history) {
4386 if (!segment.usedThirdBuffer) {
4387 stats.twoBufferTime += segment.totalTime;
4388 }
4389 if (segment.occupancyAverage < 1.0f) {
4390 stats.doubleBufferedTime += segment.totalTime;
4391 } else if (segment.occupancyAverage < 2.0f) {
4392 stats.tripleBufferedTime += segment.totalTime;
4393 }
4394 ++stats.numSegments;
4395 stats.totalTime += segment.totalTime;
4396 }
4397}
4398
Yiwei Zhang5434a782018-12-05 18:06:32 -08004399void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4400 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004401
4402 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4403 const size_t count = currentLayers.size();
4404 for (size_t i=0 ; i<count ; i++) {
4405 currentLayers[i]->dumpFrameEvents(result);
4406 }
4407}
4408
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004410 result.append("Buffering stats:\n");
4411 result.append(" [Layer name] <Active time> <Two buffer> "
4412 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004413 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004414 typedef std::tuple<std::string, float, float, float> BufferTuple;
4415 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004416 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004417 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004418 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004419 if (stats.numSegments == 0) {
4420 continue;
4421 }
4422 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4423 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4424 stats.totalTime;
4425 float doubleBufferRatio = static_cast<float>(
4426 stats.doubleBufferedTime) / stats.totalTime;
4427 float tripleBufferRatio = static_cast<float>(
4428 stats.tripleBufferedTime) / stats.totalTime;
4429 sorted.insert({activeTime, {name, twoBufferRatio,
4430 doubleBufferRatio, tripleBufferRatio}});
4431 }
4432 for (const auto& sortedPair : sorted) {
4433 float activeTime = sortedPair.first;
4434 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004435 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4436 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004437 }
4438 result.append("\n");
4439}
4440
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004442 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004443 const auto displayId = display->getId();
4444 if (!displayId) {
4445 continue;
4446 }
4447 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004448 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004449 continue;
4450 }
4451
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452 StringAppendF(&result,
4453 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4454 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004455 uint8_t port;
4456 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004457 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004458 result.append("no identification data\n");
4459 continue;
4460 }
4461
4462 if (!isEdid(data)) {
4463 result.append("unknown identification data: ");
4464 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004466 }
4467 result.append("\n");
4468 continue;
4469 }
4470
4471 const auto edid = parseEdid(data);
4472 if (!edid) {
4473 result.append("invalid EDID: ");
4474 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004476 }
4477 result.append("\n");
4478 continue;
4479 }
4480
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004482 result.append(edid->displayName.data(), edid->displayName.length());
4483 result.append("\"\n");
4484 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004485}
4486
Yiwei Zhang5434a782018-12-05 18:06:32 -08004487void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004488 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4490 StringAppendF(&result, "DisplayColorSetting: %s\n",
4491 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004492
4493 // TODO: print out if wide-color mode is active or not
4494
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004495 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004496 const auto displayId = display->getId();
4497 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004498 continue;
4499 }
4500
Yiwei Zhang5434a782018-12-05 18:06:32 -08004501 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004502 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004503 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004505 }
4506
Lloyd Pique32cbe282018-10-19 13:09:22 -07004507 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 StringAppendF(&result, " Current color mode: %s (%d)\n",
4509 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004510 }
4511 result.append("\n");
4512}
4513
Vishnu Nair8406fd72019-07-30 11:29:31 -07004514LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004515 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004516 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004517 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004518 layer->writeToProtoDrawingState(layerProto, traceFlags);
4519 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004520 });
4521
4522 return layersProto;
4523}
4524
Vishnu Nair8406fd72019-07-30 11:29:31 -07004525LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4526 LayersProto layersProto;
4527 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4528 return layersProto;
4529}
4530
Dominik Laskowskic2867142019-01-21 11:33:38 -08004531void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4532 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004533 Colorizer colorizer(colorize);
4534
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535 // figure out if we're stuck somewhere
4536 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004537 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004538 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4539
4540 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004541 * Dump library configuration.
4542 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004543
4544 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004545 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004546 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004547 appendSfConfigString(result);
4548 appendUiConfigString(result);
4549 appendGuiConfigString(result);
4550 result.append("\n");
4551
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004552 result.append("\nDisplay identification data:\n");
4553 dumpDisplayIdentificationData(result);
4554
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004555 result.append("\nWide-Color information:\n");
4556 dumpWideColorInfo(result);
4557
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004558 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004559 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004560 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004561 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004562 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004563
Andy McFadden41d67d72014-04-25 16:58:34 -07004564 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004565 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004566 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004567 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004568 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004569
Dan Stozab90cf072015-03-05 11:05:59 -08004570 dumpStaticScreenStats(result);
4571 result.append("\n");
4572
Alec Mouri40189b02019-03-05 15:07:54 -08004573 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4574 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4575 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004576
Dan Stozae77c7662016-05-13 11:37:28 -07004577 dumpBufferingStats(result);
4578
Andy McFadden4803b742012-09-24 19:07:20 -07004579 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004580 * Dump the visible layer list
4581 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004582 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004583 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004584 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4585 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004586 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004587
Chia-I Wu2f884132018-09-13 15:17:58 -07004588 {
Lloyd Pique207def92019-02-28 16:09:52 -08004589 StringAppendF(&result, "Composition layers\n");
4590 mDrawingState.traverseInZOrder([&](Layer* layer) {
4591 auto compositionLayer = layer->getCompositionLayer();
4592 if (compositionLayer) compositionLayer->dump(result);
4593 });
4594 }
4595
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004596 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004597 * Dump Display state
4598 */
4599
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004600 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004602 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004603 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004604 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004605 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004606 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004607
4608 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609 * Dump SurfaceFlinger global state
4610 */
4611
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004613 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004616 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004618 DebugEGLImageTracker::getInstance()->dump(result);
4619
Dominik Laskowski075d3172018-05-24 15:50:06 -07004620 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004621 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4622 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4624 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004625 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result,
4627 " transaction-flags : %08x\n"
4628 " gpu_to_cpu_unsupported : %d\n",
4629 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004630
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004631 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004632 displayId && getHwComposer().isConnected(*displayId)) {
4633 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004634 StringAppendF(&result,
4635 " refresh-rate : %f fps\n"
4636 " x-dpi : %f\n"
4637 " y-dpi : %f\n",
4638 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4639 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004640 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643
Dan Stozae22aec72016-08-01 13:20:59 -07004644 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004645 * Tracing state
4646 */
4647 mTracing.dump(result);
4648 result.append("\n");
4649
4650 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004651 * HWC layer minidump
4652 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004653 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004654 const auto displayId = display->getId();
4655 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004656 continue;
4657 }
4658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004660 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004661 const sp<DisplayDevice> displayDevice = display;
4662 mCurrentState.traverseInZOrder(
4663 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004664 result.append("\n");
4665 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004666
4667 /*
4668 * Dump HWComposer state
4669 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004670 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004671 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004672 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004673 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004674 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004675 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676
4677 /*
4678 * Dump gralloc state
4679 */
4680 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4681 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004682
4683 /*
4684 * Dump VrFlinger state if in use.
4685 */
4686 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4687 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004689 result.append("\n");
4690 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004691
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004692 result.append(mTimeStats->miniDump());
4693 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694}
4695
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696void SurfaceFlinger::updateColorMatrixLocked() {
4697 mat4 colorMatrix;
4698 if (mGlobalSaturationFactor != 1.0f) {
4699 // Rec.709 luma coefficients
4700 float3 luminance{0.213f, 0.715f, 0.072f};
4701 luminance *= 1.0f - mGlobalSaturationFactor;
4702 mat4 saturationMatrix = mat4(
4703 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4704 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4705 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4706 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4707 );
4708 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4709 } else {
4710 colorMatrix = mClientColorMatrix * mDaltonizer();
4711 }
4712
4713 if (mCurrentState.colorMatrix != colorMatrix) {
4714 mCurrentState.colorMatrix = colorMatrix;
4715 mCurrentState.colorMatrixChanged = true;
4716 setTransactionFlags(eTransactionNeeded);
4717 }
4718}
4719
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004720status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004721#pragma clang diagnostic push
4722#pragma clang diagnostic error "-Wswitch-enum"
4723 switch (static_cast<ISurfaceComposerTag>(code)) {
4724 // These methods should at minimum make sure that the client requested
4725 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004726 case BOOT_FINISHED:
4727 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 case CREATE_DISPLAY:
4729 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004730 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731 case GET_ANIMATION_FRAME_STATS:
4732 case GET_HDR_CAPABILITIES:
4733 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004734 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004735 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004736 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004737 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004738 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004739 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004740 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004741 case GET_DISPLAYED_CONTENT_SAMPLE:
4742 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004743 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4744 IPCThreadState* ipc = IPCThreadState::self();
4745 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4746 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004747 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004748 }
Robert Carr1db73f62016-12-21 12:58:51 -08004749 return OK;
4750 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004751 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004752 IPCThreadState* ipc = IPCThreadState::self();
4753 const int pid = ipc->getCallingPid();
4754 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4756 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004757 return PERMISSION_DENIED;
4758 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004759 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004760 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004761 // Used by apps to hook Choreographer to SurfaceFlinger.
4762 case CREATE_DISPLAY_EVENT_CONNECTION:
4763 // The following calls are currently used by clients that do not
4764 // request necessary permissions. However, they do not expose any secret
4765 // information, so it is OK to pass them.
4766 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004767 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004768 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004769 case GET_PHYSICAL_DISPLAY_IDS:
4770 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004771 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004772 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004773 case GET_DISPLAY_CONFIGS:
4774 case GET_DISPLAY_STATS:
4775 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4776 // Calling setTransactionState is safe, because you need to have been
4777 // granted a reference to Client* and Handle* to do anything with it.
4778 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004779 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004780 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004781 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004782 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004783 case IS_WIDE_COLOR_DISPLAY:
4784 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4785 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786 return OK;
4787 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004788 case CAPTURE_LAYERS: {
4789 IPCThreadState* ipc = IPCThreadState::self();
4790 const int pid = ipc->getCallingPid();
4791 const int uid = ipc->getCallingUid();
4792 // allow media to capture layer for video thumbnails
4793 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4794 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4795 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4796 return PERMISSION_DENIED;
4797 }
4798 return OK;
4799 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004800 case CAPTURE_SCREEN:
4801 case ADD_REGION_SAMPLING_LISTENER:
4802 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004803 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004804 IPCThreadState* ipc = IPCThreadState::self();
4805 const int pid = ipc->getCallingPid();
4806 const int uid = ipc->getCallingUid();
4807 if ((uid != AID_GRAPHICS) &&
4808 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4809 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4810 return PERMISSION_DENIED;
4811 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 return OK;
4813 }
4814 // The following codes are deprecated and should never be allowed to access SF.
4815 case CONNECT_DISPLAY_UNUSED:
4816 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4817 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4818 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004819 }
chaviw93df2ea2019-04-30 16:45:12 -07004820 case CAPTURE_SCREEN_BY_ID: {
4821 IPCThreadState* ipc = IPCThreadState::self();
4822 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004823 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004824 return OK;
4825 }
4826 return PERMISSION_DENIED;
4827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004828 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004829
4830 // These codes are used for the IBinder protocol to either interrogate the recipient
4831 // side of the transaction for its canonical interface descriptor or to dump its state.
4832 // We let them pass by default.
4833 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4834 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4835 code == IBinder::SYSPROPS_TRANSACTION) {
4836 return OK;
4837 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004838 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004840 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4842 return OK;
4843 }
4844 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4845 return PERMISSION_DENIED;
4846#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004847}
4848
Ana Krulec13be8ad2018-08-21 02:43:56 +00004849status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4850 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004851 status_t credentialCheck = CheckTransactCodeCredentials(code);
4852 if (credentialCheck != OK) {
4853 return credentialCheck;
4854 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004855
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004856 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4857 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004858 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004859 IPCThreadState* ipc = IPCThreadState::self();
4860 const int uid = ipc->getCallingUid();
4861 if (CC_UNLIKELY(uid != AID_SYSTEM
4862 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004863 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004864 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004865 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004866 return PERMISSION_DENIED;
4867 }
4868 int n;
4869 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004870 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004871 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 return NO_ERROR;
4873 case 1002: // SHOW_UPDATES
4874 n = data.readInt32();
4875 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004876 invalidateHwcGeometry();
4877 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004878 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004880 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004881 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004882 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004883 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004884 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004885 setTransactionFlags(
4886 eTransactionNeeded|
4887 eDisplayTransactionNeeded|
4888 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004889 return NO_ERROR;
4890 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004891 case 1006:{ // send empty update
4892 signalRefresh();
4893 return NO_ERROR;
4894 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004895 case 1008: // toggle use of hw composer
4896 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004897 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004898 invalidateHwcGeometry();
4899 repaintEverything();
4900 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004901 case 1009: // toggle use of transform hint
4902 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004903 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004904 invalidateHwcGeometry();
4905 repaintEverything();
4906 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004907 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004908 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004909 reply->writeInt32(0);
4910 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004911 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004912 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 return NO_ERROR;
4914 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004915 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004916 if (!display) {
4917 return NAME_NOT_FOUND;
4918 }
4919
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004920 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004921 return NO_ERROR;
4922 }
4923 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004924 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004925 // daltonize
4926 n = data.readInt32();
4927 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004928 case 1:
4929 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4930 break;
4931 case 2:
4932 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4933 break;
4934 case 3:
4935 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4936 break;
4937 default:
4938 mDaltonizer.setType(ColorBlindnessType::None);
4939 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004940 }
4941 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004942 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004943 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004944 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004945 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004946
4947 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004948 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004949 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004950 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004951 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004952 // apply a color matrix
4953 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004954 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004955 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004956 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004957 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004958 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004959 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004960 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004961 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004962 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004963 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004964
4965 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4966 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004968 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4969 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4970 }
4971
Chia-I Wu28f320b2018-05-03 11:02:56 -07004972 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004973 return NO_ERROR;
4974 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004975 case 1016: { // Unused.
4976 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004977 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004978 case 1017: {
4979 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004980 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004981 return NO_ERROR;
4982 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004983 case 1018: { // Modify Choreographer's phase offset
4984 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004985 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004986 return NO_ERROR;
4987 }
4988 case 1019: { // Modify SurfaceFlinger's phase offset
4989 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004990 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004991 return NO_ERROR;
4992 }
Irvel468051e2016-06-13 16:44:44 -07004993 case 1020: { // Layer updates interceptor
4994 n = data.readInt32();
4995 if (n) {
4996 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004997 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004998 }
4999 else{
5000 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005001 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005002 }
5003 return NO_ERROR;
5004 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005005 case 1021: { // Disable HWC virtual displays
5006 n = data.readInt32();
5007 mUseHwcVirtualDisplays = !n;
5008 return NO_ERROR;
5009 }
Romain Guy0147a172017-06-01 13:53:56 -07005010 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005011 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005012 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005013
Chia-I Wu28f320b2018-05-03 11:02:56 -07005014 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005015 return NO_ERROR;
5016 }
Romain Guy54f154a2017-10-24 21:40:32 +01005017 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005018 int32_t colorMode;
5019
Chia-I Wu0d711262018-05-21 15:19:35 -07005020 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005021 if (data.readInt32(&colorMode) == NO_ERROR) {
5022 mForceColorMode = static_cast<ColorMode>(colorMode);
5023 }
Romain Guy54f154a2017-10-24 21:40:32 +01005024 invalidateHwcGeometry();
5025 repaintEverything();
5026 return NO_ERROR;
5027 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005028 // Deprecate, use 1030 to check whether the device is color managed.
5029 case 1024: {
5030 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005031 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005032 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005033 n = data.readInt32();
5034 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005035 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005036 Mutex::Autolock lock(mStateLock);
5037 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005038 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005039 reply->writeInt32(NO_ERROR);
5040 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005041 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005042 bool writeFile = false;
5043 {
5044 Mutex::Autolock lock(mStateLock);
5045 mTracingEnabledChanged = true;
5046 writeFile = mTracing.disable();
5047 }
5048
5049 if (writeFile) {
5050 reply->writeInt32(mTracing.writeToFile());
5051 } else {
5052 reply->writeInt32(NO_ERROR);
5053 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005054 }
5055 return NO_ERROR;
5056 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005057 case 1026: { // Get layer tracing status
5058 reply->writeBool(mTracing.isEnabled());
5059 return NO_ERROR;
5060 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005061 // Is a DisplayColorSetting supported?
5062 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005063 const auto display = getDefaultDisplayDevice();
5064 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005065 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005066 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005067
5068 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5069 switch (setting) {
5070 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005071 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005072 break;
5073 case DisplayColorSetting::UNMANAGED:
5074 reply->writeBool(true);
5075 break;
5076 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005077 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005078 break;
5079 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005080 reply->writeBool(
5081 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005082 break;
5083 }
5084 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005085 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005086 // Is VrFlinger active?
5087 case 1028: {
5088 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005089 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005090 return NO_ERROR;
5091 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005092 // Set buffer size for SF tracing (value in KB)
5093 case 1029: {
5094 n = data.readInt32();
5095 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5096 ALOGW("Invalid buffer size: %d KB", n);
5097 reply->writeInt32(BAD_VALUE);
5098 return BAD_VALUE;
5099 }
5100
5101 ALOGD("Updating trace buffer to %d KB", n);
5102 mTracing.setBufferSize(n * 1024);
5103 reply->writeInt32(NO_ERROR);
5104 return NO_ERROR;
5105 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005106 // Is device color managed?
5107 case 1030: {
5108 reply->writeBool(useColorManagement);
5109 return NO_ERROR;
5110 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005111 // Override default composition data space
5112 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5113 // && adb shell stop zygote && adb shell start zygote
5114 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5115 // adb shell stop zygote && adb shell start zygote
5116 case 1031: {
5117 Mutex::Autolock _l(mStateLock);
5118 n = data.readInt32();
5119 if (n) {
5120 n = data.readInt32();
5121 if (n) {
5122 Dataspace dataspace = static_cast<Dataspace>(n);
5123 if (!validateCompositionDataspace(dataspace)) {
5124 return BAD_VALUE;
5125 }
5126 mDefaultCompositionDataspace = dataspace;
5127 }
5128 n = data.readInt32();
5129 if (n) {
5130 Dataspace dataspace = static_cast<Dataspace>(n);
5131 if (!validateCompositionDataspace(dataspace)) {
5132 return BAD_VALUE;
5133 }
5134 mWideColorGamutCompositionDataspace = dataspace;
5135 }
5136 } else {
5137 // restore composition data space.
5138 mDefaultCompositionDataspace = defaultCompositionDataspace;
5139 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5140 }
5141 return NO_ERROR;
5142 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005143 // Set trace flags
5144 case 1033: {
5145 n = data.readUint32();
5146 ALOGD("Updating trace flags to 0x%x", n);
5147 mTracing.setTraceFlags(n);
5148 reply->writeInt32(NO_ERROR);
5149 return NO_ERROR;
5150 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005151 case 1034: {
5152 // TODO(b/129297325): expose this via developer menu option
5153 n = data.readInt32();
5154 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005155 RefreshRateType type;
5156 {
5157 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5158 type = mDesiredActiveConfig.type;
5159 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005160 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005161 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005162 } else if (!n) {
5163 mRefreshRateOverlay.reset();
5164 }
5165 return NO_ERROR;
5166 }
Ady Abraham34392f72019-04-10 11:29:27 -07005167 case 1035: {
5168 n = data.readInt32();
5169 mDebugDisplayConfigSetByBackdoor = false;
5170 if (n >= 0) {
5171 const auto displayToken = getInternalDisplayToken();
5172 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5173 if (result != NO_ERROR) {
5174 return result;
5175 }
5176 mDebugDisplayConfigSetByBackdoor = true;
5177 }
5178 return NO_ERROR;
5179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005180 }
5181 }
5182 return err;
5183}
5184
Steven Thomas6d8110b2017-08-31 18:24:21 -07005185void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005186 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005187 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005188}
5189
Ana Krulec7d1d6832018-12-27 11:10:09 -08005190void SurfaceFlinger::repaintEverythingForHWC() {
5191 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005192 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005193}
5194
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005195// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5196class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005197public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005198 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5199 ~WindowDisconnector() {
5200 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005201 }
5202
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005203private:
5204 ANativeWindow* mWindow;
5205 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005206};
5207
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005208status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005209 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5210 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005211 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005212 uint32_t reqWidth, uint32_t reqHeight,
5213 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005214 ISurfaceComposer::Rotation rotation,
5215 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005216 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005217
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005218 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005219
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005220 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5221
Chia-I Wu20261cb2018-08-23 12:55:44 -07005222 sp<DisplayDevice> display;
5223 {
5224 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005225
Chia-I Wu20261cb2018-08-23 12:55:44 -07005226 display = getDisplayDeviceLocked(displayToken);
5227 if (!display) return BAD_VALUE;
5228
Chia-I Wucb023152018-08-28 12:57:23 -07005229 // set the requested width/height to the logical display viewport size
5230 // by default
5231 if (reqWidth == 0 || reqHeight == 0) {
5232 reqWidth = uint32_t(display->getViewport().width());
5233 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005234 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005235 }
5236
Peiyong Lin0e003c92018-09-17 11:09:51 -07005237 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005238 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005239
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005240 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5241 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005242 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005243 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005244}
5245
chaviw93df2ea2019-04-30 16:45:12 -07005246static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5247 switch (colorMode) {
5248 case ColorMode::DISPLAY_P3:
5249 case ColorMode::BT2100_PQ:
5250 case ColorMode::BT2100_HLG:
5251 case ColorMode::DISPLAY_BT2020:
5252 return Dataspace::DISPLAY_P3;
5253 default:
5254 return Dataspace::V0_SRGB;
5255 }
5256}
5257
5258const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5259 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5260 if (displayToken) {
5261 return getDisplayDeviceLocked(displayToken);
5262 }
5263 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5264 // may not have a displayId.
5265 for (const auto& [token, display] : mDisplays) {
5266 if (display->getLayerStack() == displayOrLayerStack) {
5267 return display;
5268 }
5269 }
5270 return nullptr;
5271}
5272
5273status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5274 sp<GraphicBuffer>* outBuffer) {
5275 sp<DisplayDevice> display;
5276 uint32_t width;
5277 uint32_t height;
5278 ui::Transform::orientation_flags captureOrientation;
5279 {
5280 Mutex::Autolock _l(mStateLock);
5281 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5282 if (!display) {
5283 return BAD_VALUE;
5284 }
5285
5286 width = uint32_t(display->getViewport().width());
5287 height = uint32_t(display->getViewport().height());
5288
5289 captureOrientation = fromSurfaceComposerRotation(
5290 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005291 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5292 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5293 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5294 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5295 }
chaviw93df2ea2019-04-30 16:45:12 -07005296 *outDataspace =
5297 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5298 }
5299
5300 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5301 false /* captureSecureLayers */);
5302
5303 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5304 std::placeholders::_1);
5305 bool ignored = false;
5306 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5307 false /* useIdentityTransform */,
5308 ignored /* outCapturedSecureLayers */);
5309}
5310
Robert Carr866455f2019-04-02 16:28:26 -07005311status_t SurfaceFlinger::captureLayers(
5312 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5313 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5314 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5315 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005316 ATRACE_CALL();
5317
5318 class LayerRenderArea : public RenderArea {
5319 public:
Robert Carr578038f2018-03-09 12:25:24 -08005320 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005321 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5322 bool childrenOnly)
5323 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005324 mLayer(layer),
5325 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005326 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005327 mFlinger(flinger),
5328 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005329 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005330 Rect getBounds() const override {
5331 const Layer::State& layerState(mLayer->getDrawingState());
5332 return mLayer->getBufferSize(layerState);
5333 }
Marissa Wall61c58622018-07-18 10:12:20 -07005334 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005335 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005336 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005337 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005338 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005339 }
chaviwa76b2712017-09-20 12:02:26 -07005340 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005341 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005342 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005343 Rect getSourceCrop() const override {
5344 if (mCrop.isEmpty()) {
5345 return getBounds();
5346 } else {
5347 return mCrop;
5348 }
5349 }
Robert Carr578038f2018-03-09 12:25:24 -08005350 class ReparentForDrawing {
5351 public:
5352 const sp<Layer>& oldParent;
5353 const sp<Layer>& newParent;
5354
Vishnu Nair4351ad52019-02-11 14:13:02 -08005355 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5356 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005357 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005358 // Compute and cache the bounds for the new parent layer.
5359 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005360 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005361 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005362 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005363 };
5364
5365 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005366 const Rect sourceCrop = getSourceCrop();
5367 // no need to check rotation because there is none
5368 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5369 sourceCrop.height() != getReqHeight();
5370
Robert Carr578038f2018-03-09 12:25:24 -08005371 if (!mChildrenOnly) {
5372 mTransform = mLayer->getTransform().inverse();
5373 drawLayers();
5374 } else {
5375 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005376 // In the "childrenOnly" case we reparent the children to a screenshot
5377 // layer which has no properties set and which does not draw.
5378 sp<ContainerLayer> screenshotParentLayer =
5379 mFlinger->getFactory().createContainerLayer(
5380 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5381 bounds.getWidth(), bounds.getHeight(), 0,
5382 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005383
Vishnu Nair4351ad52019-02-11 14:13:02 -08005384 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005385 drawLayers();
5386 }
5387 }
chaviwa76b2712017-09-20 12:02:26 -07005388
chaviwa76b2712017-09-20 12:02:26 -07005389 private:
chaviw7206d492017-11-10 16:16:12 -08005390 const sp<Layer> mLayer;
5391 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005392
Peiyong Linefefaac2018-08-17 12:27:51 -07005393 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005394 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005395
5396 SurfaceFlinger* mFlinger;
5397 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005398 };
5399
Robert Carrc0df3122019-04-11 13:18:21 -07005400 int reqWidth = 0;
5401 int reqHeight = 0;
5402 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005403 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005404 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005405
Robert Carrc0df3122019-04-11 13:18:21 -07005406 {
5407 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005408
Robert Carrc0df3122019-04-11 13:18:21 -07005409 parent = fromHandle(layerHandleBinder);
5410 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5411 ALOGE("captureLayers called with an invalid or removed parent");
5412 return NAME_NOT_FOUND;
5413 }
5414
5415 const int uid = IPCThreadState::self()->getCallingUid();
5416 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5417 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5418 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5419 return PERMISSION_DENIED;
5420 }
5421
5422 if (sourceCrop.width() <= 0) {
5423 crop.left = 0;
5424 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5425 }
5426
5427 if (sourceCrop.height() <= 0) {
5428 crop.top = 0;
5429 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5430 }
5431 reqWidth = crop.width() * frameScale;
5432 reqHeight = crop.height() * frameScale;
5433
5434 for (const auto& handle : excludeHandles) {
5435 sp<Layer> excludeLayer = fromHandle(handle);
5436 if (excludeLayer != nullptr) {
5437 excludeLayers.emplace(excludeLayer);
5438 } else {
5439 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5440 return NAME_NOT_FOUND;
5441 }
5442 }
5443 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005444
Chia-I Wu20261cb2018-08-23 12:55:44 -07005445 // really small crop or frameScale
5446 if (reqWidth <= 0) {
5447 reqWidth = 1;
5448 }
5449 if (reqHeight <= 0) {
5450 reqHeight = 1;
5451 }
5452
Robert Carr866455f2019-04-02 16:28:26 -07005453 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5454 auto traverseLayers = [parent, childrenOnly,
5455 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005456 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5457 if (!layer->isVisible()) {
5458 return;
Robert Carr578038f2018-03-09 12:25:24 -08005459 } else if (childrenOnly && layer == parent.get()) {
5460 return;
chaviwa76b2712017-09-20 12:02:26 -07005461 }
Robert Carr866455f2019-04-02 16:28:26 -07005462
5463 sp<Layer> p = layer;
5464 while (p != nullptr) {
5465 if (excludeLayers.count(p) != 0) {
5466 return;
5467 }
5468 p = p->getParent();
5469 }
5470
chaviwa76b2712017-09-20 12:02:26 -07005471 visitor(layer);
5472 });
5473 };
Robert Carr108b2c72019-04-02 16:32:58 -07005474
5475 bool outCapturedSecureLayers = false;
5476 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5477 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005478}
5479
5480status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5481 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005482 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005483 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005484 bool useIdentityTransform,
5485 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005486 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005487
Peiyong Lin0e003c92018-09-17 11:09:51 -07005488 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005489 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5490 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005491 *outBuffer =
5492 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5493 static_cast<android_pixel_format>(reqPixelFormat), 1,
5494 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005495
Robert Carr108b2c72019-04-02 16:32:58 -07005496 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5497 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005498}
5499
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005500status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5501 TraverseLayersFunction traverseLayers,
5502 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005503 bool useIdentityTransform,
5504 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005505 // This mutex protects syncFd and captureResult for communication of the return values from the
5506 // main thread back to this Binder thread
5507 std::mutex captureMutex;
5508 std::condition_variable captureCondition;
5509 std::unique_lock<std::mutex> captureLock(captureMutex);
5510 int syncFd = -1;
5511 std::optional<status_t> captureResult;
5512
Robert Carr03480e22018-01-04 16:02:06 -08005513 const int uid = IPCThreadState::self()->getCallingUid();
5514 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5515
Dominik Laskowski8c001672018-05-30 16:52:06 -07005516 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005517 // If there is a refresh pending, bug out early and tell the binder thread to try again
5518 // after the refresh.
5519 if (mRefreshPending) {
5520 ATRACE_NAME("Skipping screenshot for now");
5521 std::unique_lock<std::mutex> captureLock(captureMutex);
5522 captureResult = std::make_optional<status_t>(EAGAIN);
5523 captureCondition.notify_one();
5524 return;
5525 }
5526
5527 status_t result = NO_ERROR;
5528 int fd = -1;
5529 {
5530 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005531 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005532 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005533 useIdentityTransform, forSystem, &fd,
5534 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005535 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005536 }
5537
5538 {
5539 std::unique_lock<std::mutex> captureLock(captureMutex);
5540 syncFd = fd;
5541 captureResult = std::make_optional<status_t>(result);
5542 captureCondition.notify_one();
5543 }
5544 });
5545
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005546 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005547 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005548 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005549 while (*captureResult == EAGAIN) {
5550 captureResult.reset();
5551 result = postMessageAsync(message);
5552 if (result != NO_ERROR) {
5553 return result;
5554 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005555 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005556 }
5557 result = *captureResult;
5558 }
5559
5560 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005561 sync_wait(syncFd, -1);
5562 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005563 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005564
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005565 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005566}
5567
chaviwa76b2712017-09-20 12:02:26 -07005568void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005569 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005570 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5571 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005572 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005573
chaviwa76b2712017-09-20 12:02:26 -07005574 const auto reqWidth = renderArea.getReqWidth();
5575 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005576 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005577 const auto transform = renderArea.getTransform();
5578 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005579
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005580 renderengine::DisplaySettings clientCompositionDisplay;
5581 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005582
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005583 // assume that bounds are never offset, and that they are the same as the
5584 // buffer bounds.
5585 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005586 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005587 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005588
5589 // Now take into account the rotation flag. We append a transform that
5590 // rotates the layer stack about the origin, then translate by buffer
5591 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005592 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005593 int displacementX = 0;
5594 int displacementY = 0;
5595 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5596 switch (rotation) {
5597 case ui::Transform::ROT_90:
5598 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005599 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005600 break;
5601 case ui::Transform::ROT_180:
5602 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005603 displacementY = renderArea.getBounds().getWidth();
5604 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005605 break;
5606 case ui::Transform::ROT_270:
5607 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005608 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005609 break;
5610 default:
5611 break;
5612 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005613
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005614 // We need to transform the clipping window into the right spot.
5615 // First, rotate the clipping rectangle by the rotation hint to get the
5616 // right orientation
5617 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5618 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5619 const vec4 rotClipTL = rotMatrix * clipTL;
5620 const vec4 rotClipBR = rotMatrix * clipBR;
5621 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5622 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5623 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5624 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5625
5626 // Now reposition the clipping rectangle with the displacement vector
5627 // computed above.
5628 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005629 clientCompositionDisplay.clip =
5630 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5631 newClipRight + displacementX, newClipBottom + displacementY);
5632
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005633 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005634 clientCompositionDisplay.globalTransform =
5635 clipTransform * clientCompositionDisplay.globalTransform;
5636
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5638 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005639
chaviw50da5042018-04-09 13:49:37 -07005640 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005641
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005642 renderengine::LayerSettings fillLayer;
5643 fillLayer.source.buffer.buffer = nullptr;
5644 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5645 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5646 fillLayer.alpha = half(alpha);
5647 clientCompositionLayers.push_back(fillLayer);
5648
5649 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005650 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005651 const bool supportProtectedContent = false;
5652 Region clip(renderArea.getBounds());
5653 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5654 clip,
5655 useIdentityTransform,
5656 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5657 renderArea.isSecure(),
5658 supportProtectedContent,
5659 clearRegion,
5660 };
5661 auto result = layer->prepareClientComposition(targetSettings);
5662 if (result) {
5663 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005664 }
chaviwa76b2712017-09-20 12:02:26 -07005665 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666
5667 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005668 // Use an empty fence for the buffer fence, since we just created the buffer so
5669 // there is no need for synchronization with the GPU.
5670 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005671 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005672 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005673 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005674 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005675
5676 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005677}
5678
chaviwa76b2712017-09-20 12:02:26 -07005679status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5680 TraverseLayersFunction traverseLayers,
5681 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005682 bool useIdentityTransform, bool forSystem,
5683 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005684 ATRACE_CALL();
5685
chaviwa76b2712017-09-20 12:02:26 -07005686 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005687 outCapturedSecureLayers =
5688 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005689 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005690
Robert Carr03480e22018-01-04 16:02:06 -08005691 // We allow the system server to take screenshots of secure layers for
5692 // use in situations like the Screen-rotation animation and place
5693 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005694 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005695 ALOGW("FB is protected: PERMISSION_DENIED");
5696 return PERMISSION_DENIED;
5697 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005698 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005699 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005700}
5701
chaviw95ef3c42019-02-14 10:55:09 -08005702void SurfaceFlinger::setInputWindowsFinished() {
5703 Mutex::Autolock _l(mStateLock);
5704
5705 mPendingSyncInputWindows = false;
5706 mTransactionCV.broadcast();
5707}
chaviw5f21a5e2019-02-14 10:00:34 -08005708
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005709// ---------------------------------------------------------------------------
5710
Dan Stoza412903f2017-04-27 13:42:17 -07005711void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5712 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005713}
5714
Dan Stoza412903f2017-04-27 13:42:17 -07005715void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5716 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005717}
5718
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005719void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005720 const LayerVector::Visitor& visitor) {
5721 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005722 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005723 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005724 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005725 continue;
5726 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005727 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005728 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005729 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005730 return;
5731 }
chaviwa76b2712017-09-20 12:02:26 -07005732 if (!layer->isVisible()) {
5733 return;
5734 }
5735 visitor(layer);
5736 });
5737 }
5738}
5739
Dominik Laskowski22488f62019-03-28 09:53:04 -07005740void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5741 const std::vector<int32_t>& allowedConfigs) {
5742 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005743 return;
5744 }
5745
5746 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005747 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08005748
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005749 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07005750 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005751 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005752 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005753 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005754 setDesiredActiveConfig(
5755 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07005756 break;
Ady Abraham97d04232019-03-05 19:48:12 -08005757 }
5758 }
Ady Abraham838de062019-02-04 10:24:03 -08005759}
5760
Dominik Laskowski22488f62019-03-28 09:53:04 -07005761status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005762 const std::vector<int32_t>& allowedConfigs) {
5763 ATRACE_CALL();
5764
Dominik Laskowski22488f62019-03-28 09:53:04 -07005765 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005766 return BAD_VALUE;
5767 }
5768
Ady Abraham34392f72019-04-10 11:29:27 -07005769 if (mDebugDisplayConfigSetByBackdoor) {
5770 // ignore this request as config is overridden by backdoor
5771 return NO_ERROR;
5772 }
5773
Ady Abraham838de062019-02-04 10:24:03 -08005774 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005775 const auto display = getDisplayDeviceLocked(displayToken);
5776 if (!display) {
5777 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5778 displayToken.get());
5779 } else if (display->isVirtual()) {
5780 ALOGW("Attempt to set allowed display configs for virtual display");
5781 } else {
5782 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5783 }
Ady Abraham838de062019-02-04 10:24:03 -08005784 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005785
Ady Abraham838de062019-02-04 10:24:03 -08005786 return NO_ERROR;
5787}
5788
Dominik Laskowski22488f62019-03-28 09:53:04 -07005789status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005790 std::vector<int32_t>* outAllowedConfigs) {
5791 ATRACE_CALL();
5792
Dominik Laskowski22488f62019-03-28 09:53:04 -07005793 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005794 return BAD_VALUE;
5795 }
5796
Dominik Laskowski22488f62019-03-28 09:53:04 -07005797 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005798
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005799 const auto display = getDisplayDeviceLocked(displayToken);
5800 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005801 return NAME_NOT_FOUND;
5802 }
5803
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005804 if (display->isPrimary()) {
5805 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5806 }
5807
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005808 return NO_ERROR;
5809}
5810
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005811void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005812 mFlinger->setInputWindowsFinished();
5813}
5814
Robert Carrc0df3122019-04-11 13:18:21 -07005815sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5816 BBinder *b = handle->localBinder();
5817 if (b == nullptr) {
5818 return nullptr;
5819 }
5820 auto it = mLayersByLocalBinderToken.find(b);
5821 if (it != mLayersByLocalBinderToken.end()) {
5822 return it->second.promote();
5823 }
5824 return nullptr;
5825}
5826
Alec Mouri4545a8a2019-08-08 20:05:32 -07005827void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5828 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5829}
5830
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005831} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005832
Mathias Agopian3f844832013-08-07 21:24:32 -07005833#if defined(__gl_h_)
5834#error "don't include gl/gl.h in this file"
5835#endif
5836
5837#if defined(__gl2_h_)
5838#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005839#endif