blob: 799dd3c8d49ba9322492e25dd2188d1c91fdf329 [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>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080056#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070057#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070058#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <ui/ColorSpace.h>
60#include <ui/DebugUtils.h>
61#include <ui/DisplayInfo.h>
62#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070063#include <ui/GraphicBufferAllocator.h>
64#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070065#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080066#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <utils/String16.h>
68#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070069#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080070#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070074#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Robert Carr578038f2018-03-09 12:25:24 -080076#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070077#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070078#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020079#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080080#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070085#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080086#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070087#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070088#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070089#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080090#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070091#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092
Steven Thomasb02664d2017-07-26 18:48:28 -070093#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070094#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070095#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070096#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070097#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070098#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070099#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700101#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/EventControlThread.h"
103#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700104#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700105#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700106#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700107#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800108#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700109
Mathias Agopianff2ed702013-09-01 21:36:12 -0700110#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700111
David Sodman7e4ae112018-02-09 15:02:28 -0800112#include "android-base/stringprintf.h"
113
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800115#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
116#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700117#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900118#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
chaviw1d044282017-09-27 12:19:28 -0700120#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700124
Jaesoo Lee43518572017-01-23 19:03:16 +0900125using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900127using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800128
Ady Abraham8532d012019-05-08 14:50:56 -0700129using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700131using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700132using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800133using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700134using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700135using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900136
Steven Thomasb02664d2017-07-26 18:48:28 -0700137namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700138
139#pragma clang diagnostic push
140#pragma clang diagnostic error "-Wswitch-enum"
141
142bool isWideColorMode(const ColorMode colorMode) {
143 switch (colorMode) {
144 case ColorMode::DISPLAY_P3:
145 case ColorMode::ADOBE_RGB:
146 case ColorMode::DCI_P3:
147 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700148 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700149 case ColorMode::BT2100_PQ:
150 case ColorMode::BT2100_HLG:
151 return true;
152 case ColorMode::NATIVE:
153 case ColorMode::STANDARD_BT601_625:
154 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
155 case ColorMode::STANDARD_BT601_525:
156 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
157 case ColorMode::STANDARD_BT709:
158 case ColorMode::SRGB:
159 return false;
160 }
161 return false;
162}
163
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700164ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
165 switch (rotation) {
166 case ISurfaceComposer::eRotateNone:
167 return ui::Transform::ROT_0;
168 case ISurfaceComposer::eRotate90:
169 return ui::Transform::ROT_90;
170 case ISurfaceComposer::eRotate180:
171 return ui::Transform::ROT_180;
172 case ISurfaceComposer::eRotate270:
173 return ui::Transform::ROT_270;
174 }
175 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
176 return ui::Transform::ROT_0;
177}
178
Peiyong Linfca547f2018-07-09 13:03:33 -0700179#pragma clang diagnostic pop
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181class ConditionalLock {
182public:
183 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
184 if (lock) {
185 mMutex.lock();
186 }
187 }
188 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
189private:
190 Mutex& mMutex;
191 bool mLocked;
192};
Peiyong Linfca547f2018-07-09 13:03:33 -0700193
Peiyong Lin9d846a52018-11-05 13:18:20 -0800194// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
195bool validateCompositionDataspace(Dataspace dataspace) {
196 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
197}
198
Steven Thomasb02664d2017-07-26 18:48:28 -0700199} // namespace anonymous
200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201// ---------------------------------------------------------------------------
202
Mathias Agopian99b49842011-06-27 16:05:52 -0700203const String16 sHardwareTest("android.permission.HARDWARE_TEST");
204const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
205const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
206const String16 sDump("android.permission.DUMP");
207
208// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700210bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800211uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800212bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800213bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800214int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600215bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700216int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700217bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700218bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700219Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
220ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
221Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700223
Kalle Raitaa099a242017-01-11 11:17:29 -0800224std::string getHwcServiceName() {
225 char value[PROPERTY_VALUE_MAX] = {};
226 property_get("debug.sf.hwc_service_name", value, "default");
227 ALOGI("Using HWComposer service: '%s'", value);
228 return std::string(value);
229}
230
231bool useTrebleTestingOverride() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.treble_testing_override", value, "false");
234 ALOGI("Treble testing override: '%s'", value);
235 return std::string(value) == "true";
236}
237
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
239 switch(displayColorSetting) {
240 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700241 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800242 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Enhanced");
246 default:
247 return std::string("Unknown ") +
248 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250}
251
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700252SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
255 : mFactory(factory),
256 mPhaseOffsets(mFactory.createPhaseOffsets()),
257 mInterceptor(mFactory.createSurfaceInterceptor(this)),
258 mTimeStats(mFactory.createTimeStats()),
259 mEventQueue(mFactory.createMessageQueue()),
260 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800263 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800264
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900265 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900267 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800272
Steven Thomas050b2c82017-03-06 11:45:16 -0800273 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800275
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 mDefaultCompositionDataspace =
283 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700284 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
285 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 defaultCompositionDataspace = mDefaultCompositionDataspace;
287 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
288 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
289 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
290 wideColorGamutCompositionPixelFormat =
291 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700292
Yichi Chenda901bf2019-06-28 14:58:27 +0800293 mColorSpaceAgnosticDataspace =
294 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
295
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900296 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
299 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
300 switch (tmpPrimaryDisplayOrientation) {
301 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700302 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800303 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700305 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800306 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700308 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800309 break;
310 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700311 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800312 break;
313 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700314 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800315
Sundong Ahn85131bd2019-02-18 15:51:53 +0900316 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800317
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800318 // debugging stuff...
319 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700320
Mathias Agopianb4b17302013-03-20 18:36:41 -0700321 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700322 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324 property_get("debug.sf.showupdates", value, "0");
325 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700326
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700327 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000328
329 // DDMS debugging deprecated (b/120782499)
330 property_get("debug.sf.ddms", value, "0");
331 int debugDdms = atoi(value);
332 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700333
334 property_get("debug.sf.disable_backpressure", value, "0");
335 mPropagateBackpressure = !atoi(value);
336 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700337
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800338 property_get("debug.sf.enable_hwc_vds", value, "0");
339 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800340 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800341
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800342 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800343 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800344 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700345
Yiwei Zhang243b3782018-05-15 17:40:04 -0700346 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700347 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
348 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
349
Ana Krulece5a06e02019-03-06 17:09:03 -0800350 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800351 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800352
353 int int_value = atoi(value);
354 if (int_value) {
355 mUseSmart90ForVideo = true;
356 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800357
Dan Stozaec460082018-12-17 15:35:09 -0800358 property_get("debug.sf.luma_sampling", value, "1");
359 mLumaSampling = atoi(value);
360
Ana Krulec757f63a2019-01-25 10:46:18 -0800361 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700362 mVsyncModulator.setPhaseOffsets(early, gl, late,
363 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700364
Romain Guy11d63f42017-07-20 12:47:14 -0700365 // We should be reading 'persist.sys.sf.color_saturation' here
366 // but since /data may be encrypted, we need to wait until after vold
367 // comes online to attempt to read the property. The property is
368 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800369
370 if (useTrebleTestingOverride()) {
371 // Without the override SurfaceFlinger cannot connect to HIDL
372 // services that are not listed in the manifests. Considered
373 // deriving the setting from the set service name, but it
374 // would be brittle if the name that's not 'default' is used
375 // for production purposes later on.
376 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
377 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800378}
379
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380void SurfaceFlinger::onFirstRef()
381{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800382 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800383}
384
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700385SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800386
Dan Stozac7014012014-02-14 15:03:43 -0800387void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800388{
389 // the window manager died on us. prepare its eulogy.
390
Andy McFadden13a082e2012-08-24 10:16:42 -0700391 // restore initial conditions (default device unblank, etc)
392 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393
394 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700395 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800396}
397
Robert Carr1db73f62016-12-21 12:58:51 -0800398static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700399 status_t err = client->initCheck();
400 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800401 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800402 }
Robert Carr1db73f62016-12-21 12:58:51 -0800403 return nullptr;
404}
405
406sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
407 return initClient(new Client(this));
408}
409
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700410sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
411 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700412{
413 class DisplayToken : public BBinder {
414 sp<SurfaceFlinger> flinger;
415 virtual ~DisplayToken() {
416 // no more references, this display must be terminated
417 Mutex::Autolock _l(flinger->mStateLock);
418 flinger->mCurrentState.displays.removeItem(this);
419 flinger->setTransactionFlags(eDisplayTransactionNeeded);
420 }
421 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700422 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700423 : flinger(flinger) {
424 }
425 };
426
427 sp<BBinder> token = new DisplayToken(this);
428
429 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700430 // Display ID is assigned when virtual display is allocated by HWC.
431 DisplayDeviceState state;
432 state.isSecure = secure;
433 state.displayName = displayName;
434 mCurrentState.displays.add(token, state);
435 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436 return token;
437}
438
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700439void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700440 Mutex::Autolock _l(mStateLock);
441
Dominik Laskowski075d3172018-05-24 15:50:06 -0700442 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
443 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700444 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700445 return;
446 }
447
Dominik Laskowski075d3172018-05-24 15:50:06 -0700448 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
449 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700450 ALOGE("destroyDisplay called for non-virtual display");
451 return;
452 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 mInterceptor->saveDisplayDeletion(state.sequenceId);
454 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 setTransactionFlags(eDisplayTransactionNeeded);
456}
457
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800458std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
459 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700460
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800461 const auto internalDisplayId = getInternalDisplayIdLocked();
462 if (!internalDisplayId) {
463 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 }
465
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800466 std::vector<PhysicalDisplayId> displayIds;
467 displayIds.reserve(mPhysicalDisplayTokens.size());
468 displayIds.push_back(internalDisplayId->value);
469
470 for (const auto& [id, token] : mPhysicalDisplayTokens) {
471 if (id != *internalDisplayId) {
472 displayIds.push_back(id.value);
473 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700474 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800476 return displayIds;
477}
478
479sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
480 Mutex::Autolock lock(mStateLock);
481 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700482}
483
Ady Abraham37965d42018-11-01 13:43:32 -0700484status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
485 if (!outGetColorManagement) {
486 return BAD_VALUE;
487 }
488 *outGetColorManagement = useColorManagement;
489 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700490}
491
Lloyd Pique441d5042018-10-18 16:49:51 -0700492HWComposer& SurfaceFlinger::getHwComposer() const {
493 return mCompositionEngine->getHwComposer();
494}
495
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700496renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
497 return mCompositionEngine->getRenderEngine();
498}
499
Lloyd Pique70d91362018-10-18 16:02:55 -0700500compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
501 return *mCompositionEngine.get();
502}
503
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800504void SurfaceFlinger::bootFinished()
505{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700506 if (mStartPropertySetThread->join() != NO_ERROR) {
507 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800509 const nsecs_t now = systemTime();
510 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000511 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512
513 // wait patiently for the window manager death
514 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700515 mWindowManager = defaultServiceManager()->getService(name);
516 if (mWindowManager != 0) {
517 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700518 }
Robert Carr720e5062018-07-30 17:45:14 -0700519 sp<IBinder> input(defaultServiceManager()->getService(
520 String16("inputflinger")));
521 if (input == nullptr) {
522 ALOGE("Failed to link to input service");
523 } else {
524 mInputFlinger = interface_cast<IInputFlinger>(input);
525 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700526
Steven Thomas050b2c82017-03-06 11:45:16 -0800527 if (mVrFlinger) {
528 mVrFlinger->OnBootFinished();
529 }
530
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700532 // formerly we would just kill the process, but we now ask it to exit so it
533 // can choose where to stop the animation.
534 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700535
536 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
537 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
538 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700539
Ana Krulecbd6654b2019-02-15 15:18:15 -0800540 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800541 readPersistentProperties();
542 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800543
Ady Abraham97d04232019-03-05 19:48:12 -0800544 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700545 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700546 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800547
Dominik Laskowski22488f62019-03-28 09:53:04 -0700548 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800549 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800550 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800551 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800552 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800553 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554}
555
Dan Stoza436ccf32018-06-21 12:10:12 -0700556uint32_t SurfaceFlinger::getNewTexture() {
557 {
558 std::lock_guard lock(mTexturePoolMutex);
559 if (!mTexturePool.empty()) {
560 uint32_t name = mTexturePool.back();
561 mTexturePool.pop_back();
562 ATRACE_INT("TexturePoolSize", mTexturePool.size());
563 return name;
564 }
565
566 // The pool was too small, so increase it for the future
567 ++mTexturePoolSize;
568 }
569
570 // The pool was empty, so we need to get a new texture name directly using a
571 // blocking call to the main thread
572 uint32_t name = 0;
573 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
574 return name;
575}
576
Mathias Agopian3f844832013-08-07 21:24:32 -0700577void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700578 std::lock_guard lock(mTexturePoolMutex);
579 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
580 // to actually delete this or not based on mTexturePoolSize
581 mTexturePool.push_back(texture);
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700583}
584
Wei Wangf9b05ee2017-07-19 20:59:39 -0700585// Do not call property_set on main thread which will be blocked by init
586// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700588 ALOGI( "SurfaceFlinger's main thread ready to run. "
589 "Initializing graphics H/W...");
590
Ana Krulec757f63a2019-01-25 10:46:18 -0800591 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900592
Steven Thomasb02664d2017-07-26 18:48:28 -0700593 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800595 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700596 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
597 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800598 auto resyncCallback =
599 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800600
Ana Krulecc2870422019-01-29 19:00:58 -0800601 mAppConnectionHandle =
Ady Abraham45e4e362019-06-07 18:20:51 -0700602 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
603 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800604 resyncCallback,
605 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700606 mSfConnectionHandle =
607 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
608 mPhaseOffsets->getOffsetThresholdForNextVsync(),
609 resyncCallback, [this](nsecs_t timestamp) {
610 mInterceptor->saveVSyncEvent(timestamp);
611 });
Ana Krulecc2870422019-01-29 19:00:58 -0800612
613 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
614 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
615 mSfConnectionHandle.get());
616
Kevin DuBois413287f2019-02-25 08:46:47 -0800617 mRegionSamplingThread =
618 new RegionSamplingThread(*this, *mScheduler,
619 RegionSamplingThread::EnvironmentTimingTunables());
620
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700622 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700623 renderEngineFeature |= (useColorManagement ?
624 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700625 renderEngineFeature |= (useContextPriority ?
626 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700627 renderEngineFeature |=
628 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
629 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700630
631 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800632 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700633 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700634 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800635 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700636
637 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
638 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700639 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
640 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800641 // Process any initial hotplug and resulting display changes.
642 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700643 const auto display = getDefaultDisplayDeviceLocked();
644 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700645 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700646 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800647
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700649 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700650 // This callback is called from the vr flinger dispatch thread. We
651 // need to call signalTransaction(), which requires holding
652 // mStateLock when we're not on the main thread. Acquiring
653 // mStateLock from the vr flinger dispatch thread might trigger a
654 // deadlock in surface flinger (see b/66916578), so post a message
655 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700656 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700657 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
658 mVrFlingerRequestsDisplay = requestDisplay;
659 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700660 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800661 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700662 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
663 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700664 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700665 .value_or(0),
666 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800667 if (!mVrFlinger) {
668 ALOGE("Failed to start vrflinger");
669 }
670 }
671
Mathias Agopian92a979a2012-08-02 18:32:23 -0700672 // initialize our drawing state
673 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700674
Andy McFadden13a082e2012-08-24 10:16:42 -0700675 // set initial conditions (e.g. unblank default device)
676 initializeDisplays();
677
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700678 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700679
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700681
682 const bool presentFenceReliable =
683 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
684 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685
686 if (mStartPropertySetThread->Start() != NO_ERROR) {
687 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800689
Alec Mouri93bc83d2019-04-17 14:47:43 -0700690 mScheduler->setChangeRefreshRateCallback(
691 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
692 Mutex::Autolock lock(mStateLock);
693 setRefreshRateTo(type, event);
694 });
Alec Mouri7f015182019-07-11 13:56:22 -0700695 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
696 Mutex::Autolock lock(mStateLock);
697 const auto display = getDefaultDisplayDeviceLocked();
698 if (!display) {
699 // If we don't have a default display the fallback to the default
700 // refresh rate type
701 return RefreshRateType::DEFAULT;
702 }
703
704 const int configId = display->getActiveConfig();
705 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
706 if (refresh && refresh->configId == configId) {
707 return type;
708 }
709 }
710 // This should never happen, but just gracefully fallback to default.
711 return RefreshRateType::DEFAULT;
712 });
Alec Mouridc28b372019-04-18 21:17:13 -0700713 mScheduler->setGetVsyncPeriodCallback([this] {
714 Mutex::Autolock lock(mStateLock);
715 return getVsyncPeriod();
716 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700717
Dominik Laskowski22488f62019-03-28 09:53:04 -0700718 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
719 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800720
Dan Stoza9e56aa02015-11-02 13:00:03 -0800721 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700722}
723
Romain Guy11d63f42017-07-20 12:47:14 -0700724void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700725 Mutex::Autolock _l(mStateLock);
726
Romain Guy11d63f42017-07-20 12:47:14 -0700727 char value[PROPERTY_VALUE_MAX];
728
729 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800730 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700731 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800732 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100733
734 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700735 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800736
737 property_get("persist.sys.sf.color_mode", value, "0");
738 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700739}
740
Mathias Agopiana67e4182012-06-19 17:26:12 -0700741void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800742 // Start boot animation service by setting a property mailbox
743 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800745 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700746 if (mStartPropertySetThread->join() != NO_ERROR) {
747 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800748 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749}
750
Mathias Agopian875d8e12013-06-07 15:35:48 -0700751size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700752 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700753}
754
Mathias Agopian875d8e12013-06-07 15:35:48 -0700755size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700756 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700757}
758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800759// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800760
Jamie Gennis582270d2011-08-17 18:19:00 -0700761bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800762 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800763 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800764 return authenticateSurfaceTextureLocked(bufferProducer);
765}
766
767bool SurfaceFlinger::authenticateSurfaceTextureLocked(
768 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800769 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800770 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800771}
772
Brian Anderson6b376712017-04-04 10:51:39 -0700773status_t SurfaceFlinger::getSupportedFrameTimestamps(
774 std::vector<FrameEvent>* outSupported) const {
775 *outSupported = {
776 FrameEvent::REQUESTED_PRESENT,
777 FrameEvent::ACQUIRE,
778 FrameEvent::LATCH,
779 FrameEvent::FIRST_REFRESH_START,
780 FrameEvent::LAST_REFRESH_START,
781 FrameEvent::GPU_COMPOSITION_DONE,
782 FrameEvent::DEQUEUE_READY,
783 FrameEvent::RELEASE,
784 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700785 ConditionalLock _l(mStateLock,
786 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700787 if (!getHwComposer().hasCapability(
788 HWC2::Capability::PresentFenceIsNotReliable)) {
789 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
790 }
791 return NO_ERROR;
792}
793
Dominik Laskowski22488f62019-03-28 09:53:04 -0700794status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
795 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700796 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 return BAD_VALUE;
798 }
799
Dominik Laskowski22488f62019-03-28 09:53:04 -0700800 Mutex::Autolock lock(mStateLock);
801
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800802 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700803 if (!displayId) {
804 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700805 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700806
Mathias Agopian8b736f12012-08-13 17:54:26 -0700807 // TODO: Not sure if display density should handled by SF any longer
808 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700809 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700810 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700811 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800812 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700813 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814 }
815 return density;
816 }
817 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700818 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 return getDensityFromProperty("ro.sf.lcd_density"); }
822 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700825
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 DisplayInfo info = DisplayInfo();
828
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 float xdpi = hwConfig->getDpiX();
830 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700832 info.w = hwConfig->getWidth();
833 info.h = hwConfig->getHeight();
834 // Default display viewport to display width and height
835 info.viewportW = info.w;
836 info.viewportH = info.h;
837
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800838 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 // The density of the device is provided by a build property
840 float density = Density::getBuildDensity() / 160.0f;
841 if (density == 0) {
842 // the build doesn't provide a density -- this is wrong!
843 // use xdpi instead
844 ALOGE("ro.sf.lcd_density must be defined as a build property");
845 density = xdpi / 160.0f;
846 }
847 if (Density::getEmuDensity()) {
848 // if "qemu.sf.lcd_density" is specified, it overrides everything
849 xdpi = ydpi = density = Density::getEmuDensity();
850 density /= 160.0f;
851 }
852 info.density = density;
853
854 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855 const auto display = getDefaultDisplayDeviceLocked();
856 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700857
858 // This is for screenrecord
859 const Rect viewport = display->getViewport();
860 if (viewport.isValid()) {
861 info.viewportW = uint32_t(viewport.getWidth());
862 info.viewportH = uint32_t(viewport.getHeight());
863 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700864 } else {
865 // TODO: where should this value come from?
866 static const int TV_DENSITY = 213;
867 info.density = TV_DENSITY / 160.0f;
868 info.orientation = 0;
869 }
870
Dan Stoza7f7da322014-05-02 15:26:25 -0700871 info.xdpi = xdpi;
872 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800873 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700874 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
875 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
876 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800877
Andy McFadden91b2ca82014-06-13 14:04:23 -0700878 // This is how far in advance a buffer must be queued for
879 // presentation at a given time. If you want a buffer to appear
880 // on the screen at time N, you must submit the buffer before
881 // (N - presentationDeadline).
882 //
883 // Normally it's one full refresh period (to give SF a chance to
884 // latch the buffer), but this can be reduced by configuring a
885 // DispSync offset. Any additional delays introduced by the hardware
886 // composer or panel must be accounted for here.
887 //
888 // We add an additional 1ms to allow for processing time and
889 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700890 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700891
892 // All non-virtual displays are currently considered secure.
893 info.secure = true;
894
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800895 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700896 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800897 std::swap(info.w, info.h);
898 }
899
Michael Wright28f24d02016-07-12 13:30:53 -0700900 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700901 }
902
Dan Stoza7f7da322014-05-02 15:26:25 -0700903 return NO_ERROR;
904}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700905
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700906status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
907 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700908 return BAD_VALUE;
909 }
910
Ana Krulecc2870422019-01-29 19:00:58 -0800911 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700912 return NO_ERROR;
913}
914
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700915int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
916 const auto display = getDisplayDevice(displayToken);
917 if (!display) {
918 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800919 return BAD_VALUE;
920 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700921
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700922 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700923}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700924
Ady Abraham03b02dd2019-03-21 15:40:11 -0700925void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800926 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800927
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800929 // config twice. However event generation config might have changed so we need to update it
930 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800931 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700932 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
933 mDesiredActiveConfig = info;
934 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800935
936 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800937 // This will trigger HWC refresh without resetting the idle timer.
938 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700939 // Start receiving vsync samples now, so that we can detect a period
940 // switch.
941 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700942 // As we called to set period, we will call to onRefreshRateChangeCompleted once
943 // DispSync model is locked.
944 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700945 mPhaseOffsets->setRefreshRateType(info.type);
946 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700947 mVsyncModulator.setPhaseOffsets(early, gl, late,
948 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800950 mDesiredActiveConfigChanged = true;
951 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700952
953 if (mRefreshRateOverlay) {
954 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
955 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956}
957
958status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
959 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800960
961 std::vector<int32_t> allowedConfig;
962 allowedConfig.push_back(mode);
963
964 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965}
966
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800967void SurfaceFlinger::setActiveConfigInternal() {
968 ATRACE_CALL();
969
Dominik Laskowski22488f62019-03-28 09:53:04 -0700970 const auto display = getDefaultDisplayDeviceLocked();
971 if (!display) {
972 return;
973 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974
Dominik Laskowski22488f62019-03-28 09:53:04 -0700975 std::lock_guard<std::mutex> lock(mActiveConfigLock);
976 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
977
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 display->setActiveConfig(mUpcomingActiveConfig.configId);
979
Alec Mouri754c98a2019-03-18 18:53:42 -0700980 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800981 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700982 mVsyncModulator.setPhaseOffsets(early, gl, late,
983 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700985
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800986 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800987 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
988 mUpcomingActiveConfig.configId);
989 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990}
991
Ady Abraham53852a52019-05-28 18:07:44 -0700992void SurfaceFlinger::desiredActiveConfigChangeDone() {
993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
994 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
995 mDesiredActiveConfigChanged = false;
996 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
997
998 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
999 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1000 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001001 mVsyncModulator.setPhaseOffsets(early, gl, late,
1002 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -07001003}
1004
Dominik Laskowski22488f62019-03-28 09:53:04 -07001005bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001006 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001008 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001010 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 return true;
1012 }
1013
1014 // We received the present fence from the HWC, so we assume it successfully updated
1015 // the config, hence we update SF.
1016 mCheckPendingFence = false;
1017 setActiveConfigInternal();
1018 }
1019
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 // Store the local variable to release the lock.
1021 ActiveConfigInfo desiredActiveConfig;
1022 {
1023 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001024 if (!mDesiredActiveConfigChanged) {
1025 return false;
1026 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001027 desiredActiveConfig = mDesiredActiveConfig;
1028 }
1029
Dominik Laskowski22488f62019-03-28 09:53:04 -07001030 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1032 // display is not valid or we are already in the requested mode
1033 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001034 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001036 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037
Ady Abraham838de062019-02-04 10:24:03 -08001038 // Desired active config was set, it is different than the config currently in use, however
1039 // allowed configs might have change by the time we process the refresh.
1040 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001041 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001042 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001043 return false;
1044 }
Alec Mouri7f015182019-07-11 13:56:22 -07001045
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 mUpcomingActiveConfig = desiredActiveConfig;
1047 const auto displayId = display->getId();
1048 LOG_ALWAYS_FATAL_IF(!displayId);
1049
1050 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1051 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1052
1053 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001055 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001057}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1060 Vector<ColorMode>* outColorModes) {
1061 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001062 return BAD_VALUE;
1063 }
1064
Peiyong Lina52f0292018-03-14 17:26:31 -07001065 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001066 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001068 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1069
1070 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1071 if (!displayId) {
1072 return NAME_NOT_FOUND;
1073 }
1074
Dominik Laskowski075d3172018-05-24 15:50:06 -07001075 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001076 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001077 }
Michael Wright28f24d02016-07-12 13:30:53 -07001078 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001079
1080 // If it's built-in display and the configuration claims it's not wide color capable,
1081 // filter out all wide color modes. The typical reason why this happens is that the
1082 // hardware is not good enough to support GPU composition of wide color, and thus the
1083 // OEMs choose to disable this capability.
1084 if (isInternalDisplay && !hasWideColorDisplay) {
1085 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1086 isWideColorMode);
1087 } else {
1088 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1089 }
Michael Wright28f24d02016-07-12 13:30:53 -07001090
1091 return NO_ERROR;
1092}
1093
Daniel Solomon42d04562019-01-20 21:03:19 -08001094status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1095 ui::DisplayPrimaries &primaries) {
1096 if (!displayToken) {
1097 return BAD_VALUE;
1098 }
1099
1100 // Currently we only support this API for a single internal display.
1101 if (getInternalDisplayToken() != displayToken) {
1102 return BAD_VALUE;
1103 }
1104
1105 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1106 return NO_ERROR;
1107}
1108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1110 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001111 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001112 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001113 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001114}
1115
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001117 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118 Vector<ColorMode> modes;
1119 getDisplayColorModes(displayToken, &modes);
1120 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1121 if (mode < ColorMode::NATIVE || !exists) {
1122 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1123 decodeColorMode(mode).c_str(), mode, displayToken.get());
1124 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001125 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 const auto display = getDisplayDevice(displayToken);
1127 if (!display) {
1128 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1129 decodeColorMode(mode).c_str(), mode, displayToken.get());
1130 } else if (display->isVirtual()) {
1131 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1132 decodeColorMode(mode).c_str(), mode);
1133 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001134 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
Lloyd Piquef5275482019-01-29 18:42:42 -08001135 RenderIntent::COLORIMETRIC,
1136 Dataspace::UNKNOWN);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137 }
1138 }));
1139
Michael Wright28f24d02016-07-12 13:30:53 -07001140 return NO_ERROR;
1141}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001142
Svetoslavd85084b2014-03-20 10:28:31 -07001143status_t SurfaceFlinger::clearAnimationFrameStats() {
1144 Mutex::Autolock _l(mStateLock);
1145 mAnimFrameTracker.clearStats();
1146 return NO_ERROR;
1147}
1148
1149status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1150 Mutex::Autolock _l(mStateLock);
1151 mAnimFrameTracker.getStats(outStats);
1152 return NO_ERROR;
1153}
1154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001155status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1156 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001157 Mutex::Autolock _l(mStateLock);
1158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 const auto display = getDisplayDeviceLocked(displayToken);
1160 if (!display) {
1161 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001162 return BAD_VALUE;
1163 }
1164
Peiyong Linfb069302018-04-25 14:34:31 -07001165 // At this point the DisplayDeivce should already be set up,
1166 // meaning the luminance information is already queried from
1167 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001169 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1170 capabilities.getDesiredMaxLuminance(),
1171 capabilities.getDesiredMaxAverageLuminance(),
1172 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001173
1174 return NO_ERROR;
1175}
1176
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001177status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1178 ui::PixelFormat* outFormat,
1179 ui::Dataspace* outDataspace,
1180 uint8_t* outComponentMask) const {
1181 if (!outFormat || !outDataspace || !outComponentMask) {
1182 return BAD_VALUE;
1183 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001184 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001185 if (!display || !display->getId()) {
1186 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1187 return BAD_VALUE;
1188 }
1189 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1190 outDataspace, outComponentMask);
1191}
1192
Kevin DuBois74e53772018-11-19 10:52:38 -08001193status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1194 bool enable, uint8_t componentMask,
1195 uint64_t maxFrames) const {
1196 const auto display = getDisplayDevice(displayToken);
1197 if (!display || !display->getId()) {
1198 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1199 return BAD_VALUE;
1200 }
1201
1202 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1203 componentMask, maxFrames);
1204}
1205
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001206status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1207 uint64_t maxFrames, uint64_t timestamp,
1208 DisplayedFrameStats* outStats) const {
1209 const auto display = getDisplayDevice(displayToken);
1210 if (!display || !display->getId()) {
1211 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1212 return BAD_VALUE;
1213 }
1214
1215 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1216 outStats);
1217}
1218
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001219status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1220 if (!outSupported) {
1221 return BAD_VALUE;
1222 }
1223 *outSupported = getRenderEngine().supportsProtectedContent();
1224 return NO_ERROR;
1225}
1226
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001227status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1228 bool* outIsWideColorDisplay) const {
1229 if (!displayToken || !outIsWideColorDisplay) {
1230 return BAD_VALUE;
1231 }
1232 Mutex::Autolock _l(mStateLock);
1233 const auto display = getDisplayDeviceLocked(displayToken);
1234 if (!display) {
1235 return BAD_VALUE;
1236 }
Peiyong Linff84a152019-05-17 18:36:19 -07001237
1238 // Use hasWideColorDisplay to override built-in display.
1239 const auto displayId = display->getId();
1240 if (displayId && displayId == getInternalDisplayIdLocked()) {
1241 *outIsWideColorDisplay = hasWideColorDisplay;
1242 return NO_ERROR;
1243 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001244 *outIsWideColorDisplay = display->hasWideColorGamut();
1245 return NO_ERROR;
1246}
1247
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001248status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001249 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001250 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251
Chia-I Wu90f669f2017-10-05 14:24:41 -07001252 if (mInjectVSyncs == enable) {
1253 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001254 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255
Ana Krulecc2870422019-01-29 19:00:58 -08001256 auto resyncCallback =
1257 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001258
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001259 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001260 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001261 if (enable) {
1262 ALOGV("VSync Injections enabled");
1263 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001264 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001265 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001266 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001267 impl::EventThread::InterceptVSyncsCallback(),
1268 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001269 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001270 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001271 } else {
1272 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001273 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1274 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001275 }
1276
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001277 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001278 }));
1279
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001280 return NO_ERROR;
1281}
1282
1283status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001284 Mutex::Autolock _l(mStateLock);
1285
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001286 if (!mInjectVSyncs) {
1287 ALOGE("VSync Injections not enabled");
1288 return BAD_VALUE;
1289 }
1290 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1291 ALOGV("Injecting VSync inside SurfaceFlinger");
1292 mVSyncInjector->onInjectSyncEvent(when);
1293 }
1294 return NO_ERROR;
1295}
1296
Lloyd Pique755e3192018-01-31 16:46:15 -08001297status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1298 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001299 // Try to acquire a lock for 1s, fail gracefully
1300 const status_t err = mStateLock.timedLock(s2ns(1));
1301 const bool locked = (err == NO_ERROR);
1302 if (!locked) {
1303 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1304 return TIMED_OUT;
1305 }
1306
1307 outLayers->clear();
1308 mCurrentState.traverseInZOrder([&](Layer* layer) {
1309 outLayers->push_back(layer->getLayerDebugInfo());
1310 });
1311
1312 mStateLock.unlock();
1313 return NO_ERROR;
1314}
1315
Peiyong Linc6780972018-10-28 15:24:08 -07001316status_t SurfaceFlinger::getCompositionPreference(
1317 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1318 Dataspace* outWideColorGamutDataspace,
1319 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001320 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001321 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001322 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001323 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001324 return NO_ERROR;
1325}
1326
Dan Stozaec460082018-12-17 15:35:09 -08001327status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1328 const sp<IBinder>& stopLayerHandle,
1329 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001330 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001331 return BAD_VALUE;
1332 }
1333 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001334 return NO_ERROR;
1335}
1336
Dan Stozaec460082018-12-17 15:35:09 -08001337status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001338 if (!listener) {
1339 return BAD_VALUE;
1340 }
Dan Stozaec460082018-12-17 15:35:09 -08001341 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001342 return NO_ERROR;
1343}
Dan Gittik57e63c52019-01-18 16:37:54 +00001344
1345status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1346 bool* outSupport) const {
1347 if (!displayToken || !outSupport) {
1348 return BAD_VALUE;
1349 }
1350 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1351 if (!displayId) {
1352 return NAME_NOT_FOUND;
1353 }
1354 *outSupport =
1355 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1356 return NO_ERROR;
1357}
1358
1359status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1360 float brightness) const {
1361 if (!displayToken) {
1362 return BAD_VALUE;
1363 }
1364 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1365 if (!displayId) {
1366 return NAME_NOT_FOUND;
1367 }
1368 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1369}
1370
Ady Abraham8532d012019-05-08 14:50:56 -07001371status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1372 PowerHint powerHint = static_cast<PowerHint>(hintId);
1373
1374 if (powerHint == PowerHint::INTERACTION) {
1375 mScheduler->notifyTouchEvent();
1376 }
1377
1378 return NO_ERROR;
1379}
1380
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001381// ----------------------------------------------------------------------------
1382
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001383sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001384 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001385 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001386 Mutex::Autolock lock(mStateLock);
1387 return getVsyncPeriod();
1388 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001389
Ana Krulecc2870422019-01-29 19:00:58 -08001390 const auto& handle =
1391 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001392
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001393 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1394 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001395}
1396
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001398
1399void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001400 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001401}
1402
1403void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001404 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001405 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001406}
1407
1408void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001409 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001410 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001411}
1412
1413void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001414 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001415 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001416}
1417
1418status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001419 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001420 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001421}
1422
1423status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001424 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001425 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426 if (res == NO_ERROR) {
1427 msg->wait();
1428 }
1429 return res;
1430}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001431
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001432void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001433 do {
1434 waitForEvent();
1435 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001436}
1437
Dominik Laskowski83b88212018-12-11 13:34:06 -08001438nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001439 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001440 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1441 return 0;
1442 }
1443
1444 const auto config = getHwComposer().getActiveConfig(*displayId);
1445 return config ? config->getVsyncPeriod() : 0;
1446}
1447
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001448void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1449 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001450 ATRACE_NAME("SF onVsync");
1451
Steven Thomas3cfac282017-02-06 12:29:30 -08001452 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 return;
1456 }
1457
Dominik Laskowski075d3172018-05-24 15:50:06 -07001458 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001459 return;
1460 }
1461
Dominik Laskowski075d3172018-05-24 15:50:06 -07001462 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001463 // For now, we don't do anything with external display vsyncs.
1464 return;
1465 }
1466
Alec Mourif8e689c2019-05-20 18:32:22 -07001467 bool periodFlushed = false;
1468 mScheduler->addResyncSample(timestamp, &periodFlushed);
1469 if (periodFlushed) {
1470 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001471 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001472}
1473
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001474void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001475 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1476 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001477}
1478
Ady Abraham261614e2019-07-10 17:53:12 -07001479bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001480 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001481}
1482
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001483void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001484 const auto display = getDefaultDisplayDeviceLocked();
1485 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001486 return;
1487 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001488 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001489
Ana Krulec7d1d6832018-12-27 11:10:09 -08001490 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001491 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001492 if (!refreshRateConfig) {
1493 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001494 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001495 }
Ady Abraham1902d072019-03-01 17:18:59 -08001496
Alec Mouri0a1cc962019-03-14 12:33:02 -07001497 const int desiredConfigId = refreshRateConfig->configId;
1498
Dominik Laskowski22488f62019-03-28 09:53:04 -07001499 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001500 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1501 return;
1502 }
1503
Dominik Laskowski22488f62019-03-28 09:53:04 -07001504 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001505}
1506
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001507void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001508 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001509 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001510 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001511
Lloyd Piqueba04e622017-12-14 17:11:26 -08001512 // Ignore events that do not have the right sequenceId.
1513 if (sequenceId != getBE().mComposerSequenceId) {
1514 return;
1515 }
1516
Steven Thomasb02664d2017-07-26 18:48:28 -07001517 // Only lock if we're not on the main thread. This function is normally
1518 // called on a hwbinder thread, but for the primary display it's called on
1519 // the main thread with the state lock already held, so don't attempt to
1520 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001521 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001524
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001525 if (std::this_thread::get_id() == mMainThreadId) {
1526 // Process all pending hot plug events immediately if we are on the main thread.
1527 processDisplayHotplugEventsLocked();
1528 }
1529
Lloyd Piqueba04e622017-12-14 17:11:26 -08001530 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001531}
1532
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001533void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001534 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001535 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001536 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001537 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001538 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001539}
1540
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001541void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001542 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001543
1544 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1545 // display power state.
1546 postMessageAsync(new LambdaMessage(
1547 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1548}
1549
1550void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1551 ATRACE_CALL();
1552
Ady Abraham27c70212019-06-11 10:52:26 -07001553 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1554
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001555 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001556 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1557 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001558 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001559 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001560 }
Mathias Agopian86303202012-07-24 22:46:10 -07001561}
1562
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001563// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001564void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001565 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566 // Clear the drawing state so that the logic inside of
1567 // handleTransactionLocked will fire. It will determine the delta between
1568 // mCurrentState and mDrawingState and re-apply all changes when we make the
1569 // transition.
1570 mDrawingState.displays.clear();
1571 mDisplays.clear();
1572}
1573
Steven Thomas050b2c82017-03-06 11:45:16 -08001574void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001575 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001576 if (!mVrFlinger)
1577 return;
1578 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001579 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001580 return;
1581 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582
Lloyd Pique441d5042018-10-18 16:49:51 -07001583 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 ALOGE("Vr flinger is only supported for remote hardware composer"
1585 " service connections. Ignoring request to transition to vr"
1586 " flinger.");
1587 mVrFlingerRequestsDisplay = false;
1588 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001589 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001590
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001591 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001592
Steven Thomas0123ac62018-07-12 11:32:34 -07001593 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001594 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001595
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001596 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001597
1598 // Clear out all the output layers from the composition engine for all
1599 // displays before destroying the hardware composer interface. This ensures
1600 // any HWC layers are destroyed through that interface before it becomes
1601 // invalid.
1602 for (const auto& [token, displayDevice] : mDisplays) {
1603 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1604 compositionengine::Output::OutputLayers());
1605 }
1606
Steven Thomas0123ac62018-07-12 11:32:34 -07001607 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1608 // called below. Clear the reference now so we don't accidentally use it
1609 // later.
1610 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001611
Steven Thomasb02664d2017-07-26 18:48:28 -07001612 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001614 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001615
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001617 // Delete the current instance before creating the new one
1618 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1619 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1620 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1621 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001624 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001625
1626 if (vrFlingerRequestsDisplay) {
1627 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001628 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001629
1630 mVisibleRegionsDirty = true;
1631 invalidateHwcGeometry();
1632
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001633 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001634 display = getDefaultDisplayDeviceLocked();
1635 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001636 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001639 const nsecs_t vsyncPeriod = getVsyncPeriod();
1640 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001641
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001642 // The present fences returned from vr_hwc are not an accurate
1643 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001644 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001645
Steven Thomasb02664d2017-07-26 18:48:28 -07001646 // Use phase of 0 since phase is not known.
1647 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001648 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001649 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001650
Ana Krulecc2870422019-01-29 19:00:58 -08001651 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001652
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001653 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001654 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655}
1656
Ady Abrahambe0f9482019-04-24 15:41:53 -07001657bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1658 // We are storing the last 2 present fences. If sf's phase offset is to be
1659 // woken up before the actual vsync but targeting the next vsync, we need to check
1660 // fence N-2
1661 const sp<Fence>& fence =
1662 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1663 ? mPreviousPresentFences[0]
1664 : mPreviousPresentFences[1];
1665
1666 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1667}
1668
Alec Mouriaa614192019-06-06 13:28:34 -07001669nsecs_t SurfaceFlinger::getExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
1670 DisplayStatInfo stats;
1671 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001672 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001673 // Inflate the expected present time if we're targetting the next vsync.
1674 const nsecs_t correctedTime =
1675 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1676 ? presentTime
1677 : presentTime + stats.vsyncPeriod;
1678 return correctedTime;
1679}
1680
Dominik Laskowski22488f62019-03-28 09:53:04 -07001681void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001682 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001683 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001684 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001685 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001686 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1687 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1688 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1689 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1690 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1691 if (frameMissed) {
1692 mFrameMissedCount++;
1693 mTimeStats->incrementMissedFrames();
1694 }
1695
Alec Mouri40189b02019-03-05 15:07:54 -08001696 if (hwcFrameMissed) {
1697 mHwcFrameMissedCount++;
1698 }
1699
1700 if (gpuFrameMissed) {
1701 mGpuFrameMissedCount++;
1702 }
1703
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001704 if (mUseSmart90ForVideo) {
1705 // This call is made each time SF wakes up and creates a new frame. It is part
1706 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001707 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001708 }
1709
Ady Abrahamb838aed2019-02-12 15:30:16 -08001710 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001711 break;
1712 }
1713
Alec Mourife3dc942019-02-12 14:19:18 -08001714 // For now, only propagate backpressure when missing a hwc frame.
Alec Mourib0f45822019-05-06 11:01:35 -07001715 if (hwcFrameMissed && !gpuFrameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001716 if (mPropagateBackpressure) {
1717 signalLayerUpdate();
1718 break;
1719 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001720 }
Dan Stoza50182882016-07-08 12:02:20 -07001721
Steven Thomas050b2c82017-03-06 11:45:16 -08001722 // Now that we're going to make it to the handleMessageTransaction()
1723 // call below it's safe to call updateVrFlinger(), which will
1724 // potentially trigger a display handoff.
1725 updateVrFlinger();
1726
Dan Stoza6b9454d2014-11-07 16:00:59 -08001727 bool refreshNeeded = handleMessageTransaction();
1728 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001729
1730 updateCursorAsync();
1731 updateInputFlinger();
1732
Dan Stoza58784442014-12-02 16:58:17 -08001733 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001734 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001735 // Signal a refresh if a transaction modified the window state,
1736 // a new buffer was latched, or if HWC has requested a full
1737 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001738 signalRefresh();
1739 }
1740 break;
1741 }
1742 case MessageQueue::REFRESH: {
1743 handleMessageRefresh();
1744 break;
1745 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001746 }
1747}
1748
Dan Stoza6b9454d2014-11-07 16:00:59 -08001749bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001750 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001751 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001752
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001753 bool flushedATransaction = flushTransactionQueues();
1754
1755 bool runHandleTransaction = transactionFlags &&
1756 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1757
1758 if (runHandleTransaction) {
1759 handleTransaction(eTransactionMask);
1760 } else {
1761 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001762 }
1763
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001764 if (transactionFlushNeeded()) {
1765 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001766 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001767
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001768 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001769}
1770
Mathias Agopian4fec8732012-06-29 14:12:52 -07001771void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001772 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001773
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001774 mRefreshPending = false;
1775
Lloyd Piqueab039b52019-02-13 14:22:42 -08001776 compositionengine::CompositionRefreshArgs refreshArgs;
1777 for (const auto& [_, display] : mDisplays) {
1778 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1779 }
1780 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1781 auto compositionLayer = layer->getCompositionLayer();
1782 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1783 });
1784
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001785 const bool repaintEverything = mRepaintEverything.exchange(false);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001786 mCompositionEngine->preComposition(refreshArgs);
Lloyd Pique074e8122018-07-26 12:57:23 -07001787 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001788 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001789 for (const auto& [token, display] : mDisplays) {
1790 beginFrame(display);
1791 prepareFrame(display);
1792 doDebugFlashRegions(display, repaintEverything);
1793 doComposition(display, repaintEverything);
1794 }
1795
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001796 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001797
1798 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001799 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001800
Dan Stozabfbffeb2016-07-21 14:49:33 -07001801 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001802 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001803 for (const auto& [token, displayDevice] : mDisplays) {
1804 auto display = displayDevice->getCompositionDisplay();
1805 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001806 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001807 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001808 mHadDeviceComposition =
1809 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001810 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001811
Jorim Jaggi90535212018-05-23 23:44:06 +02001812 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001813
David Sodman7e4ae112018-02-09 15:02:28 -08001814 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001815 if (mVisibleRegionsDirty) {
1816 mVisibleRegionsDirty = false;
1817 if (mTracingEnabled) {
1818 mTracing.notify("visibleRegionsDirty");
1819 }
1820 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001821
1822 if (mCompositionEngine->needsAnotherUpdate()) {
1823 signalLayerUpdate();
1824 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001826
David Sodmanfa9b2af2017-12-24 13:28:59 -08001827
1828bool SurfaceFlinger::handleMessageInvalidate() {
1829 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001830 bool refreshNeeded = handlePageFlip();
1831
Vishnu Nair4351ad52019-02-11 14:13:02 -08001832 if (mVisibleRegionsDirty) {
1833 computeLayerBounds();
1834 }
1835
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001836 for (auto& layer : mLayersPendingRefresh) {
1837 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001838 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001839 invalidateLayerStack(layer, visibleReg);
1840 }
1841 mLayersPendingRefresh.clear();
1842 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001843}
1844
David Sodman79bba0e2018-08-05 18:07:49 -07001845void SurfaceFlinger::calculateWorkingSet() {
1846 ATRACE_CALL();
1847 ALOGV(__FUNCTION__);
1848
Lloyd Piquef5275482019-01-29 18:42:42 -08001849 const bool updatingGeometryThisFrame = mGeometryInvalid;
1850 mGeometryInvalid = false;
1851
1852 {
1853 // Use a map so that we latch the state of each front-end layer once.
1854 std::unordered_map<compositionengine::LayerFE*, compositionengine::LayerFECompositionState*>
1855 uniqueVisibleLayers;
1856
1857 // Figure out which frontend layers are being composed, and build the unique
1858 // set of them (and the corresponding composition layer)
Lloyd Pique32cbe282018-10-19 13:09:22 -07001859 for (const auto& [token, displayDevice] : mDisplays) {
1860 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquef5275482019-01-29 18:42:42 -08001861 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1862 uniqueVisibleLayers.insert(std::make_pair(&layer->getLayerFE(),
1863 &layer->getLayer().editState().frontEnd));
1864 }
1865 }
David Sodman79bba0e2018-08-05 18:07:49 -07001866
Lloyd Piquef5275482019-01-29 18:42:42 -08001867 // Update the composition state from each front-end layer.
1868 for (auto& [layerFE, state] : uniqueVisibleLayers) {
1869 layerFE->latchCompositionState(*state, updatingGeometryThisFrame);
1870 }
1871 }
1872
1873 if (CC_UNLIKELY(updatingGeometryThisFrame)) {
1874 for (const auto& [token, displayDevice] : mDisplays) {
1875 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquea83776c2019-01-29 18:42:32 -08001876 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001877
Lloyd Piquea83776c2019-01-29 18:42:32 -08001878 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquef5275482019-01-29 18:42:42 -08001879 // Assign a simple Z order sequence to each visible layer.
1880 layer->editState().z = zOrder++;
David Sodman79bba0e2018-08-05 18:07:49 -07001881 }
1882 }
1883 }
1884
Lloyd Piquef5275482019-01-29 18:42:42 -08001885 // Determine the color configuration of each output
Lloyd Pique32cbe282018-10-19 13:09:22 -07001886 for (const auto& [token, displayDevice] : mDisplays) {
1887 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001888
Lloyd Piquef5275482019-01-29 18:42:42 -08001889 ColorMode colorMode = ColorMode::NATIVE;
1890 Dataspace dataspace = Dataspace::UNKNOWN;
1891 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1892 if (useColorManagement) {
1893 pickColorMode(displayDevice, &colorMode, &dataspace, &renderIntent);
1894 }
1895 display->setColorMode(colorMode, dataspace, renderIntent, mColorSpaceAgnosticDataspace);
1896 }
1897
1898 for (const auto& [token, displayDevice] : mDisplays) {
1899 auto display = displayDevice->getCompositionDisplay();
1900
1901 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1902 // Update the composition state of the output layer, as needed
1903 // recomputing it from the state given by the front-end layer.
1904 layer->updateCompositionState(updatingGeometryThisFrame);
1905 }
1906 }
1907
1908 for (const auto& [token, displayDevice] : mDisplays) {
1909 auto display = displayDevice->getCompositionDisplay();
1910
1911 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1912 // Send the updated state to the HWC, if appropriate.
1913 layer->writeStateToHWC(updatingGeometryThisFrame);
1914 }
1915 }
1916
1917 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1918 for (const auto& [token, displayDevice] : mDisplays) {
1919 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001920 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001921 }
Lloyd Piquef5275482019-01-29 18:42:42 -08001922 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001923 }
David Sodman79bba0e2018-08-05 18:07:49 -07001924}
1925
Lloyd Pique32cbe282018-10-19 13:09:22 -07001926void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1927 bool repaintEverything) {
1928 auto display = displayDevice->getCompositionDisplay();
1929 const auto& displayState = display->getState();
1930
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931 // is debugging enabled
1932 if (CC_LIKELY(!mDebugRegion))
1933 return;
1934
Lloyd Pique32cbe282018-10-19 13:09:22 -07001935 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001936 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001937 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001938 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001939 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001940 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001941 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001942
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001943 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001944 }
1945 }
1946
Lloyd Pique32cbe282018-10-19 13:09:22 -07001947 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948
1949 if (mDebugRegion > 1) {
1950 usleep(mDebugRegion * 1000);
1951 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001952
Lloyd Pique32cbe282018-10-19 13:09:22 -07001953 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001954}
1955
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001956void SurfaceFlinger::logLayerStats() {
1957 ATRACE_CALL();
1958 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001959 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001960 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001961 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001962 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001963 }
1964 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001965
1966 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001967 }
1968}
1969
Ana Krulece588e312018-09-18 12:32:24 -07001970void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1971 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972 // Update queue of past composite+present times and determine the
1973 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001974 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001976 while (!getBE().mCompositePresentTimes.empty()) {
1977 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978 // Cached values should have been updated before calling this method,
1979 // which helps avoid duplicate syscalls.
1980 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1981 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1982 break;
1983 }
1984 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001985 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986 }
1987
1988 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001989 while (getBE().mCompositePresentTimes.size() > 16) {
1990 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991 }
1992
Ana Krulece588e312018-09-18 12:32:24 -07001993 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001994}
1995
Ana Krulece588e312018-09-18 12:32:24 -07001996void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1997 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001998 // Integer division and modulo round toward 0 not -inf, so we need to
1999 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002000 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2001 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2002 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002003
Ana Krulec757f63a2019-01-25 10:46:18 -08002004 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002005 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002006 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002007 }
2008
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002009 // Snap the latency to a value that removes scheduling jitter from the
2010 // composition and present times, which often have >1ms of jitter.
2011 // Reducing jitter is important if an app attempts to extrapolate
2012 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002013 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002014 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002015 nsecs_t bias = stats.vsyncPeriod / 2;
2016 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2017 nsecs_t snappedCompositeToPresentLatency =
2018 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002019
David Sodman99974d22017-11-28 12:04:33 -08002020 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002021 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2022 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002023 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002024}
2025
David Sodman2b406362017-12-15 13:33:47 -08002026void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002027{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 ATRACE_CALL();
2029 ALOGV("postComposition");
2030
Brian Anderson3546a3f2016-07-14 11:51:14 -07002031 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002032 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002033 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002034 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002035 }
2036
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002037 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002038 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002039
David Sodman73beded2017-11-15 11:56:06 -08002040 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002042 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002044 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2045 ->getRenderSurface()
2046 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002047 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002048 } else {
2049 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2050 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051
David Sodman73beded2017-11-15 11:56:06 -08002052 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002053 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2054 mPreviousPresentFences[0] = displayDevice
2055 ? getHwComposer().getPresentFence(*displayDevice->getId())
2056 : Fence::NO_FENCE;
2057 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002058 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002059
Ana Krulece588e312018-09-18 12:32:24 -07002060 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002061 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062
Lloyd Piqueab039b52019-02-13 14:22:42 -08002063 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2064 // be sampled a little later than when we started doing work for this frame,
2065 // but that should be okay since updateCompositorTiming has snapping logic.
2066 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2067 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002068 CompositorTiming compositorTiming;
2069 {
David Sodman99974d22017-11-28 12:04:33 -08002070 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2071 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002072 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002073
Robert Carr2047fae2016-11-28 14:09:09 -08002074 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002075 bool frameLatched =
2076 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2077 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002078 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002079 recordBufferingStats(layer->getName().string(),
2080 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002081 }
Robert Carr2047fae2016-11-28 14:09:09 -08002082 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002083
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002084 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002085 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002086 }
2087
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002088 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002089 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2090 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002091 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002092 }
2093 }
2094
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002095 if (mAnimCompositionPending) {
2096 mAnimCompositionPending = false;
2097
Brian Anderson4e606e32017-03-16 15:34:57 -07002098 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002099 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002100 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 // The HWC doesn't support present fences, so use the refresh
2103 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 const nsecs_t presentTime =
2105 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 mAnimFrameTracker.setActualPresentTime(presentTime);
2107 }
2108 mAnimFrameTracker.advanceFrame();
2109 }
Dan Stozab90cf072015-03-05 11:05:59 -08002110
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002111 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002112 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002113 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002114 }
2115
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002116 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002117
Lloyd Pique32cbe282018-10-19 13:09:22 -07002118 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2119 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002120 return;
2121 }
2122
2123 nsecs_t currentTime = systemTime();
2124 if (mHasPoweredOff) {
2125 mHasPoweredOff = false;
2126 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002127 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002128 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002129 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2130 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002131 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002132 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002133 }
David Sodman4a36e932017-11-07 14:29:47 -08002134 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002135 }
David Sodman4a36e932017-11-07 14:29:47 -08002136 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002137
2138 {
2139 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002140 if (mTexturePool.size() < mTexturePoolSize) {
2141 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002142 const size_t offset = mTexturePool.size();
2143 mTexturePool.resize(mTexturePoolSize);
2144 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2145 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002146 } else if (mTexturePool.size() > mTexturePoolSize) {
2147 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2148 const size_t offset = mTexturePoolSize;
2149 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2150 mTexturePool.resize(mTexturePoolSize);
2151 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002152 }
2153 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002154
Ady Abrahambe0f9482019-04-24 15:41:53 -07002155 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002156 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002157
Kevin DuBois413287f2019-02-25 08:46:47 -08002158 if (mLumaSampling && mRegionSamplingThread) {
2159 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002160 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002161
2162 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2163 // side-effect of getTotalSize(), so we check that again here
2164 if (ATRACE_ENABLED()) {
2165 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2166 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002167}
2168
Vishnu Nair4351ad52019-02-11 14:13:02 -08002169void SurfaceFlinger::computeLayerBounds() {
2170 for (const auto& pair : mDisplays) {
2171 const auto& displayDevice = pair.second;
2172 const auto display = displayDevice->getCompositionDisplay();
2173 for (const auto& layer : mDrawingState.layersSortedByZ) {
2174 // only consider the layers on the given layer stack
2175 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002176 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002177 }
2178
2179 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2180 }
2181 }
2182}
2183
Mathias Agopiancd60f992012-08-16 16:28:27 -07002184void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002185 ATRACE_CALL();
2186 ALOGV("rebuildLayerStacks");
2187
Mathias Agopiancd60f992012-08-16 16:28:27 -07002188 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002189 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002190 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002191 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002192
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002193 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002194 const auto& displayDevice = pair.second;
2195 auto display = displayDevice->getCompositionDisplay();
2196 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002197 Region opaqueRegion;
2198 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002199 compositionengine::Output::OutputLayers layersSortedByZ;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002200 compositionengine::Output::ReleasedLayers releasedLayers;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002201 Vector<sp<Layer>> deprecated_layersSortedByZ;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002202 const ui::Transform& tr = displayState.transform;
2203 const Rect bounds = displayState.bounds;
2204 if (displayState.isEnabled) {
2205 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002206
Jeff Sharkey76488112017-02-27 14:15:18 -07002207 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002208 auto compositionLayer = layer->getCompositionLayer();
2209 if (compositionLayer == nullptr) {
2210 return;
2211 }
2212
Lloyd Pique32cbe282018-10-19 13:09:22 -07002213 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002214 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2215 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2216
Lloyd Pique07e33212018-12-18 16:33:37 -08002217 bool needsOutputLayer = false;
2218
Lloyd Piqueef36b002019-01-23 17:52:04 -08002219 if (display->belongsInOutput(layer->getLayerStack(),
2220 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002221 Region drawRegion(tr.transform(
2222 layer->visibleNonTransparentRegion));
2223 drawRegion.andSelf(bounds);
2224 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002225 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002226 }
Chia-I Wu83806892017-11-16 10:50:20 -08002227 }
2228
Lloyd Pique07e33212018-12-18 16:33:37 -08002229 if (needsOutputLayer) {
2230 layersSortedByZ.emplace_back(
2231 display->getOrCreateOutputLayer(displayId, compositionLayer,
2232 layerFE));
2233 deprecated_layersSortedByZ.add(layer);
2234
2235 auto& outputLayerState = layersSortedByZ.back()->editState();
2236 outputLayerState.visibleRegion =
2237 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2238 } else if (displayId) {
2239 // For layers that are being removed from a HWC display,
2240 // and that have queued frames, add them to a a list of
2241 // released layers so we can properly set a fence.
2242 bool hasExistingOutputLayer =
2243 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2244 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2245 mLayersWithQueuedFrames.cend(),
2246 layer) != mLayersWithQueuedFrames.cend();
2247
2248 if (hasExistingOutputLayer && hasQueuedFrames) {
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002249 releasedLayers.push_back(layer);
Chia-I Wu83806892017-11-16 10:50:20 -08002250 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002251 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002252 });
2253 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002254
2255 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002256 display->setReleasedLayers(std::move(releasedLayers));
Lloyd Piquecc01a452018-12-04 17:24:00 -08002257
2258 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002259
2260 Region undefinedRegion{bounds};
2261 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2262
2263 display->editState().undefinedRegion = undefinedRegion;
2264 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002265 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002266 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002267}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002268
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002269// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002270// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002271// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002272// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002273// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002274// The returned HDR data space is one of
2275// - Dataspace::UNKNOWN
2276// - Dataspace::BT2020_HLG
2277// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002278Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2279 Dataspace* outHdrDataSpace,
2280 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002281 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002282 *outHdrDataSpace = Dataspace::UNKNOWN;
2283
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002284 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002285 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286 case Dataspace::V0_SCRGB:
2287 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002288 case Dataspace::BT2020:
2289 case Dataspace::BT2020_ITU:
2290 case Dataspace::BT2020_LINEAR:
2291 case Dataspace::DISPLAY_BT2020:
2292 bestDataSpace = Dataspace::DISPLAY_BT2020;
2293 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002294 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002295 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002296 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 case Dataspace::BT2020_PQ:
2298 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002299 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 *outHdrDataSpace = Dataspace::BT2020_PQ;
Lloyd Piquef5275482019-01-29 18:42:42 -08002301 *outIsHdrClientComposition =
2302 layer->getCompositionLayer()->getState().frontEnd.forceClientComposition;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002303 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002304 case Dataspace::BT2020_HLG:
2305 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002306 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002307 // When there's mixed PQ content and HLG content, we set the HDR
2308 // data space to be BT2020_PQ and convert HLG to PQ.
2309 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2310 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002311 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002312 break;
2313 default:
2314 break;
2315 }
Romain Guy54f154a2017-10-24 21:40:32 +01002316 }
2317
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002319}
2320
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002322void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2323 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002324 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2325 *outMode = ColorMode::NATIVE;
2326 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002327 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002329 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002330
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002332 bool isHdrClientComposition = false;
2333 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002335 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2336
Peiyong Lina3ea5592019-02-10 14:45:00 -08002337 switch (mForceColorMode) {
2338 case ColorMode::SRGB:
2339 bestDataSpace = Dataspace::V0_SRGB;
2340 break;
2341 case ColorMode::DISPLAY_P3:
2342 bestDataSpace = Dataspace::DISPLAY_P3;
2343 break;
2344 default:
2345 break;
2346 }
2347
Peiyong Lindfde5112018-06-05 10:58:41 -07002348 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002349 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2350 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002351 if (isHdr) {
2352 bestDataSpace = hdrDataSpace;
2353 }
2354
Chia-I Wu0d711262018-05-21 15:19:35 -07002355 RenderIntent intent;
2356 switch (mDisplayColorSetting) {
2357 case DisplayColorSetting::MANAGED:
2358 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002359 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002360 break;
2361 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002362 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002363 break;
2364 default: // vendor display color setting
2365 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2366 break;
2367 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002368
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002369 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002370}
2371
Lloyd Pique32cbe282018-10-19 13:09:22 -07002372void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2373 auto display = displayDevice->getCompositionDisplay();
2374 const auto& displayState = display->getState();
2375
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002376 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002377 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2378 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002379
David Sodmanfa9b2af2017-12-24 13:28:59 -08002380 // If nothing has changed (!dirty), don't recompose.
2381 // If something changed, but we don't currently have any visible layers,
2382 // and didn't when we last did a composition, then skip it this time.
2383 // The second rule does two things:
2384 // - When all layers are removed from a display, we'll emit one black
2385 // frame, then nothing more until we get new layers.
2386 // - When a display is created with a private layer stack, we won't
2387 // emit any black frames until a layer is added to the layer stack.
2388 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002389
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 const char flagPrefix[] = {'-', '+'};
2391 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002392 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2393 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2394 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2395 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002396
Lloyd Pique31cb2942018-10-19 17:23:03 -07002397 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002398
David Sodmanfa9b2af2017-12-24 13:28:59 -08002399 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002400 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002401 }
2402}
2403
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2405 auto display = displayDevice->getCompositionDisplay();
2406 const auto& displayState = display->getState();
2407
2408 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002409 return;
David Sodman2b406362017-12-15 13:33:47 -08002410 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002411
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002412 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002414 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002415}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002416
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002418 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002419 ALOGV("doComposition");
2420
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421 auto display = displayDevice->getCompositionDisplay();
2422 const auto& displayState = display->getState();
2423
2424 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002425 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002426 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002427
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002429 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002430
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002432 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002433 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002434 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002435}
2436
David Sodmanfa9b2af2017-12-24 13:28:59 -08002437void SurfaceFlinger::postFrame()
2438{
2439 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 const auto display = getDefaultDisplayDeviceLocked();
2441 if (display && getHwComposer().isConnected(*display->getId())) {
2442 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002443 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2444 logFrameStats();
2445 }
2446 }
2447}
2448
Lloyd Pique32cbe282018-10-19 13:09:22 -07002449void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002450 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002451 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002452
Lloyd Pique32cbe282018-10-19 13:09:22 -07002453 auto display = displayDevice->getCompositionDisplay();
2454 const auto& displayState = display->getState();
2455 const auto displayId = display->getId();
2456
Lloyd Pique32cbe282018-10-19 13:09:22 -07002457 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002458 if (displayId) {
2459 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002460 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002461 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002462 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002463 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002464 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002465
Chia-I Wu7b549592017-11-15 09:14:57 -08002466 // The layer buffer from the previous frame (if any) is released
2467 // by HWC only when the release fence from this frame (if any) is
2468 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002469 if (layer->getState().hwc) {
2470 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002471 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002472 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2473 usedClientComposition =
2474 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002475 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002476
2477 // If the layer was client composited in the previous frame, we
2478 // need to merge with the previous client target acquire fence.
2479 // Since we do not track that, always merge with the current
2480 // client target acquire fence when it is available, even though
2481 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002482 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002483 releaseFence =
2484 Fence::merge("LayerRelease", releaseFence,
2485 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002486 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002487
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002488 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002489 }
Chia-I Wu83806892017-11-16 10:50:20 -08002490
2491 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002492 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002493 // supply them with the present fence.
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002494 auto releasedLayers = display->takeReleasedLayers();
2495 if (!releasedLayers.empty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002497 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002498 for (auto& weakLayer : releasedLayers) {
2499 if (auto layer = weakLayer.promote(); layer != nullptr) {
2500 layer->onLayerDisplayed(presentFence);
2501 }
Chia-I Wu83806892017-11-16 10:50:20 -08002502 }
2503 }
2504
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 if (displayId) {
2506 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002507 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002508 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509}
2510
Mathias Agopian87baae12012-07-31 12:38:26 -07002511void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002512{
Mathias Agopian841cde52012-03-01 15:44:37 -08002513 ATRACE_CALL();
2514
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002515 // here we keep a copy of the drawing state (that is the state that's
2516 // going to be overwritten by handleTransactionLocked()) outside of
2517 // mStateLock so that the side-effects of the State assignment
2518 // don't happen with mStateLock held (which can cause deadlocks).
2519 State drawingState(mDrawingState);
2520
Mathias Agopianca4d3602011-05-19 15:38:14 -07002521 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002522 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523
Mathias Agopianca4d3602011-05-19 15:38:14 -07002524 // Here we're guaranteed that some transaction flags are set
2525 // so we can call handleTransactionLocked() unconditionally.
2526 // We call getTransactionFlags(), which will also clear the flags,
2527 // with mStateLock held to guarantee that mCurrentState won't change
2528 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002529
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002530 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002531 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002532 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002533
Mathias Agopianca4d3602011-05-19 15:38:14 -07002534 mDebugInTransaction = 0;
2535 invalidateHwcGeometry();
2536 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002537}
2538
Lloyd Piqueba04e622017-12-14 17:11:26 -08002539void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2540 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002541 const std::optional<DisplayIdentificationInfo> info =
2542 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002543
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002545 continue;
2546 }
2547
Lloyd Piqueba04e622017-12-14 17:11:26 -08002548 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002549 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002550 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 mPhysicalDisplayTokens[info->id] = new BBinder();
2552 DisplayDeviceState state;
2553 state.displayId = info->id;
2554 state.isSecure = true; // All physical displays are currently considered secure.
2555 state.displayName = info->name;
2556 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2557 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002558 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002559 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002560 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002561
Dominik Laskowski075d3172018-05-24 15:50:06 -07002562 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2563 if (index >= 0) {
2564 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2565 mInterceptor->saveDisplayDeletion(state.sequenceId);
2566 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002567 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002569 }
2570
2571 processDisplayChangesLocked();
2572 }
2573
2574 mPendingHotplugEvents.clear();
2575}
2576
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002577void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002578 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2579 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002580}
2581
Lloyd Pique99d3da52018-01-22 17:48:03 -08002582sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002584 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 const sp<IGraphicBufferProducer>& producer) {
2586 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002587 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002589 creationArgs.isSecure = state.isSecure;
2590 creationArgs.displaySurface = dispSurface;
2591 creationArgs.hasWideColorGamut = false;
2592 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002593
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002594 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 creationArgs.isPrimary = isInternalDisplay;
2596
2597 if (useColorManagement && displayId) {
2598 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002600 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002601 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002602 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002603
Dominik Laskowski7e045462018-05-30 13:02:02 -07002604 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002607 }
tangrobin6753a022018-08-10 10:58:54 +08002608 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002609
Dominik Laskowski075d3172018-05-24 15:50:06 -07002610 if (displayId) {
2611 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002612 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002614 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615
Lloyd Pique90c115d2018-09-18 21:39:42 -07002616 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002617 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002618 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619
Lloyd Pique99d3da52018-01-22 17:48:03 -08002620 // Make sure that composition can never be stalled by a virtual display
2621 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002622 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002623 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2625 }
2626
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 creationArgs.displayInstallOrientation =
2628 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002629
Lloyd Pique99d3da52018-01-22 17:48:03 -08002630 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002631 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632
Lloyd Pique90c115d2018-09-18 21:39:42 -07002633 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634
2635 if (maxFrameBufferAcquiredBuffers >= 3) {
2636 nativeWindowSurface->preallocateBuffers();
2637 }
2638
2639 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002640 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002641 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002642 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002643 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002644 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002645 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
Lloyd Piquef5275482019-01-29 18:42:42 -08002646 RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002647 if (!state.isVirtual()) {
2648 LOG_ALWAYS_FATAL_IF(!displayId);
2649 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002650 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002651
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002652 display->setLayerStack(state.layerStack);
2653 display->setProjection(state.orientation, state.viewport, state.frame);
2654 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002656 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002657}
2658
Lloyd Pique347200f2017-12-14 17:00:15 -08002659void SurfaceFlinger::processDisplayChangesLocked() {
2660 // here we take advantage of Vector's copy-on-write semantics to
2661 // improve performance by skipping the transaction entirely when
2662 // know that the lists are identical
2663 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2664 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2665 if (!curr.isIdenticalTo(draw)) {
2666 mVisibleRegionsDirty = true;
2667 const size_t cc = curr.size();
2668 size_t dc = draw.size();
2669
2670 // find the displays that were removed
2671 // (ie: in drawing state but not in current state)
2672 // also handle displays that changed
2673 // (ie: displays that are in both lists)
2674 for (size_t i = 0; i < dc;) {
2675 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2676 if (j < 0) {
2677 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002679 // Save display ID before disconnecting.
2680 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002681 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002682
2683 if (!display->isVirtual()) {
2684 LOG_ALWAYS_FATAL_IF(!displayId);
2685 dispatchDisplayHotplugEvent(displayId->value, false);
2686 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002687 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002688
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002689 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002690 } else {
2691 // this display is in both lists. see if something changed.
2692 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002693 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002694 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2695 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2696 if (state_binder != draw_binder) {
2697 // changing the surface is like destroying and
2698 // recreating the DisplayDevice, so we just remove it
2699 // from the drawing state, so that it get re-added
2700 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002701 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002702 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002704 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 mDrawingState.displays.removeItemsAt(i);
2706 dc--;
2707 // at this point we must loop to the next item
2708 continue;
2709 }
2710
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002713 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002714 }
2715 if ((state.orientation != draw[i].orientation) ||
2716 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002717 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 }
2719 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002720 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002721 }
2722 }
2723 }
2724 ++i;
2725 }
2726
2727 // find displays that were added
2728 // (ie: in current state but not in drawing state)
2729 for (size_t i = 0; i < cc; i++) {
2730 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2731 const DisplayDeviceState& state(curr[i]);
2732
Lloyd Pique542307f2018-10-19 13:24:08 -07002733 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 sp<IGraphicBufferProducer> producer;
2735 sp<IGraphicBufferProducer> bqProducer;
2736 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002737 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738
Dominik Laskowski075d3172018-05-24 15:50:06 -07002739 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002740 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 // Virtual displays without a surface are dormant:
2742 // they have external state (layer stack, projection,
2743 // etc.) but no internal state (i.e. a DisplayDevice).
2744 if (state.surface != nullptr) {
2745 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002746 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002747 int width = 0;
2748 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2749 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2750 int height = 0;
2751 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2752 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2753 int intFormat = 0;
2754 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2755 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002756 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002757
Dominik Laskowski075d3172018-05-24 15:50:06 -07002758 displayId =
2759 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 }
2761
2762 // TODO: Plumb requested format back up to consumer
2763
2764 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002765 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002766 bqProducer, bqConsumer,
2767 state.displayName);
2768
2769 dispSurface = vds;
2770 producer = vds;
2771 }
2772 } else {
2773 ALOGE_IF(state.surface != nullptr,
2774 "adding a supported display, but rendering "
2775 "surface is provided (%p), ignoring it",
2776 state.surface.get());
2777
Dominik Laskowski075d3172018-05-24 15:50:06 -07002778 displayId = state.displayId;
2779 LOG_ALWAYS_FATAL_IF(!displayId);
2780 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 producer = bqProducer;
2782 }
2783
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002784 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002785 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002786 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002787 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002788 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002789 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002790 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002791 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002792 }
2793 }
2794 }
2795 }
2796 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002797
2798 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002799}
2800
Mathias Agopian87baae12012-07-31 12:38:26 -07002801void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002802{
Dan Stoza7dde5992015-05-22 09:51:44 -07002803 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002804 mCurrentState.traverseInZOrder([](Layer* layer) {
2805 layer->notifyAvailableFrames();
2806 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002807
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 /*
2809 * Traversal of the children
2810 * (perform the transaction for each of them if needed)
2811 */
2812
Marissa Wall06255332019-03-27 13:48:27 -07002813 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002816 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817
2818 const uint32_t flags = layer->doTransaction(0);
2819 if (flags & Layer::eVisibleRegion)
2820 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002821
2822 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002823 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002824 }
Robert Carr2047fae2016-11-28 14:09:09 -08002825 });
Marissa Wall06255332019-03-27 13:48:27 -07002826 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002827 }
2828
2829 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002830 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002831 */
2832
Mathias Agopiane57f2922012-08-09 16:29:12 -07002833 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002834 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002835 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002837
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002838 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002839 // The transform hint might have changed for some layers
2840 // (either because a display has changed, or because a layer
2841 // as changed).
2842 //
2843 // Walk through all the layers in currentLayers,
2844 // and update their transform hint.
2845 //
2846 // If a layer is visible only on a single display, then that
2847 // display is used to calculate the hint, otherwise we use the
2848 // default display.
2849 //
2850 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2851 // the hint is set before we acquire a buffer from the surface texture.
2852 //
2853 // NOTE: layer transactions have taken place already, so we use their
2854 // drawing state. However, SurfaceFlinger's own transaction has not
2855 // happened yet, so we must use the current state layer list
2856 // (soon to become the drawing state list).
2857 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002859 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002860 bool first = true;
2861 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002862 // NOTE: we rely on the fact that layers are sorted by
2863 // layerStack first (so we don't have to traverse the list
2864 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002865 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002866 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002867 currentlayerStack = layerStack;
2868 // figure out if this layerstack is mirrored
2869 // (more than one display) if so, pick the default display,
2870 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002871 hintDisplay = nullptr;
2872 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002873 if (display->getCompositionDisplay()
2874 ->belongsInOutput(layer->getLayerStack(),
2875 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002876 if (hintDisplay) {
2877 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002878 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002879 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002880 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002881 }
2882 }
2883 }
2884 }
Chet Haase91d25932013-04-11 15:24:55 -07002885
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002886 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002887 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2888 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002889
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002890 // could be null when this layer is using a layerStack
2891 // that is not visible on any display. Also can occur at
2892 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002894 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002895
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002896 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002897 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002898 if (hintDisplay) {
2899 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002900 }
Robert Carr2047fae2016-11-28 14:09:09 -08002901
2902 first = false;
2903 });
Mathias Agopian84300952012-11-21 16:02:13 -08002904 }
2905
2906
Mathias Agopian3559b072012-08-15 13:46:03 -07002907 /*
2908 * Perform our own transaction if needed
2909 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910
2911 if (mLayersAdded) {
2912 mLayersAdded = false;
2913 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002914 mVisibleRegionsDirty = true;
2915 }
2916
2917 // some layers might have been removed, so
2918 // we need to update the regions they're exposing.
2919 if (mLayersRemoved) {
2920 mLayersRemoved = false;
2921 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002922 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002923 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002924 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002925 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002926 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002927 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002928 }
Robert Carr2047fae2016-11-28 14:09:09 -08002929 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930 }
2931
Vishnu Nairec0ab382019-02-13 15:32:56 -08002932 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002934}
2935
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002936void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002937 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002938 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002939 return;
2940 }
2941
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002942 if (mVisibleRegionsDirty || mInputInfoChanged) {
2943 mInputInfoChanged = false;
2944 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002945 } else if (mInputWindowCommands.syncInputWindows) {
2946 // If the caller requested to sync input windows, but there are no
2947 // changes to input windows, notify immediately.
2948 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002949 }
2950
2951 executeInputWindowCommands();
2952}
2953
2954void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002955 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002956
2957 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2958 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002959 // When calculating the screen bounds we ignore the transparent region since it may
2960 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002961 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002962 }
2963 });
chaviw291d88a2019-02-14 10:33:58 -08002964
2965 mInputFlinger->setInputWindows(inputHandles,
2966 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2967 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002968}
2969
Vishnu Nairec0ab382019-02-13 15:32:56 -08002970void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002971 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002972 mPendingInputWindowCommands.clear();
2973}
2974
chaviwfbe5d9c2018-12-26 12:23:37 -08002975void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002976 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2977 if (transferTouchFocusCommand.fromToken != nullptr &&
2978 transferTouchFocusCommand.toToken != nullptr &&
2979 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2980 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2981 transferTouchFocusCommand.toToken);
2982 }
2983 }
2984
2985 mInputWindowCommands.clear();
2986}
2987
Riley Andrews03414a12014-07-01 14:22:59 -07002988void SurfaceFlinger::updateCursorAsync()
2989{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002990 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002991 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002992 continue;
2993 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002995 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2996 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002997 }
2998 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002999}
3000
chaviw61626f22018-11-15 16:26:27 -08003001void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3002 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003003 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003004 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003005 }
3006 layer->releasePendingBuffer(systemTime());
3007}
3008
Mathias Agopian4fec8732012-06-29 14:12:52 -07003009void SurfaceFlinger::commitTransaction()
3010{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003011 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003013 for (const auto& l : mLayersPendingRemoval) {
3014 recordBufferingStats(l->getName().string(),
3015 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003016
Lloyd Pique07e33212018-12-18 16:33:37 -08003017 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003018 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003019 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003020 }
chaviw74d90ad2019-04-26 14:45:26 -07003021
3022 // If the layer has been removed and has no parent, then it will not be reachable
3023 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3024 // ensure we can copy its current to drawing state.
3025 if (!l->getParent()) {
3026 mOffscreenLayers.emplace(l.get());
3027 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 }
3029 mLayersPendingRemoval.clear();
3030 }
3031
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003032 // If this transaction is part of a window animation then the next frame
3033 // we composite should be considered an animation as well.
3034 mAnimCompositionPending = mAnimTransactionPending;
3035
Nataniel Borges2b796da2019-02-15 13:32:18 -08003036 withTracingLock([&]() {
3037 mDrawingState = mCurrentState;
3038 // clear the "changed" flags in current state
3039 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003040
chaviw74d90ad2019-04-26 14:45:26 -07003041 mDrawingState.traverseInZOrder([&](Layer* layer) {
3042 layer->commitChildList();
3043
3044 // If the layer can be reached when traversing mDrawingState, then the layer is no
3045 // longer offscreen. Remove the layer from the offscreenLayer set.
3046 if (mOffscreenLayers.count(layer)) {
3047 mOffscreenLayers.erase(layer);
3048 }
3049 });
3050
3051 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003052 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003053
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003054 mTransactionPending = false;
3055 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003056 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057}
3058
Nataniel Borges2b796da2019-02-15 13:32:18 -08003059void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3060 if (mTracingEnabledChanged) {
3061 mTracingEnabled = mTracing.isEnabled();
3062 mTracingEnabledChanged = false;
3063 }
3064
3065 // Synchronize with Tracing thread
3066 std::unique_lock<std::mutex> lock;
3067 if (mTracingEnabled) {
3068 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3069 }
3070
3071 lockedOperation();
3072
3073 // Synchronize with Tracing thread
3074 if (mTracingEnabled) {
3075 lock.unlock();
3076 }
3077}
3078
chaviw74d90ad2019-04-26 14:45:26 -07003079void SurfaceFlinger::commitOffscreenLayers() {
3080 for (Layer* offscreenLayer : mOffscreenLayers) {
3081 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3082 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3083 if (!trFlags) return;
3084
3085 layer->doTransaction(0);
3086 layer->commitChildList();
3087 });
3088 }
3089}
3090
Lloyd Pique32cbe282018-10-19 13:09:22 -07003091void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003092 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003093 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003094 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003095
Lloyd Pique32cbe282018-10-19 13:09:22 -07003096 auto display = displayDevice->getCompositionDisplay();
3097
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098 Region aboveOpaqueLayers;
3099 Region aboveCoveredLayers;
3100 Region dirty;
3101
Mathias Agopian87baae12012-07-31 12:38:26 -07003102 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003103
Robert Carr2047fae2016-11-28 14:09:09 -08003104 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003105 // start with the whole surface at its current location
3106 const Layer::State& s(layer->getDrawingState());
3107
Jesse Hall01e29052013-02-19 16:13:35 -08003108 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003109 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003110 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003111 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003112
Mathias Agopianab028732010-03-16 16:41:46 -07003113 /*
3114 * opaqueRegion: area of a surface that is fully opaque.
3115 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003116 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003117
3118 /*
3119 * visibleRegion: area of a surface that is visible on screen
3120 * and not fully transparent. This is essentially the layer's
3121 * footprint minus the opaque regions above it.
3122 * Areas covered by a translucent surface are considered visible.
3123 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003124 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003125
3126 /*
3127 * coveredRegion: area of a surface that is covered by all
3128 * visible regions above it (which includes the translucent areas).
3129 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003130 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003131
Jesse Halla8026d22012-09-25 13:25:04 -07003132 /*
3133 * transparentRegion: area of a surface that is hinted to be completely
3134 * transparent. This is only used to tell when the layer has no visible
3135 * non-transparent regions and can be removed from the layer list. It
3136 * does not affect the visibleRegion of this layer or any layers
3137 * beneath it. The hint may not be correct if apps don't respect the
3138 * SurfaceView restrictions (which, sadly, some don't).
3139 */
3140 Region transparentRegion;
3141
Mathias Agopianab028732010-03-16 16:41:46 -07003142
3143 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003144 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003145 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003146 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003149 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003150 if (!visibleRegion.isEmpty()) {
3151 // Remove the transparent area from the visible region
3152 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003153 if (tr.preserveRects()) {
3154 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003155 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003156 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003157 // transformation too complex, can't do the
3158 // transparent region optimization.
3159 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003160 }
Mathias Agopianab028732010-03-16 16:41:46 -07003161 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162
Mathias Agopianab028732010-03-16 16:41:46 -07003163 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003164 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003165 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003166 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003167 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003168 // the opaque region is the layer's footprint
3169 opaqueRegion = visibleRegion;
3170 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 }
3172 }
3173
Robert Carre5f4f692018-01-12 13:12:28 -08003174 if (visibleRegion.isEmpty()) {
3175 layer->clearVisibilityRegions();
3176 return;
3177 }
3178
Mathias Agopianab028732010-03-16 16:41:46 -07003179 // Clip the covered region to the visible region
3180 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3181
3182 // Update aboveCoveredLayers for next (lower) layer
3183 aboveCoveredLayers.orSelf(visibleRegion);
3184
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 // subtract the opaque region covered by the layers above us
3186 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187
3188 // compute this layer's dirty region
3189 if (layer->contentDirty) {
3190 // we need to invalidate the whole region
3191 dirty = visibleRegion;
3192 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003193 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194 layer->contentDirty = false;
3195 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003196 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003197 * the exposed region consists of two components:
3198 * 1) what's VISIBLE now and was COVERED before
3199 * 2) what's EXPOSED now less what was EXPOSED before
3200 *
3201 * note that (1) is conservative, we start with the whole
3202 * visible region but only keep what used to be covered by
3203 * something -- which mean it may have been exposed.
3204 *
3205 * (2) handles areas that were not covered by anything but got
3206 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003207 */
Mathias Agopianab028732010-03-16 16:41:46 -07003208 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003209 const Region oldVisibleRegion = layer->visibleRegion;
3210 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003211 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3212 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 }
3214 dirty.subtractSelf(aboveOpaqueLayers);
3215
3216 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003217 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218
Mathias Agopianab028732010-03-16 16:41:46 -07003219 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003221
Jesse Halla8026d22012-09-25 13:25:04 -07003222 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223 layer->setVisibleRegion(visibleRegion);
3224 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003225 layer->setVisibleNonTransparentRegion(
3226 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003227 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228
Mathias Agopian87baae12012-07-31 12:38:26 -07003229 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230}
3231
Chia-I Wuab0c3192017-08-01 11:29:00 -07003232void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003233 for (const auto& [token, displayDevice] : mDisplays) {
3234 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003235 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003236 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003237 }
3238 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003239}
3240
Dan Stoza6b9454d2014-11-07 16:00:59 -08003241bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003242{
Ady Abraham09bd3922019-04-08 10:44:56 -07003243 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003244 ALOGV("handlePageFlip");
3245
Brian Andersond6927fb2016-07-23 23:37:30 -07003246 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247
Mathias Agopian4fec8732012-06-29 14:12:52 -07003248 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003249 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003250 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003251
3252 // Store the set of layers that need updates. This set must not change as
3253 // buffers are being latched, as this could result in a deadlock.
3254 // Example: Two producers share the same command stream and:
3255 // 1.) Layer 0 is latched
3256 // 2.) Layer 0 gets a new frame
3257 // 2.) Layer 1 gets a new frame
3258 // 3.) Layer 1 is latched.
3259 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3260 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003261 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003262 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003263 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003264 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003265 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003266 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003267 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003268 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003269 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003270 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003271 } else {
3272 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003273 }
Robert Carr2047fae2016-11-28 14:09:09 -08003274 });
3275
Lloyd Piquef2c79392018-12-20 16:23:33 -08003276 if (!mLayersWithQueuedFrames.empty()) {
3277 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3278 // writes to Layer current state. See also b/119481871
3279 Mutex::Autolock lock(mStateLock);
3280
3281 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003282 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003283 mLayersPendingRefresh.push_back(layer);
3284 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003285 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003286 if (layer->isBufferLatched()) {
3287 newDataLatched = true;
3288 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003289 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003290 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003291
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003292 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003293
3294 // If we will need to wake up at some time in the future to deal with a
3295 // queued frame that shouldn't be displayed during this vsync period, wake
3296 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003297 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003298 signalLayerUpdate();
3299 }
3300
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003301 // enter boot animation on first buffer latch
3302 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3303 ALOGI("Enter boot animation");
3304 mBootStage = BootStage::BOOTANIMATION;
3305 }
3306
Dan Stoza6b9454d2014-11-07 16:00:59 -08003307 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003308 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309}
3310
Mathias Agopianad456f92011-01-13 17:53:01 -08003311void SurfaceFlinger::invalidateHwcGeometry()
3312{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003313 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003314}
3315
Lloyd Pique32cbe282018-10-19 13:09:22 -07003316void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003317 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003318 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003319 // We only need to actually compose the display if:
3320 // 1) It is being handled by hardware composer, which may need this to
3321 // keep its virtual display state machine in sync, or
3322 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003323 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003324 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003325 return;
3326 }
3327
Dan Stoza9e56aa02015-11-02 13:00:03 -08003328 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003329 base::unique_fd readyFence;
3330 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003331
3332 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003333 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003334}
3335
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003336bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3337 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003338 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003339 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003340
Lloyd Pique32cbe282018-10-19 13:09:22 -07003341 auto display = displayDevice->getCompositionDisplay();
3342 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003343 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003344 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003345 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003346
3347 const Region bounds(displayState.bounds);
3348 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003349 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003350 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003351
Chia-I Wu8e50e692018-05-04 10:12:37 -07003352 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003353
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003354 renderengine::DisplaySettings clientCompositionDisplay;
3355 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3356 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003357 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003358
Dan Stoza9e56aa02015-11-02 13:00:03 -08003359 if (hasClientComposition) {
3360 ALOGV("hasClientComposition");
3361
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003362 if (displayDevice->isPrimary() && supportProtectedContent) {
3363 bool needsProtected = false;
3364 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3365 // If the layer is a protected layer, mark protected context is needed.
3366 if (layer->isProtected()) {
3367 needsProtected = true;
3368 break;
3369 }
3370 }
Peiyong Lin52010312019-05-02 14:22:16 -07003371 if (needsProtected != renderEngine.isProtected()) {
3372 renderEngine.useProtectedContext(needsProtected);
3373 }
3374 if (needsProtected != display->getRenderSurface()->isProtected() &&
3375 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003376 display->getRenderSurface()->setProtected(needsProtected);
3377 }
3378 }
3379
Alec Mouri6338c9d2019-02-07 16:57:51 -08003380 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003381
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003382 if (buf == nullptr) {
3383 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3384 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003385 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003386 return false;
3387 }
3388
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003389 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3390 clientCompositionDisplay.clip = displayState.scissor;
3391 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003392 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003393 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003394
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003395 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003396 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003397 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003398 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003399 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003400 clientCompositionDisplay.outputDataspace = outputDataspace;
3401 clientCompositionDisplay.maxLuminance =
3402 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003403
Lloyd Pique441d5042018-10-18 16:49:51 -07003404 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003405 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003406 getHwComposer()
3407 .hasDisplayCapability(displayId,
3408 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003409
Peiyong Lind3788632018-09-18 16:01:31 -07003410 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003411 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3412 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003413 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003414 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003415 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003416
Mathias Agopian85d751c2012-08-29 16:59:24 -07003417 /*
3418 * and then, render the layers targeted at the framebuffer
3419 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003420
Dan Stoza9e56aa02015-11-02 13:00:03 -08003421 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003423 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003424 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003425 const Region viewportRegion(displayState.viewport);
3426 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003427 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003428 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003429 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003430 switch (layer->getCompositionType(displayDevice)) {
3431 case Hwc2::IComposerClient::Composition::CURSOR:
3432 case Hwc2::IComposerClient::Composition::DEVICE:
3433 case Hwc2::IComposerClient::Composition::SIDEBAND:
3434 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003435 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003436 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003437 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003438 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003439 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003440 // never clear the very first layer since we're
3441 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003442 renderengine::LayerSettings layerSettings;
3443 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003444 bool prepared =
3445 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3446 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003447
3448 if (prepared) {
3449 layerSettings.source.buffer.buffer = nullptr;
3450 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3451 layerSettings.alpha = half(0.0);
3452 layerSettings.disableBlending = true;
3453 clientCompositionLayers.push_back(layerSettings);
3454 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003455 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003456 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003457 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003458 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003459 renderengine::LayerSettings layerSettings;
3460 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003461 layer->prepareClientLayer(renderArea, clip, clearRegion,
3462 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003463 if (prepared) {
3464 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003465 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003466 break;
3467 }
3468 default:
3469 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003470 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003471 } else {
3472 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003473 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003474 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003475 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003476
Alec Mouri820c7402019-01-23 13:02:39 -08003477 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003478 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003479 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003480
3481 // We boost GPU frequency here because there will be color spaces conversion
3482 // and it's expensive. We boost the GPU frequency so that GPU composition can
3483 // finish in time. We must reset GPU frequency afterwards, because high frequency
3484 // consumes extra battery.
3485 const bool expensiveRenderingExpected =
3486 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3487 if (expensiveRenderingExpected && displayId) {
3488 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3489 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003490 if (!debugRegion.isEmpty()) {
3491 Region::const_iterator it = debugRegion.begin();
3492 Region::const_iterator end = debugRegion.end();
3493 while (it != end) {
3494 const Rect& rect = *it++;
3495 renderengine::LayerSettings layerSettings;
3496 layerSettings.source.buffer.buffer = nullptr;
3497 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3498 layerSettings.geometry.boundaries = rect.toFloatRect();
3499 layerSettings.alpha = half(1.0);
3500 clientCompositionLayers.push_back(layerSettings);
3501 }
3502 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003503 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003504 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3505 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003506 } else if (displayId) {
3507 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003508 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003509 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510}
3511
Robert Carrc0df3122019-04-11 13:18:21 -07003512status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3513 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3514 const sp<IBinder>& parentHandle,
3515 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003516 // add this layer to the current state list
3517 {
3518 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003519 sp<Layer> parent;
3520 if (parentHandle != nullptr) {
3521 parent = fromHandle(parentHandle);
3522 if (parent == nullptr) {
3523 return NAME_NOT_FOUND;
3524 }
3525 } else {
3526 parent = parentLayer;
3527 }
3528
Robert Carr1f0a16a2016-10-24 16:27:39 -07003529 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003530 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3531 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003532 return NO_MEMORY;
3533 }
Robert Carrc0df3122019-04-11 13:18:21 -07003534
3535 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3536
Robert Carrb89ea9d2018-12-10 13:01:14 -08003537 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003538 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003539 } else if (parent == nullptr) {
3540 lbc->onRemovedFromCurrentState();
3541 } else if (parent->isRemovedFromCurrentState()) {
3542 parent->addChild(lbc);
3543 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003544 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003545 parent->addChild(lbc);
3546 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003547
Yiwei Zhang243b3782018-05-15 17:40:04 -07003548 if (gbc != nullptr) {
3549 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3550 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3551 mMaxGraphicBufferProducerListSize,
3552 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3553 mGraphicBufferProducerList.size(),
3554 mMaxGraphicBufferProducerListSize, mNumLayers);
3555 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003556 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003557 }
3558
Mathias Agopian96f08192010-06-02 23:28:45 -07003559 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003560 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003561
Dan Stoza7d89d062015-04-30 13:29:25 -07003562 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003563}
3564
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003565uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003566 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003567}
3568
Mathias Agopian3f844832013-08-07 21:24:32 -07003569uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003570 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571}
3572
Mathias Agopian3f844832013-08-07 21:24:32 -07003573uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003574 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003575}
3576
3577uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003578 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003579 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003580 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003582 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003583 }
3584 return old;
3585}
3586
Marissa Wall713b63f2018-10-17 15:42:43 -07003587bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003588 // to prevent onHandleDestroyed from being called while the lock is held,
3589 // we must keep a copy of the transactions (specifically the composer
3590 // states) around outside the scope of the lock
3591 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003592 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003593 {
3594 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003595
Valerie Haufce31b82019-04-30 16:41:14 -07003596 auto it = mTransactionQueues.begin();
3597 while (it != mTransactionQueues.end()) {
3598 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003599
Valerie Haufce31b82019-04-30 16:41:14 -07003600 while (!transactionQueue.empty()) {
3601 const auto& transaction = transactionQueue.front();
3602 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3603 transaction.states)) {
3604 setTransactionFlags(eTransactionFlushNeeded);
3605 break;
3606 }
3607 transactions.push_back(transaction);
3608 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3609 mPendingInputWindowCommands, transaction.desiredPresentTime,
3610 transaction.buffer, transaction.callback,
3611 transaction.postTime, transaction.privileged,
3612 /*isMainThread*/ true);
3613 transactionQueue.pop();
3614 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003615 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003616
Valerie Haufce31b82019-04-30 16:41:14 -07003617 if (transactionQueue.empty()) {
3618 it = mTransactionQueues.erase(it);
3619 mTransactionCV.broadcast();
3620 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003621 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003622 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003623 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003624 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003625 return flushedATransaction;
3626}
3627
3628bool SurfaceFlinger::transactionFlushNeeded() {
3629 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003630}
3631
chaviwca27f252018-02-06 16:46:39 -08003632bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3633 for (const ComposerState& state : states) {
3634 // Here we need to check that the interface we're given is indeed
3635 // one of our own. A malicious client could give us a nullptr
3636 // IInterface, or one of its own or even one of our own but a
3637 // different type. All these situations would cause us to crash.
3638 if (state.client == nullptr) {
3639 return true;
3640 }
3641
3642 sp<IBinder> binder = IInterface::asBinder(state.client);
3643 if (binder == nullptr) {
3644 return true;
3645 }
3646
3647 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3648 return true;
3649 }
3650 }
3651 return false;
3652}
3653
Marissa Wall17b4e452018-12-26 16:32:34 -08003654bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3655 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003656 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003657 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3658 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3659 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3660 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3661 return false;
3662 }
3663
Marissa Wall713b63f2018-10-17 15:42:43 -07003664 for (const ComposerState& state : states) {
3665 const layer_state_t& s = state.state;
3666 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3667 continue;
3668 }
3669 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003670 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003671 }
3672 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003673 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003674}
3675
3676void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3677 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003678 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003679 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003680 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003681 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003682 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003683 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003684
Valerie Haubc6ddb12019-03-08 11:10:15 -08003685 const int64_t postTime = systemTime();
3686
Robert Carr14167e02019-02-13 13:50:55 -08003687 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3688
Mathias Agopian698c0872011-06-28 19:09:31 -07003689 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003690
chaviwca27f252018-02-06 16:46:39 -08003691 if (containsAnyInvalidClientState(states)) {
3692 return;
3693 }
3694
Marissa Wall713b63f2018-10-17 15:42:43 -07003695 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003696 auto itr = mTransactionQueues.find(applyToken);
3697 // if this is an animation frame, wait until prior animation frame has
3698 // been applied by SF
3699 if (flags & eAnimation) {
3700 while (itr != mTransactionQueues.end()) {
3701 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3702 if (CC_UNLIKELY(err != NO_ERROR)) {
3703 ALOGW_IF(err == TIMED_OUT,
3704 "setTransactionState timed out "
3705 "waiting for animation frame to apply");
3706 break;
3707 }
3708 itr = mTransactionQueues.find(applyToken);
3709 }
3710 }
3711 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003712 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003713 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003714 uncacheBuffer, listenerCallbacks, postTime,
3715 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003716 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003717 return;
3718 }
3719
Valerie Haubc6ddb12019-03-08 11:10:15 -08003720 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003721 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003722}
3723
3724void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003725 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003726 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003727 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003728 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003729 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003730 const int64_t postTime, bool privileged,
3731 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003732 uint32_t transactionFlags = 0;
3733
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003734 if (flags & eAnimation) {
3735 // For window updates that are part of an animation we must wait for
3736 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003737 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003738 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003739 if (CC_UNLIKELY(err != NO_ERROR)) {
3740 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003741 // caller after a few seconds.
3742 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3743 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003744 mAnimTransactionPending = false;
3745 break;
3746 }
3747 }
3748 }
3749
chaviwca27f252018-02-06 16:46:39 -08003750 for (const DisplayState& display : displays) {
3751 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003752 }
3753
Marissa Walld600d572019-03-26 15:38:50 -07003754 // In case the client has sent a Transaction that should receive callbacks but without any
3755 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3756 // to the callback thread so it can send an empty callback
3757 if (!listenerCallbacks.empty()) {
3758 mTransactionCompletedThread.run();
3759 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003760 for (const auto& listenerCallback : listenerCallbacks) {
3761 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003762 }
3763
Marissa Walle2ffb422018-10-12 11:33:52 -07003764 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003765 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003766 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3767 postTime, privileged);
3768 }
3769
Marissa Wallefb71af2019-06-27 14:45:53 -07003770 for (const auto& listenerCallback : listenerCallbacks) {
3771 mTransactionCompletedThread.endRegistration(listenerCallback);
3772 }
3773
Marissa Walle2ffb422018-10-12 11:33:52 -07003774 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003775 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003776 mTransactionCompletedThread.sendCallbacks();
3777 }
3778 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003779
chaviw273171b2018-12-26 11:46:30 -08003780 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3781
Marissa Wall947d34e2019-03-29 14:03:53 -07003782 if (uncacheBuffer.isValid()) {
3783 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003784 }
3785
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003786 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3787 // anyway. This can be used as a flush mechanism for previous async transactions.
3788 // Empty animation transaction can be used to simulate back-pressure, so also force a
3789 // transaction for empty animation transactions.
3790 if (transactionFlags == 0 &&
3791 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003792 transactionFlags = eTransactionNeeded;
3793 }
3794
Marissa Wall06255332019-03-27 13:48:27 -07003795 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3796 // so we don't have to wake up again next frame to preform an uneeded traversal.
3797 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3798 transactionFlags = transactionFlags & (~eTraversalNeeded);
3799 mTraversalNeededMainThread = true;
3800 }
3801
Mathias Agopian386aa982011-11-07 21:58:03 -08003802 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003803 if (mInterceptor->isEnabled()) {
3804 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003805 }
Irvel468051e2016-06-13 16:44:44 -07003806
Mathias Agopian386aa982011-11-07 21:58:03 -08003807 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003808 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3809 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003810 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003811
3812 // if this is a synchronous transaction, wait for it to take effect
3813 // before returning.
3814 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003815 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003816 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003817 if (flags & eAnimation) {
3818 mAnimTransactionPending = true;
3819 }
chaviw4fe36852019-04-15 16:25:49 -07003820 if (mPendingInputWindowCommands.syncInputWindows) {
3821 mPendingSyncInputWindows = true;
3822 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003823
3824 // applyTransactionState can be called by either the main SF thread or by
3825 // another process through setTransactionState. While a given process may wish
3826 // to wait on synchronous transactions, the main SF thread should never
3827 // be blocked. Therefore, we only wait if isMainThread is false.
3828 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003829 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3830 if (CC_UNLIKELY(err != NO_ERROR)) {
3831 // just in case something goes wrong in SF, return to the
3832 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003833 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3834 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003835 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003836 break;
3837 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003838 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003839 }
3840}
3841
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003842uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3843 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3844 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003845
Mathias Agopiane57f2922012-08-09 16:29:12 -07003846 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003847 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3848
3849 const uint32_t what = s.what;
3850 if (what & DisplayState::eSurfaceChanged) {
3851 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3852 state.surface = s.surface;
3853 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003854 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003855 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003856 if (what & DisplayState::eLayerStackChanged) {
3857 if (state.layerStack != s.layerStack) {
3858 state.layerStack = s.layerStack;
3859 flags |= eDisplayTransactionNeeded;
3860 }
3861 }
3862 if (what & DisplayState::eDisplayProjectionChanged) {
3863 if (state.orientation != s.orientation) {
3864 state.orientation = s.orientation;
3865 flags |= eDisplayTransactionNeeded;
3866 }
3867 if (state.frame != s.frame) {
3868 state.frame = s.frame;
3869 flags |= eDisplayTransactionNeeded;
3870 }
3871 if (state.viewport != s.viewport) {
3872 state.viewport = s.viewport;
3873 flags |= eDisplayTransactionNeeded;
3874 }
3875 }
3876 if (what & DisplayState::eDisplaySizeChanged) {
3877 if (state.width != s.width) {
3878 state.width = s.width;
3879 flags |= eDisplayTransactionNeeded;
3880 }
3881 if (state.height != s.height) {
3882 state.height = s.height;
3883 flags |= eDisplayTransactionNeeded;
3884 }
3885 }
3886
Mathias Agopiane57f2922012-08-09 16:29:12 -07003887 return flags;
3888}
3889
Robert Carr14167e02019-02-13 13:50:55 -08003890bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003891 IPCThreadState* ipc = IPCThreadState::self();
3892 const int pid = ipc->getCallingPid();
3893 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003894 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003895 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003896 return false;
3897 }
3898 return true;
3899}
3900
Marissa Wall3dad52d2019-03-22 14:03:19 -07003901uint32_t SurfaceFlinger::setClientStateLocked(
3902 const ComposerState& composerState, int64_t desiredPresentTime,
3903 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3904 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003905 const layer_state_t& s = composerState.state;
3906 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3907
Mathias Agopian13127d82013-03-05 17:47:11 -08003908 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003909 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003910 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003911 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003912 new CallbackHandle(listenerCallback.transactionCompletedListener,
3913 listenerCallback.callbackIds, s.surface));
3914 }
chaviw8b3871a2017-11-01 17:41:01 -07003915 return 0;
3916 }
3917
chaviw8b3871a2017-11-01 17:41:01 -07003918 uint32_t flags = 0;
3919
Garfield Tan8a3083e2018-12-03 13:21:07 -08003920 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003921 bool geometryAppliesWithResize =
3922 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003923
3924 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3925 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003926 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003927 layer->pushPendingState();
3928 }
3929
chaviw8b3871a2017-11-01 17:41:01 -07003930 if (what & layer_state_t::ePositionChanged) {
3931 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3932 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003933 }
chaviw8b3871a2017-11-01 17:41:01 -07003934 }
3935 if (what & layer_state_t::eLayerChanged) {
3936 // NOTE: index needs to be calculated before we update the state
3937 const auto& p = layer->getParent();
3938 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003939 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003940 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003941 mCurrentState.layersSortedByZ.removeAt(idx);
3942 mCurrentState.layersSortedByZ.add(layer);
3943 // we need traversal (state changed)
3944 // AND transaction (list changed)
3945 flags |= eTransactionNeeded|eTraversalNeeded;
3946 }
chaviw8b3871a2017-11-01 17:41:01 -07003947 } else {
3948 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003949 flags |= eTransactionNeeded|eTraversalNeeded;
3950 }
3951 }
chaviw8b3871a2017-11-01 17:41:01 -07003952 }
3953 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003954 // NOTE: index needs to be calculated before we update the state
3955 const auto& p = layer->getParent();
3956 if (p == nullptr) {
3957 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3958 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3959 mCurrentState.layersSortedByZ.removeAt(idx);
3960 mCurrentState.layersSortedByZ.add(layer);
3961 // we need traversal (state changed)
3962 // AND transaction (list changed)
3963 flags |= eTransactionNeeded|eTraversalNeeded;
3964 }
3965 } else {
3966 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3967 flags |= eTransactionNeeded|eTraversalNeeded;
3968 }
chaviw8b3871a2017-11-01 17:41:01 -07003969 }
3970 }
3971 if (what & layer_state_t::eSizeChanged) {
3972 if (layer->setSize(s.w, s.h)) {
3973 flags |= eTraversalNeeded;
3974 }
3975 }
3976 if (what & layer_state_t::eAlphaChanged) {
3977 if (layer->setAlpha(s.alpha))
3978 flags |= eTraversalNeeded;
3979 }
3980 if (what & layer_state_t::eColorChanged) {
3981 if (layer->setColor(s.color))
3982 flags |= eTraversalNeeded;
3983 }
Peiyong Lind3788632018-09-18 16:01:31 -07003984 if (what & layer_state_t::eColorTransformChanged) {
3985 if (layer->setColorTransform(s.colorTransform)) {
3986 flags |= eTraversalNeeded;
3987 }
3988 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003989 if (what & layer_state_t::eBackgroundColorChanged) {
3990 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3991 flags |= eTraversalNeeded;
3992 }
3993 }
chaviw8b3871a2017-11-01 17:41:01 -07003994 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003995 // TODO: b/109894387
3996 //
3997 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3998 // rotation. To see the problem observe that if we have a square parent, and a child
3999 // of the same size, then we rotate the child 45 degrees around it's center, the child
4000 // must now be cropped to a non rectangular 8 sided region.
4001 //
4002 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4003 // private API, and the WindowManager only uses rotation in one case, which is on a top
4004 // level layer in which cropping is not an issue.
4005 //
4006 // However given that abuse of rotation matrices could lead to surfaces extending outside
4007 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4008 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4009 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004010 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004011 flags |= eTraversalNeeded;
4012 }
4013 if (what & layer_state_t::eTransparentRegionChanged) {
4014 if (layer->setTransparentRegionHint(s.transparentRegion))
4015 flags |= eTraversalNeeded;
4016 }
4017 if (what & layer_state_t::eFlagsChanged) {
4018 if (layer->setFlags(s.flags, s.mask))
4019 flags |= eTraversalNeeded;
4020 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004021 if (what & layer_state_t::eCropChanged_legacy) {
4022 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004023 flags |= eTraversalNeeded;
4024 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004025 if (what & layer_state_t::eCornerRadiusChanged) {
4026 if (layer->setCornerRadius(s.cornerRadius))
4027 flags |= eTraversalNeeded;
4028 }
chaviw8b3871a2017-11-01 17:41:01 -07004029 if (what & layer_state_t::eLayerStackChanged) {
4030 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4031 // We only allow setting layer stacks for top level layers,
4032 // everything else inherits layer stack from its parent.
4033 if (layer->hasParent()) {
4034 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4035 layer->getName().string());
4036 } else if (idx < 0) {
4037 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4038 "that also does not appear in the top level layer list. Something"
4039 " has gone wrong.", layer->getName().string());
4040 } else if (layer->setLayerStack(s.layerStack)) {
4041 mCurrentState.layersSortedByZ.removeAt(idx);
4042 mCurrentState.layersSortedByZ.add(layer);
4043 // we need traversal (state changed)
4044 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004045 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004046 }
4047 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004048 if (what & layer_state_t::eDeferTransaction_legacy) {
4049 if (s.barrierHandle_legacy != nullptr) {
4050 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4051 } else if (s.barrierGbp_legacy != nullptr) {
4052 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004053 if (authenticateSurfaceTextureLocked(gbp)) {
4054 const auto& otherLayer =
4055 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004056 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004057 } else {
4058 ALOGE("Attempt to defer transaction to to an"
4059 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004060 }
4061 }
chaviw8b3871a2017-11-01 17:41:01 -07004062 // We don't trigger a traversal here because if no other state is
4063 // changed, we don't want this to cause any more work
4064 }
4065 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004066 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004067 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004068 if (!hadParent) {
4069 mCurrentState.layersSortedByZ.remove(layer);
4070 }
chaviw8b3871a2017-11-01 17:41:01 -07004071 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004072 }
chaviw8b3871a2017-11-01 17:41:01 -07004073 }
4074 if (what & layer_state_t::eReparentChildren) {
4075 if (layer->reparentChildren(s.reparentHandle)) {
4076 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004077 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004078 }
chaviw8b3871a2017-11-01 17:41:01 -07004079 if (what & layer_state_t::eDetachChildren) {
4080 layer->detachChildren();
4081 }
4082 if (what & layer_state_t::eOverrideScalingModeChanged) {
4083 layer->setOverrideScalingMode(s.overrideScalingMode);
4084 // We don't trigger a traversal here because if no other state is
4085 // changed, we don't want this to cause any more work
4086 }
Marissa Wall61c58622018-07-18 10:12:20 -07004087 if (what & layer_state_t::eTransformChanged) {
4088 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4089 }
4090 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4091 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4092 flags |= eTraversalNeeded;
4093 }
4094 if (what & layer_state_t::eCropChanged) {
4095 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4096 }
Marissa Wall861616d2018-10-22 12:52:23 -07004097 if (what & layer_state_t::eFrameChanged) {
4098 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4099 }
Marissa Wall61c58622018-07-18 10:12:20 -07004100 if (what & layer_state_t::eAcquireFenceChanged) {
4101 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4102 }
4103 if (what & layer_state_t::eDataspaceChanged) {
4104 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4105 }
4106 if (what & layer_state_t::eHdrMetadataChanged) {
4107 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4108 }
4109 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4110 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4111 }
4112 if (what & layer_state_t::eApiChanged) {
4113 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4114 }
4115 if (what & layer_state_t::eSidebandStreamChanged) {
4116 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4117 }
Robert Carr720e5062018-07-30 17:45:14 -07004118 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004119 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004120 layer->setInputInfo(s.inputInfo);
4121 flags |= eTraversalNeeded;
4122 } else {
4123 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4124 }
Robert Carr720e5062018-07-30 17:45:14 -07004125 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004126 if (what & layer_state_t::eMetadataChanged) {
4127 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4128 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004129 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4130 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4131 flags |= eTraversalNeeded;
4132 }
4133 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004134 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004135 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004136 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004137 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4138 }
4139 }
Marissa Wall78b72202019-03-15 14:58:34 -07004140 bool bufferChanged = what & layer_state_t::eBufferChanged;
4141 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4142 sp<GraphicBuffer> buffer;
4143 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004144 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri1c8d7202019-06-01 18:51:35 -07004145 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4146 wp<ClientCache::ErasedRecipient>(layer));
4147 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004148 buffer = s.buffer;
4149 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004150 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004151 } else if (bufferChanged) {
4152 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004153 }
Marissa Wall78b72202019-03-15 14:58:34 -07004154 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004155 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004156 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004157 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004158 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004159 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4160 // Do not put anything that updates layer state or modifies flags after
4161 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004162 return flags;
4163}
4164
chaviw273171b2018-12-26 11:46:30 -08004165uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4166 uint32_t flags = 0;
4167 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4168 flags |= eTraversalNeeded;
4169 }
4170
chaviwa911b102019-02-14 10:18:33 -08004171 if (inputWindowCommands.syncInputWindows) {
4172 flags |= eTraversalNeeded;
4173 }
4174
Vishnu Nairec0ab382019-02-13 15:32:56 -08004175 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004176 return flags;
4177}
4178
Marissa Wall2d814fb2019-04-09 18:52:57 +00004179status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4180 uint32_t h, PixelFormat format, uint32_t flags,
4181 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004182 sp<IGraphicBufferProducer>* gbp,
4183 const sp<IBinder>& parentHandle,
4184 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004185 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004186 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004187 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004188 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004189 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004190
Robert Carrc0df3122019-04-11 13:18:21 -07004191 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4192 "Expected only one of parentLayer or parentHandle to be non-null. "
4193 "Programmer error?");
4194
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004195 status_t result = NO_ERROR;
4196
4197 sp<Layer> layer;
4198
Cody Northropbc755282017-03-31 12:00:08 -06004199 String8 uniqueName = getUniqueLayerName(name);
4200
Evan Roskya1f1e152019-01-24 16:17:46 -08004201 bool primaryDisplayOnly = false;
4202
4203 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4204 // TODO b/64227542
4205 if (metadata.has(METADATA_WINDOW_TYPE)) {
4206 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4207 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004208 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004209 primaryDisplayOnly = true;
4210 }
4211 }
4212
Mathias Agopian3165cc22012-08-08 19:42:09 -07004213 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004214 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004215 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4216 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004217
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004218 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004219 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004220 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4221 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004222 break;
chaviw13fdc492017-06-27 12:40:18 -07004223 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004224 // check if buffer size is set for color layer.
4225 if (w > 0 || h > 0) {
4226 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4227 int(w), int(h));
4228 return BAD_VALUE;
4229 }
4230
Evan Roskya1f1e152019-01-24 16:17:46 -08004231 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4232 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004233 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004234 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004235 // check if buffer size is set for container layer.
4236 if (w > 0 || h > 0) {
4237 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4238 int(w), int(h));
4239 return BAD_VALUE;
4240 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004241 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4242 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004243 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004244 default:
4245 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 break;
4247 }
4248
Dan Stoza7d89d062015-04-30 13:29:25 -07004249 if (result != NO_ERROR) {
4250 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004252
Evan Roskya1f1e152019-01-24 16:17:46 -08004253 if (primaryDisplayOnly) {
4254 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004255 }
4256
Robert Carrb89ea9d2018-12-10 13:01:14 -08004257 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004258 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4259 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004260 if (result != NO_ERROR) {
4261 return result;
4262 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004263 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004264
4265 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004266 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004267}
4268
Cody Northropbc755282017-03-31 12:00:08 -06004269String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4270{
4271 bool matchFound = true;
4272 uint32_t dupeCounter = 0;
4273
4274 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4275 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4276
Dan Stoza436ccf32018-06-21 12:10:12 -07004277 // Grab the state lock since we're accessing mCurrentState
4278 Mutex::Autolock lock(mStateLock);
4279
Cody Northropbc755282017-03-31 12:00:08 -06004280 // Loop over layers until we're sure there is no matching name
4281 while (matchFound) {
4282 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004283 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004284 if (layer->getName() == uniqueName) {
4285 matchFound = true;
4286 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4287 }
4288 });
4289 }
4290
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004291 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4292 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004293
4294 return uniqueName;
4295}
4296
Marissa Wallfd668622018-05-10 10:21:13 -07004297status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4298 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004299 LayerMetadata metadata, PixelFormat& format,
4300 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004301 sp<IGraphicBufferProducer>* gbp,
4302 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004304 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305 case PIXEL_FORMAT_TRANSPARENT:
4306 case PIXEL_FORMAT_TRANSLUCENT:
4307 format = PIXEL_FORMAT_RGBA_8888;
4308 break;
4309 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004310 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004311 break;
4312 }
4313
Evan Roskya1f1e152019-01-24 16:17:46 -08004314 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4315 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004316 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004317 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004318 *handle = layer->getHandle();
4319 *gbp = layer->getProducer();
4320 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004321 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004322
Marissa Wallfd668622018-05-10 10:21:13 -07004323 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004324 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004325}
4326
Marissa Wall61c58622018-07-18 10:12:20 -07004327status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4328 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004329 LayerMetadata metadata, sp<IBinder>* handle,
4330 sp<Layer>* outLayer) {
4331 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4332 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004333 *handle = layer->getHandle();
4334 *outLayer = layer;
4335
4336 return NO_ERROR;
4337}
4338
Evan Roskya1f1e152019-01-24 16:17:46 -08004339status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4340 uint32_t h, uint32_t flags, LayerMetadata metadata,
4341 sp<IBinder>* handle, sp<Layer>* outLayer) {
4342 *outLayer = getFactory().createColorLayer(
4343 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004344 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004345 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004346}
4347
Evan Roskya1f1e152019-01-24 16:17:46 -08004348status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4349 uint32_t w, uint32_t h, uint32_t flags,
4350 LayerMetadata metadata, sp<IBinder>* handle,
4351 sp<Layer>* outLayer) {
4352 *outLayer = getFactory().createContainerLayer(
4353 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004354 *handle = (*outLayer)->getHandle();
4355 return NO_ERROR;
4356}
4357
4358
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004359void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004360 mLayersPendingRemoval.add(layer);
4361 mLayersRemoved = true;
4362 setTransactionFlags(eTransactionNeeded);
4363}
4364
Robert Carr695d5282018-12-18 15:27:58 -08004365void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004366{
Robert Carr2e102c92018-10-23 12:11:15 -07004367 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004368 // If a layer has a parent, we allow it to out-live it's handle
4369 // with the idea that the parent holds a reference and will eventually
4370 // be cleaned up. However no one cleans up the top-level so we do so
4371 // here.
4372 if (layer->getParent() == nullptr) {
4373 mCurrentState.layersSortedByZ.remove(layer);
4374 }
4375 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004376
4377 auto it = mLayersByLocalBinderToken.begin();
4378 while (it != mLayersByLocalBinderToken.end()) {
4379 if (it->second == layer) {
4380 it = mLayersByLocalBinderToken.erase(it);
4381 } else {
4382 it++;
4383 }
4384 }
4385
Robert Carr695d5282018-12-18 15:27:58 -08004386 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004387}
4388
Mathias Agopianb60314a2012-04-10 22:09:54 -07004389// ---------------------------------------------------------------------------
4390
Andy McFadden13a082e2012-08-24 10:16:42 -07004391void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004392 const auto display = getDefaultDisplayDeviceLocked();
4393 if (!display) return;
4394
4395 const sp<IBinder> token = display->getDisplayToken().promote();
4396 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004397
Jesse Hall01e29052013-02-19 16:13:35 -08004398 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004399 Vector<ComposerState> state;
4400 Vector<DisplayState> displays;
4401 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004402 d.what = DisplayState::eDisplayProjectionChanged |
4403 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004404 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004405 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004406 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004407 d.frame.makeInvalid();
4408 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004409 d.width = 0;
4410 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004411 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004412 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004413
Dominik Laskowskie9774092018-12-11 10:04:24 -08004414 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004415
Dominik Laskowski83b88212018-12-11 13:34:06 -08004416 const nsecs_t vsyncPeriod = getVsyncPeriod();
4417 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004418
Brian Andersond0010582017-03-07 13:20:31 -08004419 // Use phase of 0 since phase is not known.
4420 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004421 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004422 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004423}
4424
4425void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004426 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004427 postMessageAsync(
4428 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004429}
4430
Ady Abraham27c70212019-06-11 10:52:26 -07004431void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4432 if (mHWCVsyncState != enabled) {
4433 getHwComposer().setVsyncEnabled(displayId, enabled);
4434 mHWCVsyncState = enabled;
4435 }
4436}
4437
Dominik Laskowskie9774092018-12-11 10:04:24 -08004438void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004439 if (display->isVirtual()) {
4440 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004441 return;
4442 }
4443
Dominik Laskowski075d3172018-05-24 15:50:06 -07004444 const auto displayId = display->getId();
4445 LOG_ALWAYS_FATAL_IF(!displayId);
4446
Dominik Laskowski34157762018-10-31 13:07:19 -07004447 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004448
4449 int currentMode = display->getPowerMode();
4450 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004451 return;
4452 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004454 display->setPowerMode(mode);
4455
Lloyd Pique4dccc412018-01-22 17:21:36 -08004456 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004457 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004458 }
4459
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004460 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004461 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004462 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004463 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004464 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004465 mScheduler->onScreenAcquired(mAppConnectionHandle);
4466 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004467 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004468
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004469 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004470 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004471 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004472
4473 struct sched_param param = {0};
4474 param.sched_priority = 1;
4475 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4476 ALOGW("Couldn't set SCHED_FIFO on display on");
4477 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004478 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004479 // Turn off the display
4480 struct sched_param param = {0};
4481 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4482 ALOGW("Couldn't set SCHED_OTHER on display off");
4483 }
4484
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004486 mScheduler->disableHardwareVsync(true);
4487 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004488 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004489
Ady Abraham27c70212019-06-11 10:52:26 -07004490 // Make sure HWVsync is disabled before turning off the display
4491 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4492
Dominik Laskowski075d3172018-05-24 15:50:06 -07004493 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004494 mVisibleRegionsDirty = true;
4495 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004496 } else if (mode == HWC_POWER_MODE_DOZE ||
4497 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004498 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004499 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004500 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004501 mScheduler->onScreenAcquired(mAppConnectionHandle);
4502 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004503 }
4504 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4505 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004506 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004507 mScheduler->disableHardwareVsync(true);
4508 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004509 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004510 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004511 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004512 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004513 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004514 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004515
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004516 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004517 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004518 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004519 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004520 }
4521
Dominik Laskowski34157762018-10-31 13:07:19 -07004522 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004523}
4524
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004525void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004526 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004527 const auto display = getDisplayDevice(displayToken);
4528 if (!display) {
4529 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4530 displayToken.get());
4531 } else if (display->isVirtual()) {
4532 ALOGW("Attempt to set power mode %d for virtual display", mode);
4533 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004534 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004535 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004536 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004537}
4538
4539// ---------------------------------------------------------------------------
4540
Dominik Laskowskic2867142019-01-21 11:33:38 -08004541status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4542 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004544
Mathias Agopianbd115332013-04-18 16:41:04 -07004545 IPCThreadState* ipc = IPCThreadState::self();
4546 const int pid = ipc->getCallingPid();
4547 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004548
Mathias Agopianbd115332013-04-18 16:41:04 -07004549 if ((uid != AID_SHELL) &&
4550 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4552 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004553 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004554 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004555 // (this would indicate SF is stuck, but we want to be able to
4556 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004557 status_t err = mStateLock.timedLock(s2ns(1));
4558 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004559 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004560 StringAppendF(&result,
4561 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4562 "(no locks held)\n",
4563 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004564 }
4565
Dominik Laskowskic2867142019-01-21 11:33:38 -08004566 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004567
Dominik Laskowskic2867142019-01-21 11:33:38 -08004568 static const std::unordered_map<std::string, Dumper> dumpers = {
4569 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4570 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4571 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004572 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004573 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004574 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004575 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4576 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004577 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4578 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4579 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4580 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4581 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4582 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004583 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004584 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4585 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004586
Dominik Laskowskic2867142019-01-21 11:33:38 -08004587 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004588
Dominik Laskowskic2867142019-01-21 11:33:38 -08004589 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4590 (it->second)(args, asProto, result);
4591 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004592 if (asProto) {
4593 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4594 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4595 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004596 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004597 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004598 }
4599
Mathias Agopian9795c422009-08-26 16:36:26 -07004600 if (locked) {
4601 mStateLock.unlock();
4602 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004605 return NO_ERROR;
4606}
4607
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004608status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4609 if (asProto && mTracing.isEnabled()) {
4610 mTracing.writeToFileAsync();
4611 }
4612
4613 return doDump(fd, DumpArgs(), asProto);
4614}
4615
Dominik Laskowskic2867142019-01-21 11:33:38 -08004616void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004617 mCurrentState.traverseInZOrder(
4618 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004619}
4620
Dominik Laskowskic2867142019-01-21 11:33:38 -08004621void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004622 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004623
Dominik Laskowskic2867142019-01-21 11:33:38 -08004624 if (args.size() > 1) {
4625 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004626 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004627 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004628 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004629 }
Robert Carr2047fae2016-11-28 14:09:09 -08004630 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004631 } else {
4632 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633 }
4634}
4635
Dominik Laskowskic2867142019-01-21 11:33:38 -08004636void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004637 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004638 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004639 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004640 }
Robert Carr2047fae2016-11-28 14:09:09 -08004641 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004642
Svetoslavd85084b2014-03-20 10:28:31 -07004643 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004644}
4645
Dominik Laskowskic2867142019-01-21 11:33:38 -08004646void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4647 mTimeStats->parseArgs(asProto, args, result);
4648}
4649
Jamie Gennis6547ff42013-07-16 20:12:42 -07004650// This should only be called from the main thread. Otherwise it would need
4651// the lock and should use mCurrentState rather than mDrawingState.
4652void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004653 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004654 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004655 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004656
4657 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4658}
4659
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004661 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004662
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004663 if (isLayerTripleBufferingDisabled())
4664 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004665
Yiwei Zhang5434a782018-12-05 18:06:32 -08004666 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4667 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4668 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4669 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4670 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4671 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004672 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004673}
4674
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004675void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004676 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004677 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004678 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004679 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004680
Ady Abraham97d04232019-03-05 19:48:12 -08004681 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004682 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4683 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004684 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham261614e2019-07-10 17:53:12 -07004685 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4686 if (refresh.second && isDisplayConfigAllowed(refresh.second->configId)) {
4687 StringAppendF(&result, "%dHz, ", refresh.second->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004688 }
4689 }
4690 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4691 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004692 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004693}
4694
Yiwei Zhang5434a782018-12-05 18:06:32 -08004695void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4696 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004697 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4698 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004699 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004700 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004701 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004702 }
David Sodman4a36e932017-11-07 14:29:47 -08004703 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004704 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004705 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4707 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004708}
4709
Dan Stozae77c7662016-05-13 11:37:28 -07004710void SurfaceFlinger::recordBufferingStats(const char* layerName,
4711 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004712 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4713 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004714 for (const auto& segment : history) {
4715 if (!segment.usedThirdBuffer) {
4716 stats.twoBufferTime += segment.totalTime;
4717 }
4718 if (segment.occupancyAverage < 1.0f) {
4719 stats.doubleBufferedTime += segment.totalTime;
4720 } else if (segment.occupancyAverage < 2.0f) {
4721 stats.tripleBufferedTime += segment.totalTime;
4722 }
4723 ++stats.numSegments;
4724 stats.totalTime += segment.totalTime;
4725 }
4726}
4727
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4729 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004730
4731 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4732 const size_t count = currentLayers.size();
4733 for (size_t i=0 ; i<count ; i++) {
4734 currentLayers[i]->dumpFrameEvents(result);
4735 }
4736}
4737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004739 result.append("Buffering stats:\n");
4740 result.append(" [Layer name] <Active time> <Two buffer> "
4741 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004742 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004743 typedef std::tuple<std::string, float, float, float> BufferTuple;
4744 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004745 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004746 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004747 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004748 if (stats.numSegments == 0) {
4749 continue;
4750 }
4751 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4752 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4753 stats.totalTime;
4754 float doubleBufferRatio = static_cast<float>(
4755 stats.doubleBufferedTime) / stats.totalTime;
4756 float tripleBufferRatio = static_cast<float>(
4757 stats.tripleBufferedTime) / stats.totalTime;
4758 sorted.insert({activeTime, {name, twoBufferRatio,
4759 doubleBufferRatio, tripleBufferRatio}});
4760 }
4761 for (const auto& sortedPair : sorted) {
4762 float activeTime = sortedPair.first;
4763 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004764 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4765 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004766 }
4767 result.append("\n");
4768}
4769
Yiwei Zhang5434a782018-12-05 18:06:32 -08004770void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004771 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004772 const auto displayId = display->getId();
4773 if (!displayId) {
4774 continue;
4775 }
4776 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004777 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004778 continue;
4779 }
4780
Yiwei Zhang5434a782018-12-05 18:06:32 -08004781 StringAppendF(&result,
4782 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4783 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004784 uint8_t port;
4785 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004786 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004787 result.append("no identification data\n");
4788 continue;
4789 }
4790
4791 if (!isEdid(data)) {
4792 result.append("unknown identification data: ");
4793 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004794 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004795 }
4796 result.append("\n");
4797 continue;
4798 }
4799
4800 const auto edid = parseEdid(data);
4801 if (!edid) {
4802 result.append("invalid EDID: ");
4803 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004805 }
4806 result.append("\n");
4807 continue;
4808 }
4809
Yiwei Zhang5434a782018-12-05 18:06:32 -08004810 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004811 result.append(edid->displayName.data(), edid->displayName.length());
4812 result.append("\"\n");
4813 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004814}
4815
Yiwei Zhang5434a782018-12-05 18:06:32 -08004816void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004817 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004818 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4819 StringAppendF(&result, "DisplayColorSetting: %s\n",
4820 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004821
4822 // TODO: print out if wide-color mode is active or not
4823
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004824 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004825 const auto displayId = display->getId();
4826 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004827 continue;
4828 }
4829
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004831 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004832 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004833 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004834 }
4835
Lloyd Pique32cbe282018-10-19 13:09:22 -07004836 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004837 StringAppendF(&result, " Current color mode: %s (%d)\n",
4838 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004839 }
4840 result.append("\n");
4841}
4842
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004843LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4844 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004845 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004846 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4847 const State& state = useDrawing ? mDrawingState : mCurrentState;
4848 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004849 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004850 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004851 });
4852
4853 return layersProto;
4854}
4855
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004856LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4857 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004858 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004859
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004860 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004861 resolution->set_w(displayDevice->getWidth());
4862 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004863
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004864 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004865 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004866
Lloyd Pique32cbe282018-10-19 13:09:22 -07004867 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4868 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4869 layersProto.set_global_transform(displayState.orientation);
4870
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004871 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004872 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004873 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004874 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004875 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004876 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004877 }
4878 });
4879
4880 return layersProto;
4881}
4882
Dominik Laskowskic2867142019-01-21 11:33:38 -08004883void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4884 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004885 Colorizer colorizer(colorize);
4886
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004887 // figure out if we're stuck somewhere
4888 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004889 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004890 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4891
4892 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004893 * Dump library configuration.
4894 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004895
4896 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004897 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004898 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004899 appendSfConfigString(result);
4900 appendUiConfigString(result);
4901 appendGuiConfigString(result);
4902 result.append("\n");
4903
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004904 result.append("\nDisplay identification data:\n");
4905 dumpDisplayIdentificationData(result);
4906
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004907 result.append("\nWide-Color information:\n");
4908 dumpWideColorInfo(result);
4909
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004910 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004911 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004912 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004913 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004914 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004915
Andy McFadden41d67d72014-04-25 16:58:34 -07004916 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004917 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004918 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004919 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004920 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004921
Dan Stozab90cf072015-03-05 11:05:59 -08004922 dumpStaticScreenStats(result);
4923 result.append("\n");
4924
Alec Mouri40189b02019-03-05 15:07:54 -08004925 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4926 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4927 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004928
Dan Stozae77c7662016-05-13 11:37:28 -07004929 dumpBufferingStats(result);
4930
Andy McFadden4803b742012-09-24 19:07:20 -07004931 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004932 * Dump the visible layer list
4933 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004934 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004935 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4936 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4937 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004938 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004939
Chia-I Wu2f884132018-09-13 15:17:58 -07004940 {
4941 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4942 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004943 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004944 result.append("\n");
4945 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004946
Lloyd Pique207def92019-02-28 16:09:52 -08004947 {
4948 StringAppendF(&result, "Composition layers\n");
4949 mDrawingState.traverseInZOrder([&](Layer* layer) {
4950 auto compositionLayer = layer->getCompositionLayer();
4951 if (compositionLayer) compositionLayer->dump(result);
4952 });
4953 }
4954
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004955 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004956 * Dump Display state
4957 */
4958
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004959 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004960 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004961 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004962 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004963 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004964 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004965 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004966
4967 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004968 * Dump SurfaceFlinger global state
4969 */
4970
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004971 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004972 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004973 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004974
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004975 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004976
Dominik Laskowski075d3172018-05-24 15:50:06 -07004977 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004978 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4979 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004980 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4981 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004982 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004983 StringAppendF(&result,
4984 " transaction-flags : %08x\n"
4985 " gpu_to_cpu_unsupported : %d\n",
4986 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004987
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004988 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004989 displayId && getHwComposer().isConnected(*displayId)) {
4990 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004991 StringAppendF(&result,
4992 " refresh-rate : %f fps\n"
4993 " x-dpi : %f\n"
4994 " y-dpi : %f\n",
4995 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4996 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004997 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004998
Yiwei Zhang5434a782018-12-05 18:06:32 -08004999 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005000
Dan Stozae22aec72016-08-01 13:20:59 -07005001 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005002 * Tracing state
5003 */
5004 mTracing.dump(result);
5005 result.append("\n");
5006
5007 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005008 * HWC layer minidump
5009 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005010 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005011 const auto displayId = display->getId();
5012 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005013 continue;
5014 }
5015
Yiwei Zhang5434a782018-12-05 18:06:32 -08005016 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005017 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005018 const sp<DisplayDevice> displayDevice = display;
5019 mCurrentState.traverseInZOrder(
5020 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005021 result.append("\n");
5022 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005023
5024 /*
5025 * Dump HWComposer state
5026 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005027 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005028 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005029 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005030 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005031 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005032 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005033
5034 /*
5035 * Dump gralloc state
5036 */
5037 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5038 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005039
5040 /*
5041 * Dump VrFlinger state if in use.
5042 */
5043 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5044 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005045 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005046 result.append("\n");
5047 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005048
5049 /**
5050 * Scheduler dump state.
5051 */
Ana Krulecc2870422019-01-29 19:00:58 -08005052 result.append("\nScheduler state:\n");
5053 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005054 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005055 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005056
5057 result.append(mTimeStats->miniDump());
5058 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005059}
5060
Dominik Laskowski075d3172018-05-24 15:50:06 -07005061const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005062 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005063 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005064 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005065 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005066 }
5067 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005068
Dominik Laskowski34157762018-10-31 13:07:19 -07005069 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005070 static const Vector<sp<Layer>> empty;
5071 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005072}
5073
Chia-I Wu28f320b2018-05-03 11:02:56 -07005074void SurfaceFlinger::updateColorMatrixLocked() {
5075 mat4 colorMatrix;
5076 if (mGlobalSaturationFactor != 1.0f) {
5077 // Rec.709 luma coefficients
5078 float3 luminance{0.213f, 0.715f, 0.072f};
5079 luminance *= 1.0f - mGlobalSaturationFactor;
5080 mat4 saturationMatrix = mat4(
5081 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5082 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5083 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5084 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5085 );
5086 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5087 } else {
5088 colorMatrix = mClientColorMatrix * mDaltonizer();
5089 }
5090
5091 if (mCurrentState.colorMatrix != colorMatrix) {
5092 mCurrentState.colorMatrix = colorMatrix;
5093 mCurrentState.colorMatrixChanged = true;
5094 setTransactionFlags(eTransactionNeeded);
5095 }
5096}
5097
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005098status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005099#pragma clang diagnostic push
5100#pragma clang diagnostic error "-Wswitch-enum"
5101 switch (static_cast<ISurfaceComposerTag>(code)) {
5102 // These methods should at minimum make sure that the client requested
5103 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005104 case BOOT_FINISHED:
5105 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005106 case CREATE_DISPLAY:
5107 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005108 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005109 case GET_ANIMATION_FRAME_STATS:
5110 case GET_HDR_CAPABILITIES:
5111 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005112 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005113 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005114 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005115 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005116 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005117 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005118 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005119 case GET_DISPLAYED_CONTENT_SAMPLE:
5120 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005121 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5122 IPCThreadState* ipc = IPCThreadState::self();
5123 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5124 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005125 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005126 }
Robert Carr1db73f62016-12-21 12:58:51 -08005127 return OK;
5128 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005129 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005130 IPCThreadState* ipc = IPCThreadState::self();
5131 const int pid = ipc->getCallingPid();
5132 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005133 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5134 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005135 return PERMISSION_DENIED;
5136 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005137 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005138 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005139 // Used by apps to hook Choreographer to SurfaceFlinger.
5140 case CREATE_DISPLAY_EVENT_CONNECTION:
5141 // The following calls are currently used by clients that do not
5142 // request necessary permissions. However, they do not expose any secret
5143 // information, so it is OK to pass them.
5144 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005145 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005146 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005147 case GET_PHYSICAL_DISPLAY_IDS:
5148 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005149 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005150 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005151 case GET_DISPLAY_CONFIGS:
5152 case GET_DISPLAY_STATS:
5153 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5154 // Calling setTransactionState is safe, because you need to have been
5155 // granted a reference to Client* and Handle* to do anything with it.
5156 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005157 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005158 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005159 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005160 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005161 case IS_WIDE_COLOR_DISPLAY:
5162 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5163 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005164 return OK;
5165 }
Chong Zhangda6c1592019-07-16 13:45:06 -07005166 case CAPTURE_LAYERS: {
5167 IPCThreadState* ipc = IPCThreadState::self();
5168 const int pid = ipc->getCallingPid();
5169 const int uid = ipc->getCallingUid();
5170 // allow media to capture layer for video thumbnails
5171 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
5172 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5173 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
5174 return PERMISSION_DENIED;
5175 }
5176 return OK;
5177 }
Dan Stoza84ab9372018-12-17 15:27:57 -08005178 case CAPTURE_SCREEN:
5179 case ADD_REGION_SAMPLING_LISTENER:
5180 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005181 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005182 IPCThreadState* ipc = IPCThreadState::self();
5183 const int pid = ipc->getCallingPid();
5184 const int uid = ipc->getCallingUid();
5185 if ((uid != AID_GRAPHICS) &&
5186 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5187 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5188 return PERMISSION_DENIED;
5189 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005190 return OK;
5191 }
5192 // The following codes are deprecated and should never be allowed to access SF.
5193 case CONNECT_DISPLAY_UNUSED:
5194 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5195 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5196 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005197 }
chaviw93df2ea2019-04-30 16:45:12 -07005198 case CAPTURE_SCREEN_BY_ID: {
5199 IPCThreadState* ipc = IPCThreadState::self();
5200 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005201 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005202 return OK;
5203 }
5204 return PERMISSION_DENIED;
5205 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005206 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005207
5208 // These codes are used for the IBinder protocol to either interrogate the recipient
5209 // side of the transaction for its canonical interface descriptor or to dump its state.
5210 // We let them pass by default.
5211 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5212 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5213 code == IBinder::SYSPROPS_TRANSACTION) {
5214 return OK;
5215 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005216 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005217 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005218 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005219 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5220 return OK;
5221 }
5222 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5223 return PERMISSION_DENIED;
5224#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005225}
5226
Ana Krulec13be8ad2018-08-21 02:43:56 +00005227status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5228 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005229 status_t credentialCheck = CheckTransactCodeCredentials(code);
5230 if (credentialCheck != OK) {
5231 return credentialCheck;
5232 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005233
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005234 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5235 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005236 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005237 IPCThreadState* ipc = IPCThreadState::self();
5238 const int uid = ipc->getCallingUid();
5239 if (CC_UNLIKELY(uid != AID_SYSTEM
5240 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005241 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005242 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005243 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005244 return PERMISSION_DENIED;
5245 }
5246 int n;
5247 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005248 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005249 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005250 return NO_ERROR;
5251 case 1002: // SHOW_UPDATES
5252 n = data.readInt32();
5253 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005254 invalidateHwcGeometry();
5255 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005256 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005257 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005258 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005259 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005260 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005261 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005262 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005263 setTransactionFlags(
5264 eTransactionNeeded|
5265 eDisplayTransactionNeeded|
5266 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005267 return NO_ERROR;
5268 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005269 case 1006:{ // send empty update
5270 signalRefresh();
5271 return NO_ERROR;
5272 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005273 case 1008: // toggle use of hw composer
5274 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005275 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005276 invalidateHwcGeometry();
5277 repaintEverything();
5278 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005279 case 1009: // toggle use of transform hint
5280 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005281 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005282 invalidateHwcGeometry();
5283 repaintEverything();
5284 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005285 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005286 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005287 reply->writeInt32(0);
5288 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005289 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005290 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005291 return NO_ERROR;
5292 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005293 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005294 if (!display) {
5295 return NAME_NOT_FOUND;
5296 }
5297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005298 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005299 return NO_ERROR;
5300 }
5301 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005302 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005303 // daltonize
5304 n = data.readInt32();
5305 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005306 case 1:
5307 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5308 break;
5309 case 2:
5310 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5311 break;
5312 case 3:
5313 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5314 break;
5315 default:
5316 mDaltonizer.setType(ColorBlindnessType::None);
5317 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005318 }
5319 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005320 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005321 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005322 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005323 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005324
5325 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005326 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005327 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005328 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005329 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005330 // apply a color matrix
5331 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005332 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005333 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005334 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005335 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005336 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005337 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005338 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005339 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005340 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005341 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005342
5343 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5344 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005345 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005346 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5347 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5348 }
5349
Chia-I Wu28f320b2018-05-03 11:02:56 -07005350 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005351 return NO_ERROR;
5352 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005353 // This is an experimental interface
5354 // Needs to be shifted to proper binder interface when we productize
5355 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005356 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005357 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005358 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005359 return NO_ERROR;
5360 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005361 case 1017: {
5362 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005363 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005364 return NO_ERROR;
5365 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005366 case 1018: { // Modify Choreographer's phase offset
5367 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005368 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005369 return NO_ERROR;
5370 }
5371 case 1019: { // Modify SurfaceFlinger's phase offset
5372 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005373 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005374 return NO_ERROR;
5375 }
Irvel468051e2016-06-13 16:44:44 -07005376 case 1020: { // Layer updates interceptor
5377 n = data.readInt32();
5378 if (n) {
5379 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005380 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005381 }
5382 else{
5383 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005384 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005385 }
5386 return NO_ERROR;
5387 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005388 case 1021: { // Disable HWC virtual displays
5389 n = data.readInt32();
5390 mUseHwcVirtualDisplays = !n;
5391 return NO_ERROR;
5392 }
Romain Guy0147a172017-06-01 13:53:56 -07005393 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005394 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005395 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005396
Chia-I Wu28f320b2018-05-03 11:02:56 -07005397 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005398 return NO_ERROR;
5399 }
Romain Guy54f154a2017-10-24 21:40:32 +01005400 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005401 int32_t colorMode;
5402
Chia-I Wu0d711262018-05-21 15:19:35 -07005403 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005404 if (data.readInt32(&colorMode) == NO_ERROR) {
5405 mForceColorMode = static_cast<ColorMode>(colorMode);
5406 }
Romain Guy54f154a2017-10-24 21:40:32 +01005407 invalidateHwcGeometry();
5408 repaintEverything();
5409 return NO_ERROR;
5410 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005411 // Deprecate, use 1030 to check whether the device is color managed.
5412 case 1024: {
5413 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005414 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005415 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005416 n = data.readInt32();
5417 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005418 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005419 Mutex::Autolock lock(mStateLock);
5420 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005421 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005422 reply->writeInt32(NO_ERROR);
5423 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005424 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005425 bool writeFile = false;
5426 {
5427 Mutex::Autolock lock(mStateLock);
5428 mTracingEnabledChanged = true;
5429 writeFile = mTracing.disable();
5430 }
5431
5432 if (writeFile) {
5433 reply->writeInt32(mTracing.writeToFile());
5434 } else {
5435 reply->writeInt32(NO_ERROR);
5436 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005437 }
5438 return NO_ERROR;
5439 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005440 case 1026: { // Get layer tracing status
5441 reply->writeBool(mTracing.isEnabled());
5442 return NO_ERROR;
5443 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005444 // Is a DisplayColorSetting supported?
5445 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005446 const auto display = getDefaultDisplayDevice();
5447 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005448 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005449 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005450
5451 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5452 switch (setting) {
5453 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005454 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005455 break;
5456 case DisplayColorSetting::UNMANAGED:
5457 reply->writeBool(true);
5458 break;
5459 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005460 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005461 break;
5462 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005463 reply->writeBool(
5464 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005465 break;
5466 }
5467 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005468 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005469 // Is VrFlinger active?
5470 case 1028: {
5471 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005472 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005473 return NO_ERROR;
5474 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005475 // Set buffer size for SF tracing (value in KB)
5476 case 1029: {
5477 n = data.readInt32();
5478 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5479 ALOGW("Invalid buffer size: %d KB", n);
5480 reply->writeInt32(BAD_VALUE);
5481 return BAD_VALUE;
5482 }
5483
5484 ALOGD("Updating trace buffer to %d KB", n);
5485 mTracing.setBufferSize(n * 1024);
5486 reply->writeInt32(NO_ERROR);
5487 return NO_ERROR;
5488 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005489 // Is device color managed?
5490 case 1030: {
5491 reply->writeBool(useColorManagement);
5492 return NO_ERROR;
5493 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005494 // Override default composition data space
5495 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5496 // && adb shell stop zygote && adb shell start zygote
5497 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5498 // adb shell stop zygote && adb shell start zygote
5499 case 1031: {
5500 Mutex::Autolock _l(mStateLock);
5501 n = data.readInt32();
5502 if (n) {
5503 n = data.readInt32();
5504 if (n) {
5505 Dataspace dataspace = static_cast<Dataspace>(n);
5506 if (!validateCompositionDataspace(dataspace)) {
5507 return BAD_VALUE;
5508 }
5509 mDefaultCompositionDataspace = dataspace;
5510 }
5511 n = data.readInt32();
5512 if (n) {
5513 Dataspace dataspace = static_cast<Dataspace>(n);
5514 if (!validateCompositionDataspace(dataspace)) {
5515 return BAD_VALUE;
5516 }
5517 mWideColorGamutCompositionDataspace = dataspace;
5518 }
5519 } else {
5520 // restore composition data space.
5521 mDefaultCompositionDataspace = defaultCompositionDataspace;
5522 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5523 }
5524 return NO_ERROR;
5525 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005526 // Set trace flags
5527 case 1033: {
5528 n = data.readUint32();
5529 ALOGD("Updating trace flags to 0x%x", n);
5530 mTracing.setTraceFlags(n);
5531 reply->writeInt32(NO_ERROR);
5532 return NO_ERROR;
5533 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005534 case 1034: {
5535 // TODO(b/129297325): expose this via developer menu option
5536 n = data.readInt32();
5537 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005538 RefreshRateType type;
5539 {
5540 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5541 type = mDesiredActiveConfig.type;
5542 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005543 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005544 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005545 } else if (!n) {
5546 mRefreshRateOverlay.reset();
5547 }
5548 return NO_ERROR;
5549 }
Ady Abraham34392f72019-04-10 11:29:27 -07005550 case 1035: {
5551 n = data.readInt32();
5552 mDebugDisplayConfigSetByBackdoor = false;
5553 if (n >= 0) {
5554 const auto displayToken = getInternalDisplayToken();
5555 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5556 if (result != NO_ERROR) {
5557 return result;
5558 }
5559 mDebugDisplayConfigSetByBackdoor = true;
5560 }
5561 return NO_ERROR;
5562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005563 }
5564 }
5565 return err;
5566}
5567
Steven Thomas6d8110b2017-08-31 18:24:21 -07005568void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005569 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005570 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005571}
5572
Ana Krulec7d1d6832018-12-27 11:10:09 -08005573void SurfaceFlinger::repaintEverythingForHWC() {
5574 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005575 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005576}
5577
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005578// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5579class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005580public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005581 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5582 ~WindowDisconnector() {
5583 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005584 }
5585
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005586private:
5587 ANativeWindow* mWindow;
5588 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005589};
5590
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005591status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005592 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5593 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005594 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005595 uint32_t reqWidth, uint32_t reqHeight,
5596 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005597 ISurfaceComposer::Rotation rotation,
5598 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005599 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005600
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005601 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005602
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005603 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5604
Chia-I Wu20261cb2018-08-23 12:55:44 -07005605 sp<DisplayDevice> display;
5606 {
5607 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005608
Chia-I Wu20261cb2018-08-23 12:55:44 -07005609 display = getDisplayDeviceLocked(displayToken);
5610 if (!display) return BAD_VALUE;
5611
Chia-I Wucb023152018-08-28 12:57:23 -07005612 // set the requested width/height to the logical display viewport size
5613 // by default
5614 if (reqWidth == 0 || reqHeight == 0) {
5615 reqWidth = uint32_t(display->getViewport().width());
5616 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005617 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005618 }
5619
Peiyong Lin0e003c92018-09-17 11:09:51 -07005620 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005621 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005622
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005623 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5624 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005625 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005626 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005627}
5628
chaviw93df2ea2019-04-30 16:45:12 -07005629static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5630 switch (colorMode) {
5631 case ColorMode::DISPLAY_P3:
5632 case ColorMode::BT2100_PQ:
5633 case ColorMode::BT2100_HLG:
5634 case ColorMode::DISPLAY_BT2020:
5635 return Dataspace::DISPLAY_P3;
5636 default:
5637 return Dataspace::V0_SRGB;
5638 }
5639}
5640
5641const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5642 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5643 if (displayToken) {
5644 return getDisplayDeviceLocked(displayToken);
5645 }
5646 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5647 // may not have a displayId.
5648 for (const auto& [token, display] : mDisplays) {
5649 if (display->getLayerStack() == displayOrLayerStack) {
5650 return display;
5651 }
5652 }
5653 return nullptr;
5654}
5655
5656status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5657 sp<GraphicBuffer>* outBuffer) {
5658 sp<DisplayDevice> display;
5659 uint32_t width;
5660 uint32_t height;
5661 ui::Transform::orientation_flags captureOrientation;
5662 {
5663 Mutex::Autolock _l(mStateLock);
5664 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5665 if (!display) {
5666 return BAD_VALUE;
5667 }
5668
5669 width = uint32_t(display->getViewport().width());
5670 height = uint32_t(display->getViewport().height());
5671
5672 captureOrientation = fromSurfaceComposerRotation(
5673 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005674 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5675 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5676 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5677 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5678 }
chaviw93df2ea2019-04-30 16:45:12 -07005679 *outDataspace =
5680 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5681 }
5682
5683 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5684 false /* captureSecureLayers */);
5685
5686 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5687 std::placeholders::_1);
5688 bool ignored = false;
5689 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5690 false /* useIdentityTransform */,
5691 ignored /* outCapturedSecureLayers */);
5692}
5693
Robert Carr866455f2019-04-02 16:28:26 -07005694status_t SurfaceFlinger::captureLayers(
5695 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5696 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5697 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5698 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005699 ATRACE_CALL();
5700
5701 class LayerRenderArea : public RenderArea {
5702 public:
Robert Carr578038f2018-03-09 12:25:24 -08005703 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005704 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5705 bool childrenOnly)
5706 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005707 mLayer(layer),
5708 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005709 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005710 mFlinger(flinger),
5711 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005712 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005713 Rect getBounds() const override {
5714 const Layer::State& layerState(mLayer->getDrawingState());
5715 return mLayer->getBufferSize(layerState);
5716 }
Marissa Wall61c58622018-07-18 10:12:20 -07005717 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005718 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005719 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005720 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005721 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005722 }
chaviwa76b2712017-09-20 12:02:26 -07005723 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005724 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005725 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005726 Rect getSourceCrop() const override {
5727 if (mCrop.isEmpty()) {
5728 return getBounds();
5729 } else {
5730 return mCrop;
5731 }
5732 }
Robert Carr578038f2018-03-09 12:25:24 -08005733 class ReparentForDrawing {
5734 public:
5735 const sp<Layer>& oldParent;
5736 const sp<Layer>& newParent;
5737
Vishnu Nair4351ad52019-02-11 14:13:02 -08005738 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5739 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005740 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005741 // Compute and cache the bounds for the new parent layer.
5742 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005743 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005744 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005745 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005746 };
5747
5748 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005749 const Rect sourceCrop = getSourceCrop();
5750 // no need to check rotation because there is none
5751 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5752 sourceCrop.height() != getReqHeight();
5753
Robert Carr578038f2018-03-09 12:25:24 -08005754 if (!mChildrenOnly) {
5755 mTransform = mLayer->getTransform().inverse();
5756 drawLayers();
5757 } else {
5758 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005759 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005760 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005761 bounds.getWidth(), bounds.getHeight(), 0,
5762 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005763
Vishnu Nair4351ad52019-02-11 14:13:02 -08005764 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005765 drawLayers();
5766 }
5767 }
chaviwa76b2712017-09-20 12:02:26 -07005768
chaviwa76b2712017-09-20 12:02:26 -07005769 private:
chaviw7206d492017-11-10 16:16:12 -08005770 const sp<Layer> mLayer;
5771 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005772
5773 // In the "childrenOnly" case we reparent the children to a screenshot
5774 // layer which has no properties set and which does not draw.
5775 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005776 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005777 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005778
5779 SurfaceFlinger* mFlinger;
5780 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005781 };
5782
Robert Carrc0df3122019-04-11 13:18:21 -07005783 int reqWidth = 0;
5784 int reqHeight = 0;
5785 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005786 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005787 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005788
Robert Carrc0df3122019-04-11 13:18:21 -07005789 {
5790 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005791
Robert Carrc0df3122019-04-11 13:18:21 -07005792 parent = fromHandle(layerHandleBinder);
5793 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5794 ALOGE("captureLayers called with an invalid or removed parent");
5795 return NAME_NOT_FOUND;
5796 }
5797
5798 const int uid = IPCThreadState::self()->getCallingUid();
5799 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5800 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5801 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5802 return PERMISSION_DENIED;
5803 }
5804
5805 if (sourceCrop.width() <= 0) {
5806 crop.left = 0;
5807 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5808 }
5809
5810 if (sourceCrop.height() <= 0) {
5811 crop.top = 0;
5812 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5813 }
5814 reqWidth = crop.width() * frameScale;
5815 reqHeight = crop.height() * frameScale;
5816
5817 for (const auto& handle : excludeHandles) {
5818 sp<Layer> excludeLayer = fromHandle(handle);
5819 if (excludeLayer != nullptr) {
5820 excludeLayers.emplace(excludeLayer);
5821 } else {
5822 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5823 return NAME_NOT_FOUND;
5824 }
5825 }
5826 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005827
Chia-I Wu20261cb2018-08-23 12:55:44 -07005828 // really small crop or frameScale
5829 if (reqWidth <= 0) {
5830 reqWidth = 1;
5831 }
5832 if (reqHeight <= 0) {
5833 reqHeight = 1;
5834 }
5835
Robert Carr866455f2019-04-02 16:28:26 -07005836 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5837 auto traverseLayers = [parent, childrenOnly,
5838 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005839 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5840 if (!layer->isVisible()) {
5841 return;
Robert Carr578038f2018-03-09 12:25:24 -08005842 } else if (childrenOnly && layer == parent.get()) {
5843 return;
chaviwa76b2712017-09-20 12:02:26 -07005844 }
Robert Carr866455f2019-04-02 16:28:26 -07005845
5846 sp<Layer> p = layer;
5847 while (p != nullptr) {
5848 if (excludeLayers.count(p) != 0) {
5849 return;
5850 }
5851 p = p->getParent();
5852 }
5853
chaviwa76b2712017-09-20 12:02:26 -07005854 visitor(layer);
5855 });
5856 };
Robert Carr108b2c72019-04-02 16:32:58 -07005857
5858 bool outCapturedSecureLayers = false;
5859 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5860 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005861}
5862
5863status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5864 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005865 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005866 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005867 bool useIdentityTransform,
5868 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005869 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005870
Peiyong Lin0e003c92018-09-17 11:09:51 -07005871 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005872 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5873 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005874 *outBuffer =
5875 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5876 static_cast<android_pixel_format>(reqPixelFormat), 1,
5877 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005878
Robert Carr108b2c72019-04-02 16:32:58 -07005879 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5880 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005881}
5882
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005883status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5884 TraverseLayersFunction traverseLayers,
5885 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005886 bool useIdentityTransform,
5887 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005888 // This mutex protects syncFd and captureResult for communication of the return values from the
5889 // main thread back to this Binder thread
5890 std::mutex captureMutex;
5891 std::condition_variable captureCondition;
5892 std::unique_lock<std::mutex> captureLock(captureMutex);
5893 int syncFd = -1;
5894 std::optional<status_t> captureResult;
5895
Robert Carr03480e22018-01-04 16:02:06 -08005896 const int uid = IPCThreadState::self()->getCallingUid();
5897 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5898
Dominik Laskowski8c001672018-05-30 16:52:06 -07005899 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005900 // If there is a refresh pending, bug out early and tell the binder thread to try again
5901 // after the refresh.
5902 if (mRefreshPending) {
5903 ATRACE_NAME("Skipping screenshot for now");
5904 std::unique_lock<std::mutex> captureLock(captureMutex);
5905 captureResult = std::make_optional<status_t>(EAGAIN);
5906 captureCondition.notify_one();
5907 return;
5908 }
5909
5910 status_t result = NO_ERROR;
5911 int fd = -1;
5912 {
5913 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005914 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005915 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005916 useIdentityTransform, forSystem, &fd,
5917 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005918 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005919 }
5920
5921 {
5922 std::unique_lock<std::mutex> captureLock(captureMutex);
5923 syncFd = fd;
5924 captureResult = std::make_optional<status_t>(result);
5925 captureCondition.notify_one();
5926 }
5927 });
5928
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005929 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005930 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005931 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005932 while (*captureResult == EAGAIN) {
5933 captureResult.reset();
5934 result = postMessageAsync(message);
5935 if (result != NO_ERROR) {
5936 return result;
5937 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005938 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005939 }
5940 result = *captureResult;
5941 }
5942
5943 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005944 sync_wait(syncFd, -1);
5945 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005946 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005947
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005948 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005949}
5950
chaviwa76b2712017-09-20 12:02:26 -07005951void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005952 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005953 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5954 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005955 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005956
chaviwa76b2712017-09-20 12:02:26 -07005957 const auto reqWidth = renderArea.getReqWidth();
5958 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005959 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005960 const auto transform = renderArea.getTransform();
5961 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005962
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005963 renderengine::DisplaySettings clientCompositionDisplay;
5964 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005965
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005966 // assume that bounds are never offset, and that they are the same as the
5967 // buffer bounds.
5968 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005969 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005970 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005971
5972 // Now take into account the rotation flag. We append a transform that
5973 // rotates the layer stack about the origin, then translate by buffer
5974 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005975 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005976 int displacementX = 0;
5977 int displacementY = 0;
5978 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5979 switch (rotation) {
5980 case ui::Transform::ROT_90:
5981 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005982 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005983 break;
5984 case ui::Transform::ROT_180:
5985 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005986 displacementY = renderArea.getBounds().getWidth();
5987 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005988 break;
5989 case ui::Transform::ROT_270:
5990 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005991 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005992 break;
5993 default:
5994 break;
5995 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005996
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005997 // We need to transform the clipping window into the right spot.
5998 // First, rotate the clipping rectangle by the rotation hint to get the
5999 // right orientation
6000 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6001 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6002 const vec4 rotClipTL = rotMatrix * clipTL;
6003 const vec4 rotClipBR = rotMatrix * clipBR;
6004 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6005 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6006 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6007 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6008
6009 // Now reposition the clipping rectangle with the displacement vector
6010 // computed above.
6011 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006012 clientCompositionDisplay.clip =
6013 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6014 newClipRight + displacementX, newClipBottom + displacementY);
6015
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006016 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006017 clientCompositionDisplay.globalTransform =
6018 clipTransform * clientCompositionDisplay.globalTransform;
6019
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006020 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6021 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006022
chaviw50da5042018-04-09 13:49:37 -07006023 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006024
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006025 renderengine::LayerSettings fillLayer;
6026 fillLayer.source.buffer.buffer = nullptr;
6027 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6028 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6029 fillLayer.alpha = half(alpha);
6030 clientCompositionLayers.push_back(fillLayer);
6031
6032 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006033 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006034 renderengine::LayerSettings layerSettings;
6035 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006036 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006037 if (prepared) {
6038 clientCompositionLayers.push_back(layerSettings);
6039 }
chaviwa76b2712017-09-20 12:02:26 -07006040 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006041
6042 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006043 // Use an empty fence for the buffer fence, since we just created the buffer so
6044 // there is no need for synchronization with the GPU.
6045 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006046 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006047 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006048 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006049 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006050
6051 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006052}
6053
chaviwa76b2712017-09-20 12:02:26 -07006054status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6055 TraverseLayersFunction traverseLayers,
6056 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006057 bool useIdentityTransform, bool forSystem,
6058 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006059 ATRACE_CALL();
6060
chaviwa76b2712017-09-20 12:02:26 -07006061 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006062 outCapturedSecureLayers =
6063 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006064 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006065
Robert Carr03480e22018-01-04 16:02:06 -08006066 // We allow the system server to take screenshots of secure layers for
6067 // use in situations like the Screen-rotation animation and place
6068 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006069 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006070 ALOGW("FB is protected: PERMISSION_DENIED");
6071 return PERMISSION_DENIED;
6072 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006073 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006074 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006075}
6076
chaviw95ef3c42019-02-14 10:55:09 -08006077void SurfaceFlinger::setInputWindowsFinished() {
6078 Mutex::Autolock _l(mStateLock);
6079
6080 mPendingSyncInputWindows = false;
6081 mTransactionCV.broadcast();
6082}
chaviw5f21a5e2019-02-14 10:00:34 -08006083
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006084// ---------------------------------------------------------------------------
6085
Dan Stoza412903f2017-04-27 13:42:17 -07006086void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6087 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006088}
6089
Dan Stoza412903f2017-04-27 13:42:17 -07006090void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6091 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006092}
6093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006094void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006095 const LayerVector::Visitor& visitor) {
6096 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006097 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006098 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006099 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006100 continue;
6101 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006102 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006103 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006104 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006105 return;
6106 }
chaviwa76b2712017-09-20 12:02:26 -07006107 if (!layer->isVisible()) {
6108 return;
6109 }
6110 visitor(layer);
6111 });
6112 }
6113}
6114
Dominik Laskowski22488f62019-03-28 09:53:04 -07006115void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6116 const std::vector<int32_t>& allowedConfigs) {
6117 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006118 return;
6119 }
6120
6121 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006122 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006123
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006124 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006125 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006126 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006127 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006128 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006129 setDesiredActiveConfig(
6130 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006131 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006132 }
6133 }
Ady Abraham838de062019-02-04 10:24:03 -08006134}
6135
Dominik Laskowski22488f62019-03-28 09:53:04 -07006136status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006137 const std::vector<int32_t>& allowedConfigs) {
6138 ATRACE_CALL();
6139
Dominik Laskowski22488f62019-03-28 09:53:04 -07006140 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006141 return BAD_VALUE;
6142 }
6143
Ady Abraham34392f72019-04-10 11:29:27 -07006144 if (mDebugDisplayConfigSetByBackdoor) {
6145 // ignore this request as config is overridden by backdoor
6146 return NO_ERROR;
6147 }
6148
Ady Abraham838de062019-02-04 10:24:03 -08006149 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006150 const auto display = getDisplayDeviceLocked(displayToken);
6151 if (!display) {
6152 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6153 displayToken.get());
6154 } else if (display->isVirtual()) {
6155 ALOGW("Attempt to set allowed display configs for virtual display");
6156 } else {
6157 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6158 }
Ady Abraham838de062019-02-04 10:24:03 -08006159 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006160
Ady Abraham838de062019-02-04 10:24:03 -08006161 return NO_ERROR;
6162}
6163
Dominik Laskowski22488f62019-03-28 09:53:04 -07006164status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006165 std::vector<int32_t>* outAllowedConfigs) {
6166 ATRACE_CALL();
6167
Dominik Laskowski22488f62019-03-28 09:53:04 -07006168 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006169 return BAD_VALUE;
6170 }
6171
Dominik Laskowski22488f62019-03-28 09:53:04 -07006172 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006173
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006174 const auto display = getDisplayDeviceLocked(displayToken);
6175 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006176 return NAME_NOT_FOUND;
6177 }
6178
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006179 if (display->isPrimary()) {
6180 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6181 }
6182
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006183 return NO_ERROR;
6184}
6185
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006186void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006187 mFlinger->setInputWindowsFinished();
6188}
6189
Robert Carrc0df3122019-04-11 13:18:21 -07006190sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6191 BBinder *b = handle->localBinder();
6192 if (b == nullptr) {
6193 return nullptr;
6194 }
6195 auto it = mLayersByLocalBinderToken.find(b);
6196 if (it != mLayersByLocalBinderToken.end()) {
6197 return it->second.promote();
6198 }
6199 return nullptr;
6200}
6201
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006202} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006203
Mathias Agopian3f844832013-08-07 21:24:32 -07006204#if defined(__gl_h_)
6205#error "don't include gl/gl.h in this file"
6206#endif
6207
6208#if defined(__gl2_h_)
6209#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006210#endif