blob: 017c3d2bb609141065bda307fa6c59c129fb5dd8 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/Layer.h>
45#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070046#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080047#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070048#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080049#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080050#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070052#include <gui/DebugEGLImageTracker.h>
53
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070055#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080056#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080057#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070060#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <ui/ColorSpace.h>
62#include <ui/DebugUtils.h>
63#include <ui/DisplayInfo.h>
64#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070065#include <ui/GraphicBufferAllocator.h>
66#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070067#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080068#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <utils/String16.h>
70#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070071#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080072#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070073#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopian921e6ac2012-07-23 23:11:29 -070075#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070076#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Robert Carr578038f2018-03-09 12:25:24 -080078#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070079#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070080#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020081#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020083#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080084#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080086#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070087#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080088#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070089#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070090#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070091#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080094
Steven Thomasb02664d2017-07-26 18:48:28 -070095#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070096#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070097#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070098#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070099#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700100#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700101#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700103#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104#include "Scheduler/EventControlThread.h"
105#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700106#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700107#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700108#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700109#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800110#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700111
Mathias Agopianff2ed702013-09-01 21:36:12 -0700112#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700113
David Sodman7e4ae112018-02-09 15:02:28 -0800114#include "android-base/stringprintf.h"
115
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800117#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
118#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700119#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900120#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121
chaviw1d044282017-09-27 12:19:28 -0700122#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900123#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700124
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800125namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
242 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
259 mTimeStats(mFactory.createTimeStats()),
260 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700261 mCompositionEngine(mFactory.createCompositionEngine()),
262 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900267 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 mDefaultCompositionDataspace =
285 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700286 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
287 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 defaultCompositionDataspace = mDefaultCompositionDataspace;
289 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
290 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
291 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
292 wideColorGamutCompositionPixelFormat =
293 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294
Yichi Chenda901bf2019-06-28 14:58:27 +0800295 mColorSpaceAgnosticDataspace =
296 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
301 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
302 switch (tmpPrimaryDisplayOrientation) {
303 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700304 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800305 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700307 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800308 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700310 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
312 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700313 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
315 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700316 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800317
Sundong Ahn85131bd2019-02-18 15:51:53 +0900318 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 // debugging stuff...
321 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700322
Mathias Agopianb4b17302013-03-20 18:36:41 -0700323 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700324 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 property_get("debug.sf.showupdates", value, "0");
327 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700328
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700329 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000330
331 // DDMS debugging deprecated (b/120782499)
332 property_get("debug.sf.ddms", value, "0");
333 int debugDdms = atoi(value);
334 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700335
336 property_get("debug.sf.disable_backpressure", value, "0");
337 mPropagateBackpressure = !atoi(value);
338 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700339
Ady Abraham4658e112019-07-22 13:07:26 -0700340 property_get("debug.sf.enable_gl_backpressure", value, "0");
341 mPropagateBackpressureClientComposition = atoi(value);
342 ALOGI_IF(mPropagateBackpressureClientComposition,
343 "Enabling backpressure propagation for Client Composition");
344
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800345 property_get("debug.sf.enable_hwc_vds", value, "0");
346 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800347 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800348
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800349 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800350 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800351 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700352
Yiwei Zhang243b3782018-05-15 17:40:04 -0700353 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700354 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
355 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
356
Ana Krulece5a06e02019-03-06 17:09:03 -0800357 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800358 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800359
360 int int_value = atoi(value);
361 if (int_value) {
362 mUseSmart90ForVideo = true;
363 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800364
Dan Stozaec460082018-12-17 15:35:09 -0800365 property_get("debug.sf.luma_sampling", value, "1");
366 mLumaSampling = atoi(value);
367
Romain Guy11d63f42017-07-20 12:47:14 -0700368 // We should be reading 'persist.sys.sf.color_saturation' here
369 // but since /data may be encrypted, we need to wait until after vold
370 // comes online to attempt to read the property. The property is
371 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800372
373 if (useTrebleTestingOverride()) {
374 // Without the override SurfaceFlinger cannot connect to HIDL
375 // services that are not listed in the manifests. Considered
376 // deriving the setting from the set service name, but it
377 // would be brittle if the name that's not 'default' is used
378 // for production purposes later on.
379 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381}
382
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800383void SurfaceFlinger::onFirstRef()
384{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800385 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386}
387
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700388SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389
Dan Stozac7014012014-02-14 15:03:43 -0800390void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800391{
392 // the window manager died on us. prepare its eulogy.
393
Andy McFadden13a082e2012-08-24 10:16:42 -0700394 // restore initial conditions (default device unblank, etc)
395 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800396
397 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399}
400
Robert Carr1db73f62016-12-21 12:58:51 -0800401static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700402 status_t err = client->initCheck();
403 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800404 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 }
Robert Carr1db73f62016-12-21 12:58:51 -0800406 return nullptr;
407}
408
409sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
410 return initClient(new Client(this));
411}
412
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700413sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
414 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415{
416 class DisplayToken : public BBinder {
417 sp<SurfaceFlinger> flinger;
418 virtual ~DisplayToken() {
419 // no more references, this display must be terminated
420 Mutex::Autolock _l(flinger->mStateLock);
421 flinger->mCurrentState.displays.removeItem(this);
422 flinger->setTransactionFlags(eDisplayTransactionNeeded);
423 }
424 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700425 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700426 : flinger(flinger) {
427 }
428 };
429
430 sp<BBinder> token = new DisplayToken(this);
431
432 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700433 // Display ID is assigned when virtual display is allocated by HWC.
434 DisplayDeviceState state;
435 state.isSecure = secure;
436 state.displayName = displayName;
437 mCurrentState.displays.add(token, state);
438 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 return token;
440}
441
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700442void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700443 Mutex::Autolock _l(mStateLock);
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
446 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700447 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700448 return;
449 }
450
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
452 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700453 ALOGE("destroyDisplay called for non-virtual display");
454 return;
455 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700456 mInterceptor->saveDisplayDeletion(state.sequenceId);
457 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 setTransactionFlags(eDisplayTransactionNeeded);
459}
460
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800461std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
462 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800464 const auto internalDisplayId = getInternalDisplayIdLocked();
465 if (!internalDisplayId) {
466 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 }
468
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800469 std::vector<PhysicalDisplayId> displayIds;
470 displayIds.reserve(mPhysicalDisplayTokens.size());
471 displayIds.push_back(internalDisplayId->value);
472
473 for (const auto& [id, token] : mPhysicalDisplayTokens) {
474 if (id != *internalDisplayId) {
475 displayIds.push_back(id.value);
476 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479 return displayIds;
480}
481
482sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
483 Mutex::Autolock lock(mStateLock);
484 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485}
486
Ady Abraham37965d42018-11-01 13:43:32 -0700487status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
488 if (!outGetColorManagement) {
489 return BAD_VALUE;
490 }
491 *outGetColorManagement = useColorManagement;
492 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700493}
494
Lloyd Pique441d5042018-10-18 16:49:51 -0700495HWComposer& SurfaceFlinger::getHwComposer() const {
496 return mCompositionEngine->getHwComposer();
497}
498
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700499renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
500 return mCompositionEngine->getRenderEngine();
501}
502
Lloyd Pique70d91362018-10-18 16:02:55 -0700503compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
504 return *mCompositionEngine.get();
505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
516 // wait patiently for the window manager death
517 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700518 mWindowManager = defaultServiceManager()->getService(name);
519 if (mWindowManager != 0) {
520 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 }
Robert Carr720e5062018-07-30 17:45:14 -0700522 sp<IBinder> input(defaultServiceManager()->getService(
523 String16("inputflinger")));
524 if (input == nullptr) {
525 ALOGE("Failed to link to input service");
526 } else {
527 mInputFlinger = interface_cast<IInputFlinger>(input);
528 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529
Steven Thomas050b2c82017-03-06 11:45:16 -0800530 if (mVrFlinger) {
531 mVrFlinger->OnBootFinished();
532 }
533
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700535 // formerly we would just kill the process, but we now ask it to exit so it
536 // can choose where to stop the animation.
537 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700538
539 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
540 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
541 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700542
Ana Krulecbd6654b2019-02-15 15:18:15 -0800543 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800544 readPersistentProperties();
545 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800546
Ady Abraham97d04232019-03-05 19:48:12 -0800547 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700548 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700549 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800550
Dominik Laskowski22488f62019-03-28 09:53:04 -0700551 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800552 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800553 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800554 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800555 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800556 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800557}
558
Dan Stoza436ccf32018-06-21 12:10:12 -0700559uint32_t SurfaceFlinger::getNewTexture() {
560 {
561 std::lock_guard lock(mTexturePoolMutex);
562 if (!mTexturePool.empty()) {
563 uint32_t name = mTexturePool.back();
564 mTexturePool.pop_back();
565 ATRACE_INT("TexturePoolSize", mTexturePool.size());
566 return name;
567 }
568
569 // The pool was too small, so increase it for the future
570 ++mTexturePoolSize;
571 }
572
573 // The pool was empty, so we need to get a new texture name directly using a
574 // blocking call to the main thread
575 uint32_t name = 0;
576 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
577 return name;
578}
579
Mathias Agopian3f844832013-08-07 21:24:32 -0700580void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700581 std::lock_guard lock(mTexturePoolMutex);
582 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
583 // to actually delete this or not based on mTexturePoolSize
584 mTexturePool.push_back(texture);
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700586}
587
Wei Wangf9b05ee2017-07-19 20:59:39 -0700588// Do not call property_set on main thread which will be blocked by init
589// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700590void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700591 ALOGI( "SurfaceFlinger's main thread ready to run. "
592 "Initializing graphics H/W...");
593
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700594 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700597 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800598 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700599 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
600 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800601 auto resyncCallback =
602 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800603
Ana Krulecc2870422019-01-29 19:00:58 -0800604 mAppConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700605 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700606 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800607 resyncCallback,
608 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700609 mSfConnectionHandle =
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700610 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
Ady Abraham45e4e362019-06-07 18:20:51 -0700611 mPhaseOffsets->getOffsetThresholdForNextVsync(),
612 resyncCallback, [this](nsecs_t timestamp) {
613 mInterceptor->saveVSyncEvent(timestamp);
614 });
Ana Krulecc2870422019-01-29 19:00:58 -0800615
616 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700617
618 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
619 mPhaseOffsets->getCurrentOffsets());
Ana Krulecc2870422019-01-29 19:00:58 -0800620
Kevin DuBois413287f2019-02-25 08:46:47 -0800621 mRegionSamplingThread =
622 new RegionSamplingThread(*this, *mScheduler,
623 RegionSamplingThread::EnvironmentTimingTunables());
624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700626 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700627 renderEngineFeature |= (useColorManagement ?
628 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700629 renderEngineFeature |= (useContextPriority ?
630 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700631 renderEngineFeature |=
632 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
633 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800636 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700637 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700638 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800639 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700643 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
644 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700653 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700654 // This callback is called from the vr flinger dispatch thread. We
655 // need to call signalTransaction(), which requires holding
656 // mStateLock when we're not on the main thread. Acquiring
657 // mStateLock from the vr flinger dispatch thread might trigger a
658 // deadlock in surface flinger (see b/66916578), so post a message
659 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700660 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700661 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
662 mVrFlingerRequestsDisplay = requestDisplay;
663 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
667 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700668 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700669 .value_or(0),
670 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 if (!mVrFlinger) {
672 ALOGE("Failed to start vrflinger");
673 }
674 }
675
Mathias Agopian92a979a2012-08-02 18:32:23 -0700676 // initialize our drawing state
677 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700678
Andy McFadden13a082e2012-08-24 10:16:42 -0700679 // set initial conditions (e.g. unblank default device)
680 initializeDisplays();
681
Steven Thomas137d4bc2019-07-25 16:55:14 -0700682 char primeShaderCache[PROPERTY_VALUE_MAX];
683 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
684 if (atoi(primeShaderCache)) {
685 getRenderEngine().primeCache();
686 }
Dan Stoza4e637772016-07-28 13:31:51 -0700687
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700689
690 const bool presentFenceReliable =
691 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
692 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693
694 if (mStartPropertySetThread->Start() != NO_ERROR) {
695 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800696 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697
Alec Mouri93bc83d2019-04-17 14:47:43 -0700698 mScheduler->setChangeRefreshRateCallback(
699 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
700 Mutex::Autolock lock(mStateLock);
701 setRefreshRateTo(type, event);
702 });
Alec Mouri7f015182019-07-11 13:56:22 -0700703 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
704 Mutex::Autolock lock(mStateLock);
705 const auto display = getDefaultDisplayDeviceLocked();
706 if (!display) {
707 // If we don't have a default display the fallback to the default
708 // refresh rate type
709 return RefreshRateType::DEFAULT;
710 }
711
712 const int configId = display->getActiveConfig();
713 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
714 if (refresh && refresh->configId == configId) {
715 return type;
716 }
717 }
718 // This should never happen, but just gracefully fallback to default.
719 return RefreshRateType::DEFAULT;
720 });
Alec Mouridc28b372019-04-18 21:17:13 -0700721 mScheduler->setGetVsyncPeriodCallback([this] {
722 Mutex::Autolock lock(mStateLock);
723 return getVsyncPeriod();
724 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700725
Dominik Laskowski22488f62019-03-28 09:53:04 -0700726 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
727 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800728
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700730}
731
Romain Guy11d63f42017-07-20 12:47:14 -0700732void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700733 Mutex::Autolock _l(mStateLock);
734
Romain Guy11d63f42017-07-20 12:47:14 -0700735 char value[PROPERTY_VALUE_MAX];
736
737 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700739 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800740 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100741
742 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700743 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800744
745 property_get("persist.sys.sf.color_mode", value, "0");
746 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700760 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700764 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dominik Laskowski22488f62019-03-28 09:53:04 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
803 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700804 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Dominik Laskowski22488f62019-03-28 09:53:04 -0700808 Mutex::Autolock lock(mStateLock);
809
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800810 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700811 if (!displayId) {
812 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700813 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700814
Mathias Agopian8b736f12012-08-13 17:54:26 -0700815 // TODO: Not sure if display density should handled by SF any longer
816 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700817 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700819 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800820 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700821 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700822 }
823 return density;
824 }
825 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700828 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 return getDensityFromProperty("ro.sf.lcd_density"); }
830 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Dan Stoza7f7da322014-05-02 15:26:25 -0700832 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700833
Dominik Laskowski075d3172018-05-24 15:50:06 -0700834 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 DisplayInfo info = DisplayInfo();
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 float xdpi = hwConfig->getDpiX();
838 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700840 info.w = hwConfig->getWidth();
841 info.h = hwConfig->getHeight();
842 // Default display viewport to display width and height
843 info.viewportW = info.w;
844 info.viewportH = info.h;
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 // The density of the device is provided by a build property
848 float density = Density::getBuildDensity() / 160.0f;
849 if (density == 0) {
850 // the build doesn't provide a density -- this is wrong!
851 // use xdpi instead
852 ALOGE("ro.sf.lcd_density must be defined as a build property");
853 density = xdpi / 160.0f;
854 }
855 if (Density::getEmuDensity()) {
856 // if "qemu.sf.lcd_density" is specified, it overrides everything
857 xdpi = ydpi = density = Density::getEmuDensity();
858 density /= 160.0f;
859 }
860 info.density = density;
861
862 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863 const auto display = getDefaultDisplayDeviceLocked();
864 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865
866 // This is for screenrecord
867 const Rect viewport = display->getViewport();
868 if (viewport.isValid()) {
869 info.viewportW = uint32_t(viewport.getWidth());
870 info.viewportH = uint32_t(viewport.getHeight());
871 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 } else {
873 // TODO: where should this value come from?
874 static const int TV_DENSITY = 213;
875 info.density = TV_DENSITY / 160.0f;
876 info.orientation = 0;
877 }
878
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 info.xdpi = xdpi;
880 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700882 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
883 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
884 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800885
Andy McFadden91b2ca82014-06-13 14:04:23 -0700886 // This is how far in advance a buffer must be queued for
887 // presentation at a given time. If you want a buffer to appear
888 // on the screen at time N, you must submit the buffer before
889 // (N - presentationDeadline).
890 //
891 // Normally it's one full refresh period (to give SF a chance to
892 // latch the buffer), but this can be reduced by configuring a
893 // DispSync offset. Any additional delays introduced by the hardware
894 // composer or panel must be accounted for here.
895 //
896 // We add an additional 1ms to allow for processing time and
897 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700898 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
900 // All non-virtual displays are currently considered secure.
901 info.secure = true;
902
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800903 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700904 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800905 std::swap(info.w, info.h);
906 }
907
Michael Wright28f24d02016-07-12 13:30:53 -0700908 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700909 }
910
Dan Stoza7f7da322014-05-02 15:26:25 -0700911 return NO_ERROR;
912}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700913
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700914status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
915 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700916 return BAD_VALUE;
917 }
918
Ana Krulecc2870422019-01-29 19:00:58 -0800919 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return NO_ERROR;
921}
922
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700923int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
924 const auto display = getDisplayDevice(displayToken);
925 if (!display) {
926 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800927 return BAD_VALUE;
928 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700929
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700930 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700931}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700932
Ady Abraham03b02dd2019-03-21 15:40:11 -0700933void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800934 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800935
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800937 // config twice. However event generation config might have changed so we need to update it
938 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800939 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700940 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
941 mDesiredActiveConfig = info;
942 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800943
944 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945 // This will trigger HWC refresh without resetting the idle timer.
946 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700947 // Start receiving vsync samples now, so that we can detect a period
948 // switch.
949 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700950 // As we called to set period, we will call to onRefreshRateChangeCompleted once
951 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700952 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700953 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700954 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800956 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700957
958 if (mRefreshRateOverlay) {
959 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
960 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961}
962
963status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
964 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800965
966 std::vector<int32_t> allowedConfig;
967 allowedConfig.push_back(mode);
968
969 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970}
971
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972void SurfaceFlinger::setActiveConfigInternal() {
973 ATRACE_CALL();
974
Dominik Laskowski22488f62019-03-28 09:53:04 -0700975 const auto display = getDefaultDisplayDeviceLocked();
976 if (!display) {
977 return;
978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979
Dominik Laskowski22488f62019-03-28 09:53:04 -0700980 std::lock_guard<std::mutex> lock(mActiveConfigLock);
981 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
982
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983 display->setActiveConfig(mUpcomingActiveConfig.configId);
984
Alec Mouri754c98a2019-03-18 18:53:42 -0700985 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700986 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700988
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800989 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800990 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
991 mUpcomingActiveConfig.configId);
992 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993}
994
Ady Abraham53852a52019-05-28 18:07:44 -0700995void SurfaceFlinger::desiredActiveConfigChangeDone() {
996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
997 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
998 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700999
1000 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1001 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001002 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
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) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001470 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 =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001662 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001663 ? mPreviousPresentFences[0]
1664 : mPreviousPresentFences[1];
1665
1666 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1667}
1668
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001669void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001670 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.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001674 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001675 mPhaseOffsets->getOffsetThresholdForNextVsync()
1676 ? presentTime
1677 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001678}
1679
Dominik Laskowski22488f62019-03-28 09:53:04 -07001680void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001681 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001682 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001683 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001684 // calculate the expected present time once and use the cached
1685 // value throughout this frame to make sure all layers are
1686 // seeing this same value.
1687 populateExpectedPresentTime();
1688
Ady Abraham50204dd2019-07-19 15:47:11 -07001689 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1690 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1691 mHadDeviceComposition && frameMissed};
1692 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1693 mHadClientComposition && frameMissed};
1694
Alec Mouricc0fc602019-02-26 21:45:19 -08001695 if (frameMissed) {
1696 mFrameMissedCount++;
1697 mTimeStats->incrementMissedFrames();
1698 }
1699
Alec Mouri40189b02019-03-05 15:07:54 -08001700 if (hwcFrameMissed) {
1701 mHwcFrameMissedCount++;
1702 }
1703
1704 if (gpuFrameMissed) {
1705 mGpuFrameMissedCount++;
1706 }
1707
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001708 if (mUseSmart90ForVideo) {
1709 // This call is made each time SF wakes up and creates a new frame. It is part
1710 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001711 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001712 }
1713
Ady Abrahamb838aed2019-02-12 15:30:16 -08001714 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001715 break;
1716 }
1717
Ady Abraham4658e112019-07-22 13:07:26 -07001718 if (frameMissed && mPropagateBackpressure) {
1719 if ((hwcFrameMissed && !gpuFrameMissed) ||
1720 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001721 signalLayerUpdate();
1722 break;
1723 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001724 }
Dan Stoza50182882016-07-08 12:02:20 -07001725
Steven Thomas050b2c82017-03-06 11:45:16 -08001726 // Now that we're going to make it to the handleMessageTransaction()
1727 // call below it's safe to call updateVrFlinger(), which will
1728 // potentially trigger a display handoff.
1729 updateVrFlinger();
1730
Dan Stoza6b9454d2014-11-07 16:00:59 -08001731 bool refreshNeeded = handleMessageTransaction();
1732 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001733
1734 updateCursorAsync();
1735 updateInputFlinger();
1736
Dan Stoza58784442014-12-02 16:58:17 -08001737 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001738 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001739 // Signal a refresh if a transaction modified the window state,
1740 // a new buffer was latched, or if HWC has requested a full
1741 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001742 signalRefresh();
1743 }
1744 break;
1745 }
1746 case MessageQueue::REFRESH: {
1747 handleMessageRefresh();
1748 break;
1749 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001750 }
1751}
1752
Dan Stoza6b9454d2014-11-07 16:00:59 -08001753bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001754 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001755 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001756
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001757 bool flushedATransaction = flushTransactionQueues();
1758
1759 bool runHandleTransaction = transactionFlags &&
1760 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1761
1762 if (runHandleTransaction) {
1763 handleTransaction(eTransactionMask);
1764 } else {
1765 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001766 }
1767
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001768 if (transactionFlushNeeded()) {
1769 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001770 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001771
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001772 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001773}
1774
Mathias Agopian4fec8732012-06-29 14:12:52 -07001775void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001776 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001777
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001778 mRefreshPending = false;
1779
Lloyd Piqueab039b52019-02-13 14:22:42 -08001780 compositionengine::CompositionRefreshArgs refreshArgs;
1781 for (const auto& [_, display] : mDisplays) {
1782 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1783 }
1784 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1785 auto compositionLayer = layer->getCompositionLayer();
1786 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1787 });
1788
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001789 const bool repaintEverything = mRepaintEverything.exchange(false);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001790 mCompositionEngine->preComposition(refreshArgs);
Lloyd Pique074e8122018-07-26 12:57:23 -07001791 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001792 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001793 for (const auto& [token, display] : mDisplays) {
1794 beginFrame(display);
Lloyd Pique66d68602019-02-13 14:23:31 -08001795 display->getCompositionDisplay()->prepareFrame();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001796 doDebugFlashRegions(display, repaintEverything);
1797 doComposition(display, repaintEverything);
1798 }
1799
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001800 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001801
1802 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001803 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001804
Lloyd Pique66d68602019-02-13 14:23:31 -08001805 mHadClientComposition =
1806 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1807 auto& displayDevice = tokenDisplayPair.second;
1808 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1809 });
1810 mHadDeviceComposition =
1811 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1812 auto& displayDevice = tokenDisplayPair.second;
1813 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1814 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001815
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001816 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001817
David Sodman7e4ae112018-02-09 15:02:28 -08001818 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001819 if (mVisibleRegionsDirty) {
1820 mVisibleRegionsDirty = false;
1821 if (mTracingEnabled) {
1822 mTracing.notify("visibleRegionsDirty");
1823 }
1824 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001825
1826 if (mCompositionEngine->needsAnotherUpdate()) {
1827 signalLayerUpdate();
1828 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001830
David Sodmanfa9b2af2017-12-24 13:28:59 -08001831
1832bool SurfaceFlinger::handleMessageInvalidate() {
1833 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001834 bool refreshNeeded = handlePageFlip();
1835
Vishnu Nair4351ad52019-02-11 14:13:02 -08001836 if (mVisibleRegionsDirty) {
1837 computeLayerBounds();
1838 }
1839
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001840 for (auto& layer : mLayersPendingRefresh) {
1841 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001842 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001843 invalidateLayerStack(layer, visibleReg);
1844 }
1845 mLayersPendingRefresh.clear();
1846 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001847}
1848
David Sodman79bba0e2018-08-05 18:07:49 -07001849void SurfaceFlinger::calculateWorkingSet() {
1850 ATRACE_CALL();
1851 ALOGV(__FUNCTION__);
1852
Lloyd Piquef5275482019-01-29 18:42:42 -08001853 const bool updatingGeometryThisFrame = mGeometryInvalid;
1854 mGeometryInvalid = false;
1855
1856 {
1857 // Use a map so that we latch the state of each front-end layer once.
1858 std::unordered_map<compositionengine::LayerFE*, compositionengine::LayerFECompositionState*>
1859 uniqueVisibleLayers;
1860
1861 // Figure out which frontend layers are being composed, and build the unique
1862 // set of them (and the corresponding composition layer)
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863 for (const auto& [token, displayDevice] : mDisplays) {
1864 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquef5275482019-01-29 18:42:42 -08001865 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1866 uniqueVisibleLayers.insert(std::make_pair(&layer->getLayerFE(),
1867 &layer->getLayer().editState().frontEnd));
1868 }
1869 }
David Sodman79bba0e2018-08-05 18:07:49 -07001870
Lloyd Piquef5275482019-01-29 18:42:42 -08001871 // Update the composition state from each front-end layer.
1872 for (auto& [layerFE, state] : uniqueVisibleLayers) {
1873 layerFE->latchCompositionState(*state, updatingGeometryThisFrame);
1874 }
1875 }
1876
1877 if (CC_UNLIKELY(updatingGeometryThisFrame)) {
1878 for (const auto& [token, displayDevice] : mDisplays) {
1879 auto display = displayDevice->getCompositionDisplay();
Lloyd Piquea83776c2019-01-29 18:42:32 -08001880 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001881
Lloyd Piquea83776c2019-01-29 18:42:32 -08001882 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Lloyd Piquef5275482019-01-29 18:42:42 -08001883 // Assign a simple Z order sequence to each visible layer.
1884 layer->editState().z = zOrder++;
David Sodman79bba0e2018-08-05 18:07:49 -07001885 }
1886 }
1887 }
1888
Lloyd Piquef5275482019-01-29 18:42:42 -08001889 // Determine the color configuration of each output
Lloyd Pique32cbe282018-10-19 13:09:22 -07001890 for (const auto& [token, displayDevice] : mDisplays) {
1891 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001892
Lloyd Piquef5275482019-01-29 18:42:42 -08001893 ColorMode colorMode = ColorMode::NATIVE;
1894 Dataspace dataspace = Dataspace::UNKNOWN;
1895 RenderIntent renderIntent = RenderIntent::COLORIMETRIC;
1896 if (useColorManagement) {
1897 pickColorMode(displayDevice, &colorMode, &dataspace, &renderIntent);
1898 }
1899 display->setColorMode(colorMode, dataspace, renderIntent, mColorSpaceAgnosticDataspace);
1900 }
1901
1902 for (const auto& [token, displayDevice] : mDisplays) {
1903 auto display = displayDevice->getCompositionDisplay();
1904
1905 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1906 // Update the composition state of the output layer, as needed
1907 // recomputing it from the state given by the front-end layer.
1908 layer->updateCompositionState(updatingGeometryThisFrame);
1909 }
1910 }
1911
1912 for (const auto& [token, displayDevice] : mDisplays) {
1913 auto display = displayDevice->getCompositionDisplay();
1914
1915 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1916 // Send the updated state to the HWC, if appropriate.
1917 layer->writeStateToHWC(updatingGeometryThisFrame);
1918 }
1919 }
1920
1921 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1922 for (const auto& [token, displayDevice] : mDisplays) {
1923 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001924 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001925 }
Lloyd Piquef5275482019-01-29 18:42:42 -08001926 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001927 }
David Sodman79bba0e2018-08-05 18:07:49 -07001928}
1929
Lloyd Pique32cbe282018-10-19 13:09:22 -07001930void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1931 bool repaintEverything) {
1932 auto display = displayDevice->getCompositionDisplay();
1933 const auto& displayState = display->getState();
1934
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935 // is debugging enabled
1936 if (CC_LIKELY(!mDebugRegion))
1937 return;
1938
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001940 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001941 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001942 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001943 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001944 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001945 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001946
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001947 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948 }
1949 }
1950
Lloyd Pique32cbe282018-10-19 13:09:22 -07001951 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001952
1953 if (mDebugRegion > 1) {
1954 usleep(mDebugRegion * 1000);
1955 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001956
Lloyd Pique66d68602019-02-13 14:23:31 -08001957 displayDevice->getCompositionDisplay()->prepareFrame();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001958}
1959
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001960void SurfaceFlinger::logLayerStats() {
1961 ATRACE_CALL();
1962 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001963 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001964 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001965 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001966 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001967 }
1968 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001969
1970 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001971 }
1972}
1973
Ana Krulece588e312018-09-18 12:32:24 -07001974void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1975 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976 // Update queue of past composite+present times and determine the
1977 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001978 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001980 while (!getBE().mCompositePresentTimes.empty()) {
1981 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001982 // Cached values should have been updated before calling this method,
1983 // which helps avoid duplicate syscalls.
1984 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1985 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1986 break;
1987 }
1988 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001989 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990 }
1991
1992 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001993 while (getBE().mCompositePresentTimes.size() > 16) {
1994 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995 }
1996
Ana Krulece588e312018-09-18 12:32:24 -07001997 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001998}
1999
Ana Krulece588e312018-09-18 12:32:24 -07002000void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2001 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002002 // Integer division and modulo round toward 0 not -inf, so we need to
2003 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002004 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2005 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2006 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002007
Ana Krulec757f63a2019-01-25 10:46:18 -08002008 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002009 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002010 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002011 }
2012
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002013 // Snap the latency to a value that removes scheduling jitter from the
2014 // composition and present times, which often have >1ms of jitter.
2015 // Reducing jitter is important if an app attempts to extrapolate
2016 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002017 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002018 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002019 nsecs_t bias = stats.vsyncPeriod / 2;
2020 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2021 nsecs_t snappedCompositeToPresentLatency =
2022 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002023
David Sodman99974d22017-11-28 12:04:33 -08002024 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002025 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2026 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002027 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028}
2029
David Sodman2b406362017-12-15 13:33:47 -08002030void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 ATRACE_CALL();
2033 ALOGV("postComposition");
2034
Brian Anderson3546a3f2016-07-14 11:51:14 -07002035 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002036 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002037 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002038 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002039 }
2040
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002041 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002042 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043
David Sodman73beded2017-11-15 11:56:06 -08002044 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002045 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002046 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002047 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002048 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2049 ->getRenderSurface()
2050 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002051 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002052 } else {
2053 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2054 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055
David Sodman73beded2017-11-15 11:56:06 -08002056 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002057 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2058 mPreviousPresentFences[0] = displayDevice
2059 ? getHwComposer().getPresentFence(*displayDevice->getId())
2060 : Fence::NO_FENCE;
2061 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002062 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002063
Ana Krulece588e312018-09-18 12:32:24 -07002064 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002065 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066
Lloyd Piqueab039b52019-02-13 14:22:42 -08002067 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2068 // be sampled a little later than when we started doing work for this frame,
2069 // but that should be okay since updateCompositorTiming has snapping logic.
2070 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2071 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002072 CompositorTiming compositorTiming;
2073 {
David Sodman99974d22017-11-28 12:04:33 -08002074 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2075 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002076 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077
Robert Carr2047fae2016-11-28 14:09:09 -08002078 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002079 bool frameLatched =
2080 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2081 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002082 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002083 recordBufferingStats(layer->getName().string(),
2084 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002085 }
Robert Carr2047fae2016-11-28 14:09:09 -08002086 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002087
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002088 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002089 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002090 }
2091
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002092 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002093 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2094 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002095 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002096 }
2097 }
2098
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002099 if (mAnimCompositionPending) {
2100 mAnimCompositionPending = false;
2101
Brian Anderson4e606e32017-03-16 15:34:57 -07002102 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002103 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002104 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002105 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 // The HWC doesn't support present fences, so use the refresh
2107 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002108 const nsecs_t presentTime =
2109 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002110 mAnimFrameTracker.setActualPresentTime(presentTime);
2111 }
2112 mAnimFrameTracker.advanceFrame();
2113 }
Dan Stozab90cf072015-03-05 11:05:59 -08002114
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002115 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002116 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002117 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002118 }
2119
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002120 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002121
Lloyd Pique32cbe282018-10-19 13:09:22 -07002122 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2123 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002124 return;
2125 }
2126
2127 nsecs_t currentTime = systemTime();
2128 if (mHasPoweredOff) {
2129 mHasPoweredOff = false;
2130 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002131 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002132 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002133 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2134 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002135 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002136 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002137 }
David Sodman4a36e932017-11-07 14:29:47 -08002138 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002139 }
David Sodman4a36e932017-11-07 14:29:47 -08002140 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002141
2142 {
2143 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002144 if (mTexturePool.size() < mTexturePoolSize) {
2145 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002146 const size_t offset = mTexturePool.size();
2147 mTexturePool.resize(mTexturePoolSize);
2148 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2149 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002150 } else if (mTexturePool.size() > mTexturePoolSize) {
2151 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2152 const size_t offset = mTexturePoolSize;
2153 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2154 mTexturePool.resize(mTexturePoolSize);
2155 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002156 }
2157 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002158
Ady Abrahambe0f9482019-04-24 15:41:53 -07002159 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002160 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002161
Kevin DuBois413287f2019-02-25 08:46:47 -08002162 if (mLumaSampling && mRegionSamplingThread) {
2163 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002164 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002165
2166 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2167 // side-effect of getTotalSize(), so we check that again here
2168 if (ATRACE_ENABLED()) {
2169 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2170 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002171}
2172
Vishnu Nair4351ad52019-02-11 14:13:02 -08002173void SurfaceFlinger::computeLayerBounds() {
2174 for (const auto& pair : mDisplays) {
2175 const auto& displayDevice = pair.second;
2176 const auto display = displayDevice->getCompositionDisplay();
2177 for (const auto& layer : mDrawingState.layersSortedByZ) {
2178 // only consider the layers on the given layer stack
2179 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002180 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002181 }
2182
2183 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2184 }
2185 }
2186}
2187
Mathias Agopiancd60f992012-08-16 16:28:27 -07002188void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002189 ATRACE_CALL();
2190 ALOGV("rebuildLayerStacks");
2191
Mathias Agopiancd60f992012-08-16 16:28:27 -07002192 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002193 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002194 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002195 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002196
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002197 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002198 const auto& displayDevice = pair.second;
2199 auto display = displayDevice->getCompositionDisplay();
2200 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002201 Region opaqueRegion;
2202 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002203 compositionengine::Output::OutputLayers layersSortedByZ;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002204 compositionengine::Output::ReleasedLayers releasedLayers;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002205 Vector<sp<Layer>> deprecated_layersSortedByZ;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 const ui::Transform& tr = displayState.transform;
2207 const Rect bounds = displayState.bounds;
2208 if (displayState.isEnabled) {
2209 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210
Jeff Sharkey76488112017-02-27 14:15:18 -07002211 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002212 auto compositionLayer = layer->getCompositionLayer();
2213 if (compositionLayer == nullptr) {
2214 return;
2215 }
2216
Lloyd Pique32cbe282018-10-19 13:09:22 -07002217 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002218 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2219 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2220
Lloyd Pique07e33212018-12-18 16:33:37 -08002221 bool needsOutputLayer = false;
2222
Lloyd Piqueef36b002019-01-23 17:52:04 -08002223 if (display->belongsInOutput(layer->getLayerStack(),
2224 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002225 Region drawRegion(tr.transform(
2226 layer->visibleNonTransparentRegion));
2227 drawRegion.andSelf(bounds);
2228 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002229 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002230 }
Chia-I Wu83806892017-11-16 10:50:20 -08002231 }
2232
Lloyd Pique07e33212018-12-18 16:33:37 -08002233 if (needsOutputLayer) {
2234 layersSortedByZ.emplace_back(
2235 display->getOrCreateOutputLayer(displayId, compositionLayer,
2236 layerFE));
2237 deprecated_layersSortedByZ.add(layer);
2238
2239 auto& outputLayerState = layersSortedByZ.back()->editState();
2240 outputLayerState.visibleRegion =
2241 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2242 } else if (displayId) {
2243 // For layers that are being removed from a HWC display,
2244 // and that have queued frames, add them to a a list of
2245 // released layers so we can properly set a fence.
2246 bool hasExistingOutputLayer =
2247 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2248 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2249 mLayersWithQueuedFrames.cend(),
2250 layer) != mLayersWithQueuedFrames.cend();
2251
2252 if (hasExistingOutputLayer && hasQueuedFrames) {
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002253 releasedLayers.push_back(layer);
Chia-I Wu83806892017-11-16 10:50:20 -08002254 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002255 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002256 });
2257 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002258
2259 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002260 display->setReleasedLayers(std::move(releasedLayers));
Lloyd Piquecc01a452018-12-04 17:24:00 -08002261
2262 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002263
2264 Region undefinedRegion{bounds};
2265 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2266
2267 display->editState().undefinedRegion = undefinedRegion;
2268 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002270 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002271}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002272
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002273// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002274// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002275// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002276// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002277// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002278// The returned HDR data space is one of
2279// - Dataspace::UNKNOWN
2280// - Dataspace::BT2020_HLG
2281// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002282Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2283 Dataspace* outHdrDataSpace,
2284 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002285 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002286 *outHdrDataSpace = Dataspace::UNKNOWN;
2287
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002288 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002289 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002290 case Dataspace::V0_SCRGB:
2291 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002292 case Dataspace::BT2020:
2293 case Dataspace::BT2020_ITU:
2294 case Dataspace::BT2020_LINEAR:
2295 case Dataspace::DISPLAY_BT2020:
2296 bestDataSpace = Dataspace::DISPLAY_BT2020;
2297 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002298 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002299 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002301 case Dataspace::BT2020_PQ:
2302 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002303 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002304 *outHdrDataSpace = Dataspace::BT2020_PQ;
Lloyd Piquef5275482019-01-29 18:42:42 -08002305 *outIsHdrClientComposition =
2306 layer->getCompositionLayer()->getState().frontEnd.forceClientComposition;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002308 case Dataspace::BT2020_HLG:
2309 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002310 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311 // When there's mixed PQ content and HLG content, we set the HDR
2312 // data space to be BT2020_PQ and convert HLG to PQ.
2313 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2314 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002315 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002316 break;
2317 default:
2318 break;
2319 }
Romain Guy54f154a2017-10-24 21:40:32 +01002320 }
2321
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002322 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002323}
2324
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002325// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002326void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2327 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002328 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2329 *outMode = ColorMode::NATIVE;
2330 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002331 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002333 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002334
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002336 bool isHdrClientComposition = false;
2337 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002338
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002339 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2340
Peiyong Lina3ea5592019-02-10 14:45:00 -08002341 switch (mForceColorMode) {
2342 case ColorMode::SRGB:
2343 bestDataSpace = Dataspace::V0_SRGB;
2344 break;
2345 case ColorMode::DISPLAY_P3:
2346 bestDataSpace = Dataspace::DISPLAY_P3;
2347 break;
2348 default:
2349 break;
2350 }
2351
Peiyong Lindfde5112018-06-05 10:58:41 -07002352 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002353 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2354 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002355 if (isHdr) {
2356 bestDataSpace = hdrDataSpace;
2357 }
2358
Chia-I Wu0d711262018-05-21 15:19:35 -07002359 RenderIntent intent;
2360 switch (mDisplayColorSetting) {
2361 case DisplayColorSetting::MANAGED:
2362 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002363 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002364 break;
2365 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002366 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002367 break;
2368 default: // vendor display color setting
2369 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2370 break;
2371 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002372
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002373 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002374}
2375
Lloyd Pique32cbe282018-10-19 13:09:22 -07002376void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2377 auto display = displayDevice->getCompositionDisplay();
2378 const auto& displayState = display->getState();
2379
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002380 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002381 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2382 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002383
David Sodmanfa9b2af2017-12-24 13:28:59 -08002384 // If nothing has changed (!dirty), don't recompose.
2385 // If something changed, but we don't currently have any visible layers,
2386 // and didn't when we last did a composition, then skip it this time.
2387 // The second rule does two things:
2388 // - When all layers are removed from a display, we'll emit one black
2389 // frame, then nothing more until we get new layers.
2390 // - When a display is created with a private layer stack, we won't
2391 // emit any black frames until a layer is added to the layer stack.
2392 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002393
Dominik Laskowski075d3172018-05-24 15:50:06 -07002394 const char flagPrefix[] = {'-', '+'};
2395 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002396 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2397 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2398 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2399 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002400
Lloyd Pique31cb2942018-10-19 17:23:03 -07002401 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002402
David Sodmanfa9b2af2017-12-24 13:28:59 -08002403 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002404 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002405 }
2406}
2407
Lloyd Pique32cbe282018-10-19 13:09:22 -07002408void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002409 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002410 ALOGV("doComposition");
2411
Lloyd Pique32cbe282018-10-19 13:09:22 -07002412 auto display = displayDevice->getCompositionDisplay();
2413 const auto& displayState = display->getState();
2414
2415 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002416 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002417 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002418
David Sodmanfa9b2af2017-12-24 13:28:59 -08002419 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002420 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002421
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002423 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002424 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002425 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002426}
2427
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428void SurfaceFlinger::postFrame()
2429{
2430 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 const auto display = getDefaultDisplayDeviceLocked();
2432 if (display && getHwComposer().isConnected(*display->getId())) {
2433 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002434 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2435 logFrameStats();
2436 }
2437 }
2438}
2439
Lloyd Pique32cbe282018-10-19 13:09:22 -07002440void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002441 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002442 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002443
Lloyd Pique32cbe282018-10-19 13:09:22 -07002444 auto display = displayDevice->getCompositionDisplay();
2445 const auto& displayState = display->getState();
2446 const auto displayId = display->getId();
2447
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 if (displayId) {
2450 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002451 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002452 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002453 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002454 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002455 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002456
Chia-I Wu7b549592017-11-15 09:14:57 -08002457 // The layer buffer from the previous frame (if any) is released
2458 // by HWC only when the release fence from this frame (if any) is
2459 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002460 if (layer->getState().hwc) {
2461 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002462 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002463 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2464 usedClientComposition =
2465 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002466 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002467
2468 // If the layer was client composited in the previous frame, we
2469 // need to merge with the previous client target acquire fence.
2470 // Since we do not track that, always merge with the current
2471 // client target acquire fence when it is available, even though
2472 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002473 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002474 releaseFence =
2475 Fence::merge("LayerRelease", releaseFence,
2476 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002477 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002478
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002479 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002480 }
Chia-I Wu83806892017-11-16 10:50:20 -08002481
2482 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002483 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002484 // supply them with the present fence.
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002485 auto releasedLayers = display->takeReleasedLayers();
2486 if (!releasedLayers.empty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002487 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002488 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Piquec7ef21b2019-01-29 18:43:00 -08002489 for (auto& weakLayer : releasedLayers) {
2490 if (auto layer = weakLayer.promote(); layer != nullptr) {
2491 layer->onLayerDisplayed(presentFence);
2492 }
Chia-I Wu83806892017-11-16 10:50:20 -08002493 }
2494 }
2495
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 if (displayId) {
2497 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002498 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002499 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002500}
2501
Mathias Agopian87baae12012-07-31 12:38:26 -07002502void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002503{
Mathias Agopian841cde52012-03-01 15:44:37 -08002504 ATRACE_CALL();
2505
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002506 // here we keep a copy of the drawing state (that is the state that's
2507 // going to be overwritten by handleTransactionLocked()) outside of
2508 // mStateLock so that the side-effects of the State assignment
2509 // don't happen with mStateLock held (which can cause deadlocks).
2510 State drawingState(mDrawingState);
2511
Mathias Agopianca4d3602011-05-19 15:38:14 -07002512 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002513 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002514
Mathias Agopianca4d3602011-05-19 15:38:14 -07002515 // Here we're guaranteed that some transaction flags are set
2516 // so we can call handleTransactionLocked() unconditionally.
2517 // We call getTransactionFlags(), which will also clear the flags,
2518 // with mStateLock held to guarantee that mCurrentState won't change
2519 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002520
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002521 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002523 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002524
Mathias Agopianca4d3602011-05-19 15:38:14 -07002525 mDebugInTransaction = 0;
2526 invalidateHwcGeometry();
2527 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002528}
2529
Lloyd Piqueba04e622017-12-14 17:11:26 -08002530void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2531 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 const std::optional<DisplayIdentificationInfo> info =
2533 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002534
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002536 continue;
2537 }
2538
Lloyd Piqueba04e622017-12-14 17:11:26 -08002539 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002541 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 mPhysicalDisplayTokens[info->id] = new BBinder();
2543 DisplayDeviceState state;
2544 state.displayId = info->id;
2545 state.isSecure = true; // All physical displays are currently considered secure.
2546 state.displayName = info->name;
2547 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2548 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002549 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002550 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002551 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002552
Dominik Laskowski075d3172018-05-24 15:50:06 -07002553 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2554 if (index >= 0) {
2555 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2556 mInterceptor->saveDisplayDeletion(state.sequenceId);
2557 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002558 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002560 }
2561
2562 processDisplayChangesLocked();
2563 }
2564
2565 mPendingHotplugEvents.clear();
2566}
2567
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002568void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002569 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2570 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002571}
2572
Lloyd Pique99d3da52018-01-22 17:48:03 -08002573sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002574 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002575 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002576 const sp<IGraphicBufferProducer>& producer) {
2577 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002578 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002580 creationArgs.isSecure = state.isSecure;
2581 creationArgs.displaySurface = dispSurface;
2582 creationArgs.hasWideColorGamut = false;
2583 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002584
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002585 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 creationArgs.isPrimary = isInternalDisplay;
2587
2588 if (useColorManagement && displayId) {
2589 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002590 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002591 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002592 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002593 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002594
Dominik Laskowski7e045462018-05-30 13:02:02 -07002595 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002597 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002598 }
tangrobin6753a022018-08-10 10:58:54 +08002599 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002600
Dominik Laskowski075d3172018-05-24 15:50:06 -07002601 if (displayId) {
2602 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002603 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002604 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002605 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002606
Lloyd Pique90c115d2018-09-18 21:39:42 -07002607 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002608 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002609 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002610
Lloyd Pique99d3da52018-01-22 17:48:03 -08002611 // Make sure that composition can never be stalled by a virtual display
2612 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002613 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002614 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002615 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2616 }
2617
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 creationArgs.displayInstallOrientation =
2619 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002620
Lloyd Pique99d3da52018-01-22 17:48:03 -08002621 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002622 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002623
Lloyd Pique90c115d2018-09-18 21:39:42 -07002624 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002625
2626 if (maxFrameBufferAcquiredBuffers >= 3) {
2627 nativeWindowSurface->preallocateBuffers();
2628 }
2629
2630 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002631 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002632 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002633 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002634 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002635 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002636 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
Lloyd Piquef5275482019-01-29 18:42:42 -08002637 RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002638 if (!state.isVirtual()) {
2639 LOG_ALWAYS_FATAL_IF(!displayId);
2640 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002641 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002643 display->setLayerStack(state.layerStack);
2644 display->setProjection(state.orientation, state.viewport, state.frame);
2645 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002647 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002648}
2649
Lloyd Pique347200f2017-12-14 17:00:15 -08002650void SurfaceFlinger::processDisplayChangesLocked() {
2651 // here we take advantage of Vector's copy-on-write semantics to
2652 // improve performance by skipping the transaction entirely when
2653 // know that the lists are identical
2654 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2655 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2656 if (!curr.isIdenticalTo(draw)) {
2657 mVisibleRegionsDirty = true;
2658 const size_t cc = curr.size();
2659 size_t dc = draw.size();
2660
2661 // find the displays that were removed
2662 // (ie: in drawing state but not in current state)
2663 // also handle displays that changed
2664 // (ie: displays that are in both lists)
2665 for (size_t i = 0; i < dc;) {
2666 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2667 if (j < 0) {
2668 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002669 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002670 // Save display ID before disconnecting.
2671 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002672 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002673
2674 if (!display->isVirtual()) {
2675 LOG_ALWAYS_FATAL_IF(!displayId);
2676 dispatchDisplayHotplugEvent(displayId->value, false);
2677 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002678 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002679
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002680 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002681 } else {
2682 // this display is in both lists. see if something changed.
2683 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002684 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2686 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2687 if (state_binder != draw_binder) {
2688 // changing the surface is like destroying and
2689 // recreating the DisplayDevice, so we just remove it
2690 // from the drawing state, so that it get re-added
2691 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002692 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002693 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002694 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002695 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002696 mDrawingState.displays.removeItemsAt(i);
2697 dc--;
2698 // at this point we must loop to the next item
2699 continue;
2700 }
2701
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002702 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002703 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002705 }
2706 if ((state.orientation != draw[i].orientation) ||
2707 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
2710 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002711 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002712 }
2713 }
2714 }
2715 ++i;
2716 }
2717
2718 // find displays that were added
2719 // (ie: in current state but not in drawing state)
2720 for (size_t i = 0; i < cc; i++) {
2721 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2722 const DisplayDeviceState& state(curr[i]);
2723
Lloyd Pique542307f2018-10-19 13:24:08 -07002724 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 sp<IGraphicBufferProducer> producer;
2726 sp<IGraphicBufferProducer> bqProducer;
2727 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002728 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002729
Dominik Laskowski075d3172018-05-24 15:50:06 -07002730 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002731 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002732 // Virtual displays without a surface are dormant:
2733 // they have external state (layer stack, projection,
2734 // etc.) but no internal state (i.e. a DisplayDevice).
2735 if (state.surface != nullptr) {
2736 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002737 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 int width = 0;
2739 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2740 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2741 int height = 0;
2742 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2743 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2744 int intFormat = 0;
2745 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2746 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002747 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002748
Dominik Laskowski075d3172018-05-24 15:50:06 -07002749 displayId =
2750 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 }
2752
2753 // TODO: Plumb requested format back up to consumer
2754
2755 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002756 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002757 bqProducer, bqConsumer,
2758 state.displayName);
2759
2760 dispSurface = vds;
2761 producer = vds;
2762 }
2763 } else {
2764 ALOGE_IF(state.surface != nullptr,
2765 "adding a supported display, but rendering "
2766 "surface is provided (%p), ignoring it",
2767 state.surface.get());
2768
Dominik Laskowski075d3172018-05-24 15:50:06 -07002769 displayId = state.displayId;
2770 LOG_ALWAYS_FATAL_IF(!displayId);
2771 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002772 producer = bqProducer;
2773 }
2774
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002775 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002777 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002778 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002780 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002781 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002782 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 }
2784 }
2785 }
2786 }
2787 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002788
2789 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002790}
2791
Mathias Agopian87baae12012-07-31 12:38:26 -07002792void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002793{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002794 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2795
Dan Stoza7dde5992015-05-22 09:51:44 -07002796 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002797 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2798 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002799 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002800
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801 /*
2802 * Traversal of the children
2803 * (perform the transaction for each of them if needed)
2804 */
2805
Marissa Wall06255332019-03-27 13:48:27 -07002806 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002807 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002809 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810
2811 const uint32_t flags = layer->doTransaction(0);
2812 if (flags & Layer::eVisibleRegion)
2813 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002814
2815 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002816 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002817 }
Robert Carr2047fae2016-11-28 14:09:09 -08002818 });
Marissa Wall06255332019-03-27 13:48:27 -07002819 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 }
2821
2822 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002823 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 */
2825
Mathias Agopiane57f2922012-08-09 16:29:12 -07002826 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002827 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002828 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002829 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002831 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002832 // The transform hint might have changed for some layers
2833 // (either because a display has changed, or because a layer
2834 // as changed).
2835 //
2836 // Walk through all the layers in currentLayers,
2837 // and update their transform hint.
2838 //
2839 // If a layer is visible only on a single display, then that
2840 // display is used to calculate the hint, otherwise we use the
2841 // default display.
2842 //
2843 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2844 // the hint is set before we acquire a buffer from the surface texture.
2845 //
2846 // NOTE: layer transactions have taken place already, so we use their
2847 // drawing state. However, SurfaceFlinger's own transaction has not
2848 // happened yet, so we must use the current state layer list
2849 // (soon to become the drawing state list).
2850 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002851 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002852 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002853 bool first = true;
2854 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002855 // NOTE: we rely on the fact that layers are sorted by
2856 // layerStack first (so we don't have to traverse the list
2857 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002858 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002859 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002860 currentlayerStack = layerStack;
2861 // figure out if this layerstack is mirrored
2862 // (more than one display) if so, pick the default display,
2863 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002864 hintDisplay = nullptr;
2865 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002866 if (display->getCompositionDisplay()
2867 ->belongsInOutput(layer->getLayerStack(),
2868 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 if (hintDisplay) {
2870 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002871 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002872 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002873 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002874 }
2875 }
2876 }
2877 }
Chet Haase91d25932013-04-11 15:24:55 -07002878
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002879 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002880 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2881 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002882
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002883 // could be null when this layer is using a layerStack
2884 // that is not visible on any display. Also can occur at
2885 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002886 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002887 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002888
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002889 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002890 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002891 if (hintDisplay) {
2892 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002893 }
Robert Carr2047fae2016-11-28 14:09:09 -08002894
2895 first = false;
2896 });
Mathias Agopian84300952012-11-21 16:02:13 -08002897 }
2898
2899
Mathias Agopian3559b072012-08-15 13:46:03 -07002900 /*
2901 * Perform our own transaction if needed
2902 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903
2904 if (mLayersAdded) {
2905 mLayersAdded = false;
2906 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002907 mVisibleRegionsDirty = true;
2908 }
2909
2910 // some layers might have been removed, so
2911 // we need to update the regions they're exposing.
2912 if (mLayersRemoved) {
2913 mLayersRemoved = false;
2914 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002915 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002916 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002917 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002919 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002920 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002921 }
Robert Carr2047fae2016-11-28 14:09:09 -08002922 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002923 }
2924
Vishnu Nairec0ab382019-02-13 15:32:56 -08002925 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002927}
2928
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002929void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002930 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002931 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002932 return;
2933 }
2934
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002935 if (mVisibleRegionsDirty || mInputInfoChanged) {
2936 mInputInfoChanged = false;
2937 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002938 } else if (mInputWindowCommands.syncInputWindows) {
2939 // If the caller requested to sync input windows, but there are no
2940 // changes to input windows, notify immediately.
2941 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002942 }
2943
2944 executeInputWindowCommands();
2945}
2946
2947void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002948 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002949
2950 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2951 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002952 // When calculating the screen bounds we ignore the transparent region since it may
2953 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002954 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002955 }
2956 });
chaviw291d88a2019-02-14 10:33:58 -08002957
2958 mInputFlinger->setInputWindows(inputHandles,
2959 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2960 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002961}
2962
Vishnu Nairec0ab382019-02-13 15:32:56 -08002963void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002964 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002965 mPendingInputWindowCommands.clear();
2966}
2967
chaviwfbe5d9c2018-12-26 12:23:37 -08002968void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002969 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2970 if (transferTouchFocusCommand.fromToken != nullptr &&
2971 transferTouchFocusCommand.toToken != nullptr &&
2972 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2973 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2974 transferTouchFocusCommand.toToken);
2975 }
2976 }
2977
2978 mInputWindowCommands.clear();
2979}
2980
Riley Andrews03414a12014-07-01 14:22:59 -07002981void SurfaceFlinger::updateCursorAsync()
2982{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002983 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002984 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002985 continue;
2986 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002988 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2989 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002990 }
2991 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002992}
2993
chaviw61626f22018-11-15 16:26:27 -08002994void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2995 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08002996 bool ignored = false;
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002997 layer->latchBuffer(ignored, systemTime(), 0 /* expectedPresentTime */);
chaviw61626f22018-11-15 16:26:27 -08002998 }
2999 layer->releasePendingBuffer(systemTime());
3000}
3001
Mathias Agopian4fec8732012-06-29 14:12:52 -07003002void SurfaceFlinger::commitTransaction()
3003{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003004 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003005 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 for (const auto& l : mLayersPendingRemoval) {
3007 recordBufferingStats(l->getName().string(),
3008 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003009
Lloyd Pique07e33212018-12-18 16:33:37 -08003010 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003011 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003012 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003013 }
chaviw74d90ad2019-04-26 14:45:26 -07003014
3015 // If the layer has been removed and has no parent, then it will not be reachable
3016 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3017 // ensure we can copy its current to drawing state.
3018 if (!l->getParent()) {
3019 mOffscreenLayers.emplace(l.get());
3020 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003021 }
3022 mLayersPendingRemoval.clear();
3023 }
3024
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003025 // If this transaction is part of a window animation then the next frame
3026 // we composite should be considered an animation as well.
3027 mAnimCompositionPending = mAnimTransactionPending;
3028
Nataniel Borges2b796da2019-02-15 13:32:18 -08003029 withTracingLock([&]() {
3030 mDrawingState = mCurrentState;
3031 // clear the "changed" flags in current state
3032 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003033
chaviw74d90ad2019-04-26 14:45:26 -07003034 mDrawingState.traverseInZOrder([&](Layer* layer) {
3035 layer->commitChildList();
3036
3037 // If the layer can be reached when traversing mDrawingState, then the layer is no
3038 // longer offscreen. Remove the layer from the offscreenLayer set.
3039 if (mOffscreenLayers.count(layer)) {
3040 mOffscreenLayers.erase(layer);
3041 }
3042 });
3043
3044 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003045 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003046
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003047 mTransactionPending = false;
3048 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003049 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050}
3051
Nataniel Borges2b796da2019-02-15 13:32:18 -08003052void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3053 if (mTracingEnabledChanged) {
3054 mTracingEnabled = mTracing.isEnabled();
3055 mTracingEnabledChanged = false;
3056 }
3057
3058 // Synchronize with Tracing thread
3059 std::unique_lock<std::mutex> lock;
3060 if (mTracingEnabled) {
3061 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3062 }
3063
3064 lockedOperation();
3065
3066 // Synchronize with Tracing thread
3067 if (mTracingEnabled) {
3068 lock.unlock();
3069 }
3070}
3071
chaviw74d90ad2019-04-26 14:45:26 -07003072void SurfaceFlinger::commitOffscreenLayers() {
3073 for (Layer* offscreenLayer : mOffscreenLayers) {
3074 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3075 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3076 if (!trFlags) return;
3077
3078 layer->doTransaction(0);
3079 layer->commitChildList();
3080 });
3081 }
3082}
3083
Lloyd Pique32cbe282018-10-19 13:09:22 -07003084void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003085 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003086 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003087 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003088
Lloyd Pique32cbe282018-10-19 13:09:22 -07003089 auto display = displayDevice->getCompositionDisplay();
3090
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003091 Region aboveOpaqueLayers;
3092 Region aboveCoveredLayers;
3093 Region dirty;
3094
Mathias Agopian87baae12012-07-31 12:38:26 -07003095 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003096
Robert Carr2047fae2016-11-28 14:09:09 -08003097 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003098 // start with the whole surface at its current location
3099 const Layer::State& s(layer->getDrawingState());
3100
Jesse Hall01e29052013-02-19 16:13:35 -08003101 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003102 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003103 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003104 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003105
Mathias Agopianab028732010-03-16 16:41:46 -07003106 /*
3107 * opaqueRegion: area of a surface that is fully opaque.
3108 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003109 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003110
3111 /*
3112 * visibleRegion: area of a surface that is visible on screen
3113 * and not fully transparent. This is essentially the layer's
3114 * footprint minus the opaque regions above it.
3115 * Areas covered by a translucent surface are considered visible.
3116 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003117 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003118
3119 /*
3120 * coveredRegion: area of a surface that is covered by all
3121 * visible regions above it (which includes the translucent areas).
3122 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003123 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003124
Jesse Halla8026d22012-09-25 13:25:04 -07003125 /*
3126 * transparentRegion: area of a surface that is hinted to be completely
3127 * transparent. This is only used to tell when the layer has no visible
3128 * non-transparent regions and can be removed from the layer list. It
3129 * does not affect the visibleRegion of this layer or any layers
3130 * beneath it. The hint may not be correct if apps don't respect the
3131 * SurfaceView restrictions (which, sadly, some don't).
3132 */
3133 Region transparentRegion;
3134
Mathias Agopianab028732010-03-16 16:41:46 -07003135
3136 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003137 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003138 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003139 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003140
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003142 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003143 if (!visibleRegion.isEmpty()) {
3144 // Remove the transparent area from the visible region
3145 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003146 if (tr.preserveRects()) {
3147 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003148 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003149 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003150 // transformation too complex, can't do the
3151 // transparent region optimization.
3152 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003153 }
Mathias Agopianab028732010-03-16 16:41:46 -07003154 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155
Mathias Agopianab028732010-03-16 16:41:46 -07003156 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003157 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003158 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003159 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003160 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003161 // the opaque region is the layer's footprint
3162 opaqueRegion = visibleRegion;
3163 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003164 }
3165 }
3166
Robert Carre5f4f692018-01-12 13:12:28 -08003167 if (visibleRegion.isEmpty()) {
3168 layer->clearVisibilityRegions();
3169 return;
3170 }
3171
Mathias Agopianab028732010-03-16 16:41:46 -07003172 // Clip the covered region to the visible region
3173 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3174
3175 // Update aboveCoveredLayers for next (lower) layer
3176 aboveCoveredLayers.orSelf(visibleRegion);
3177
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 // subtract the opaque region covered by the layers above us
3179 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180
3181 // compute this layer's dirty region
3182 if (layer->contentDirty) {
3183 // we need to invalidate the whole region
3184 dirty = visibleRegion;
3185 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003186 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003187 layer->contentDirty = false;
3188 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003189 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003190 * the exposed region consists of two components:
3191 * 1) what's VISIBLE now and was COVERED before
3192 * 2) what's EXPOSED now less what was EXPOSED before
3193 *
3194 * note that (1) is conservative, we start with the whole
3195 * visible region but only keep what used to be covered by
3196 * something -- which mean it may have been exposed.
3197 *
3198 * (2) handles areas that were not covered by anything but got
3199 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003200 */
Mathias Agopianab028732010-03-16 16:41:46 -07003201 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003202 const Region oldVisibleRegion = layer->visibleRegion;
3203 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003204 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3205 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 }
3207 dirty.subtractSelf(aboveOpaqueLayers);
3208
3209 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003210 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211
Mathias Agopianab028732010-03-16 16:41:46 -07003212 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003214
Jesse Halla8026d22012-09-25 13:25:04 -07003215 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 layer->setVisibleRegion(visibleRegion);
3217 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003218 layer->setVisibleNonTransparentRegion(
3219 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003220 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003221
Mathias Agopian87baae12012-07-31 12:38:26 -07003222 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223}
3224
Chia-I Wuab0c3192017-08-01 11:29:00 -07003225void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003226 for (const auto& [token, displayDevice] : mDisplays) {
3227 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003228 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003229 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003230 }
3231 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003232}
3233
Dan Stoza6b9454d2014-11-07 16:00:59 -08003234bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235{
Ady Abraham09bd3922019-04-08 10:44:56 -07003236 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003237 ALOGV("handlePageFlip");
3238
Brian Andersond6927fb2016-07-23 23:37:30 -07003239 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240
Mathias Agopian4fec8732012-06-29 14:12:52 -07003241 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003242 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003243 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003244
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003245 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3246
Eric Penner51c59cd2014-07-28 19:51:58 -07003247 // Store the set of layers that need updates. This set must not change as
3248 // buffers are being latched, as this could result in a deadlock.
3249 // Example: Two producers share the same command stream and:
3250 // 1.) Layer 0 is latched
3251 // 2.) Layer 0 gets a new frame
3252 // 2.) Layer 1 gets a new frame
3253 // 3.) Layer 1 is latched.
3254 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3255 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003256 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003257 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003258 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003259 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003260 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003261 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003262 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003263 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003264 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003265 } else {
3266 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003267 }
Robert Carr2047fae2016-11-28 14:09:09 -08003268 });
3269
Lloyd Piquef2c79392018-12-20 16:23:33 -08003270 if (!mLayersWithQueuedFrames.empty()) {
3271 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3272 // writes to Layer current state. See also b/119481871
3273 Mutex::Autolock lock(mStateLock);
3274
3275 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003276 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003277 mLayersPendingRefresh.push_back(layer);
3278 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003279 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003280 if (layer->isBufferLatched()) {
3281 newDataLatched = true;
3282 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003283 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003284 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003285
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003286 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003287
3288 // If we will need to wake up at some time in the future to deal with a
3289 // queued frame that shouldn't be displayed during this vsync period, wake
3290 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003291 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003292 signalLayerUpdate();
3293 }
3294
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003295 // enter boot animation on first buffer latch
3296 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3297 ALOGI("Enter boot animation");
3298 mBootStage = BootStage::BOOTANIMATION;
3299 }
3300
Dan Stoza6b9454d2014-11-07 16:00:59 -08003301 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003302 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303}
3304
Mathias Agopianad456f92011-01-13 17:53:01 -08003305void SurfaceFlinger::invalidateHwcGeometry()
3306{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003307 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003308}
3309
Lloyd Pique32cbe282018-10-19 13:09:22 -07003310void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003311 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003312 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003313 // We only need to actually compose the display if:
3314 // 1) It is being handled by hardware composer, which may need this to
3315 // keep its virtual display state machine in sync, or
3316 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003317 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003318 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003319 return;
3320 }
3321
Dan Stoza9e56aa02015-11-02 13:00:03 -08003322 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003323 base::unique_fd readyFence;
3324 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003325
3326 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003327 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003328}
3329
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003330bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3331 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003332 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003333 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003334
Lloyd Pique32cbe282018-10-19 13:09:22 -07003335 auto display = displayDevice->getCompositionDisplay();
3336 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003337 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003338 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003339 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003340
3341 const Region bounds(displayState.bounds);
3342 const DisplayRenderArea renderArea(displayDevice);
Ady Abraham50204dd2019-07-19 15:47:11 -07003343 const TracedOrdinal<bool> hasClientComposition = {"hasClientComposition",
Lloyd Pique66d68602019-02-13 14:23:31 -08003344 displayState.usesClientComposition};
Chia-I Wu8e50e692018-05-04 10:12:37 -07003345 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003346
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003347 renderengine::DisplaySettings clientCompositionDisplay;
3348 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3349 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003350 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003351
Dan Stoza9e56aa02015-11-02 13:00:03 -08003352 if (hasClientComposition) {
3353 ALOGV("hasClientComposition");
3354
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003355 if (displayDevice->isPrimary() && supportProtectedContent) {
3356 bool needsProtected = false;
3357 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3358 // If the layer is a protected layer, mark protected context is needed.
3359 if (layer->isProtected()) {
3360 needsProtected = true;
3361 break;
3362 }
3363 }
Peiyong Lin52010312019-05-02 14:22:16 -07003364 if (needsProtected != renderEngine.isProtected()) {
3365 renderEngine.useProtectedContext(needsProtected);
3366 }
3367 if (needsProtected != display->getRenderSurface()->isProtected() &&
3368 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003369 display->getRenderSurface()->setProtected(needsProtected);
3370 }
3371 }
3372
Alec Mouri6338c9d2019-02-07 16:57:51 -08003373 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003374
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003375 if (buf == nullptr) {
3376 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3377 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003378 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003379 return false;
3380 }
3381
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003382 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3383 clientCompositionDisplay.clip = displayState.scissor;
3384 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003385 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003386 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003387
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003388 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003389 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003390 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003391 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003392 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003393 clientCompositionDisplay.outputDataspace = outputDataspace;
3394 clientCompositionDisplay.maxLuminance =
3395 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003396
Lloyd Pique66d68602019-02-13 14:23:31 -08003397 const bool hasDeviceComposition = displayState.usesDeviceComposition;
Peiyong Lined531a32018-10-26 18:27:56 -07003398 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003399 getHwComposer()
3400 .hasDisplayCapability(displayId,
3401 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003402
Peiyong Lind3788632018-09-18 16:01:31 -07003403 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003404 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3405 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003406 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003407 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003408 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003409
Mathias Agopian85d751c2012-08-29 16:59:24 -07003410 /*
3411 * and then, render the layers targeted at the framebuffer
3412 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003413
Dan Stoza9e56aa02015-11-02 13:00:03 -08003414 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003415 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003416 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003417 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003418 const Region viewportRegion(displayState.viewport);
3419 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003420 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003421 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003422 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003423 switch (layer->getCompositionType(displayDevice)) {
3424 case Hwc2::IComposerClient::Composition::CURSOR:
3425 case Hwc2::IComposerClient::Composition::DEVICE:
3426 case Hwc2::IComposerClient::Composition::SIDEBAND:
3427 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003428 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003429 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003430 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003431 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003432 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003433 // never clear the very first layer since we're
3434 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003435 renderengine::LayerSettings layerSettings;
3436 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003437 bool prepared =
3438 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3439 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003440
3441 if (prepared) {
3442 layerSettings.source.buffer.buffer = nullptr;
3443 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3444 layerSettings.alpha = half(0.0);
3445 layerSettings.disableBlending = true;
3446 clientCompositionLayers.push_back(layerSettings);
3447 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003448 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003449 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003450 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003451 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003452 renderengine::LayerSettings layerSettings;
3453 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003454 layer->prepareClientLayer(renderArea, clip, clearRegion,
3455 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003456 if (prepared) {
3457 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003458 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003459 break;
3460 }
3461 default:
3462 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003463 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003464 } else {
3465 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003466 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003467 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003468 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003469
Alec Mouri820c7402019-01-23 13:02:39 -08003470 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003471 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003472 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003473
3474 // We boost GPU frequency here because there will be color spaces conversion
3475 // and it's expensive. We boost the GPU frequency so that GPU composition can
3476 // finish in time. We must reset GPU frequency afterwards, because high frequency
3477 // consumes extra battery.
3478 const bool expensiveRenderingExpected =
3479 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3480 if (expensiveRenderingExpected && displayId) {
3481 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3482 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003483 if (!debugRegion.isEmpty()) {
3484 Region::const_iterator it = debugRegion.begin();
3485 Region::const_iterator end = debugRegion.end();
3486 while (it != end) {
3487 const Rect& rect = *it++;
3488 renderengine::LayerSettings layerSettings;
3489 layerSettings.source.buffer.buffer = nullptr;
3490 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3491 layerSettings.geometry.boundaries = rect.toFloatRect();
3492 layerSettings.alpha = half(1.0);
3493 clientCompositionLayers.push_back(layerSettings);
3494 }
3495 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003496 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003497 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3498 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003499 } else if (displayId) {
3500 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003501 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003502 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003503}
3504
Robert Carrc0df3122019-04-11 13:18:21 -07003505status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3506 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3507 const sp<IBinder>& parentHandle,
3508 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003509 // add this layer to the current state list
3510 {
3511 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003512 sp<Layer> parent;
3513 if (parentHandle != nullptr) {
3514 parent = fromHandle(parentHandle);
3515 if (parent == nullptr) {
3516 return NAME_NOT_FOUND;
3517 }
3518 } else {
3519 parent = parentLayer;
3520 }
3521
Robert Carr1f0a16a2016-10-24 16:27:39 -07003522 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003523 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3524 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003525 return NO_MEMORY;
3526 }
Robert Carrc0df3122019-04-11 13:18:21 -07003527
3528 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3529
Robert Carrb89ea9d2018-12-10 13:01:14 -08003530 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003531 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003532 } else if (parent == nullptr) {
3533 lbc->onRemovedFromCurrentState();
3534 } else if (parent->isRemovedFromCurrentState()) {
3535 parent->addChild(lbc);
3536 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003537 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003538 parent->addChild(lbc);
3539 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003540
Yiwei Zhang243b3782018-05-15 17:40:04 -07003541 if (gbc != nullptr) {
3542 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3543 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3544 mMaxGraphicBufferProducerListSize,
3545 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3546 mGraphicBufferProducerList.size(),
3547 mMaxGraphicBufferProducerListSize, mNumLayers);
3548 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003549 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003550 }
3551
Mathias Agopian96f08192010-06-02 23:28:45 -07003552 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003553 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003554
Dan Stoza7d89d062015-04-30 13:29:25 -07003555 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003556}
3557
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003558uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003559 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003560}
3561
Mathias Agopian3f844832013-08-07 21:24:32 -07003562uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003563 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003564}
3565
Mathias Agopian3f844832013-08-07 21:24:32 -07003566uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003567 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003568}
3569
3570uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003571 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003572 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003573 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003574 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003575 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003576 }
3577 return old;
3578}
3579
Marissa Wall713b63f2018-10-17 15:42:43 -07003580bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003581 // to prevent onHandleDestroyed from being called while the lock is held,
3582 // we must keep a copy of the transactions (specifically the composer
3583 // states) around outside the scope of the lock
3584 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003585 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003586 {
3587 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003588
Valerie Haufce31b82019-04-30 16:41:14 -07003589 auto it = mTransactionQueues.begin();
3590 while (it != mTransactionQueues.end()) {
3591 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003592
Valerie Haufce31b82019-04-30 16:41:14 -07003593 while (!transactionQueue.empty()) {
3594 const auto& transaction = transactionQueue.front();
3595 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003596 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003597 transaction.states)) {
3598 setTransactionFlags(eTransactionFlushNeeded);
3599 break;
3600 }
3601 transactions.push_back(transaction);
3602 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3603 mPendingInputWindowCommands, transaction.desiredPresentTime,
3604 transaction.buffer, transaction.callback,
3605 transaction.postTime, transaction.privileged,
3606 /*isMainThread*/ true);
3607 transactionQueue.pop();
3608 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003609 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003610
Valerie Haufce31b82019-04-30 16:41:14 -07003611 if (transactionQueue.empty()) {
3612 it = mTransactionQueues.erase(it);
3613 mTransactionCV.broadcast();
3614 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003615 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003616 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003617 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003618 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003619 return flushedATransaction;
3620}
3621
3622bool SurfaceFlinger::transactionFlushNeeded() {
3623 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003624}
3625
chaviwca27f252018-02-06 16:46:39 -08003626
Marissa Wall17b4e452018-12-26 16:32:34 -08003627bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003628 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003629 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003630 if (!useCachedExpectedPresentTime)
3631 populateExpectedPresentTime();
3632
3633 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003634 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3635 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3636 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3637 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3638 return false;
3639 }
3640
Marissa Wall713b63f2018-10-17 15:42:43 -07003641 for (const ComposerState& state : states) {
3642 const layer_state_t& s = state.state;
3643 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3644 continue;
3645 }
3646 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003647 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003648 }
3649 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003650 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003651}
3652
3653void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3654 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003655 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003656 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003657 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003658 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003659 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003660 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003661
Valerie Haubc6ddb12019-03-08 11:10:15 -08003662 const int64_t postTime = systemTime();
3663
Robert Carr14167e02019-02-13 13:50:55 -08003664 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3665
Mathias Agopian698c0872011-06-28 19:09:31 -07003666 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003667
Marissa Wall713b63f2018-10-17 15:42:43 -07003668 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003669 auto itr = mTransactionQueues.find(applyToken);
3670 // if this is an animation frame, wait until prior animation frame has
3671 // been applied by SF
3672 if (flags & eAnimation) {
3673 while (itr != mTransactionQueues.end()) {
3674 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3675 if (CC_UNLIKELY(err != NO_ERROR)) {
3676 ALOGW_IF(err == TIMED_OUT,
3677 "setTransactionState timed out "
3678 "waiting for animation frame to apply");
3679 break;
3680 }
3681 itr = mTransactionQueues.find(applyToken);
3682 }
3683 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003684
3685 // Expected present time is computed and cached on invalidate, so it may be stale.
3686 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3687 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003688 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003689 uncacheBuffer, listenerCallbacks, postTime,
3690 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003691 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003692 return;
3693 }
3694
Valerie Haubc6ddb12019-03-08 11:10:15 -08003695 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003696 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003697}
3698
3699void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003700 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003701 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003702 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003703 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003704 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003705 const int64_t postTime, bool privileged,
3706 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003707 uint32_t transactionFlags = 0;
3708
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003709 if (flags & eAnimation) {
3710 // For window updates that are part of an animation we must wait for
3711 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003712 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003713 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003714 if (CC_UNLIKELY(err != NO_ERROR)) {
3715 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003716 // caller after a few seconds.
3717 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3718 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003719 mAnimTransactionPending = false;
3720 break;
3721 }
3722 }
3723 }
3724
chaviwca27f252018-02-06 16:46:39 -08003725 for (const DisplayState& display : displays) {
3726 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003727 }
3728
Marissa Walld600d572019-03-26 15:38:50 -07003729 // In case the client has sent a Transaction that should receive callbacks but without any
3730 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3731 // to the callback thread so it can send an empty callback
3732 if (!listenerCallbacks.empty()) {
3733 mTransactionCompletedThread.run();
3734 }
Marissa Wallefb71af2019-06-27 14:45:53 -07003735 for (const auto& listenerCallback : listenerCallbacks) {
3736 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07003737 }
3738
Marissa Walle2ffb422018-10-12 11:33:52 -07003739 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003740 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003741 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3742 postTime, privileged);
3743 }
3744
Marissa Wallefb71af2019-06-27 14:45:53 -07003745 for (const auto& listenerCallback : listenerCallbacks) {
3746 mTransactionCompletedThread.endRegistration(listenerCallback);
3747 }
3748
Marissa Walle2ffb422018-10-12 11:33:52 -07003749 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003750 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003751 mTransactionCompletedThread.sendCallbacks();
3752 }
3753 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003754
chaviw273171b2018-12-26 11:46:30 -08003755 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3756
Marissa Wall947d34e2019-03-29 14:03:53 -07003757 if (uncacheBuffer.isValid()) {
3758 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003759 }
3760
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003761 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3762 // anyway. This can be used as a flush mechanism for previous async transactions.
3763 // Empty animation transaction can be used to simulate back-pressure, so also force a
3764 // transaction for empty animation transactions.
3765 if (transactionFlags == 0 &&
3766 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003767 transactionFlags = eTransactionNeeded;
3768 }
3769
Marissa Wall06255332019-03-27 13:48:27 -07003770 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3771 // so we don't have to wake up again next frame to preform an uneeded traversal.
3772 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3773 transactionFlags = transactionFlags & (~eTraversalNeeded);
3774 mTraversalNeededMainThread = true;
3775 }
3776
Mathias Agopian386aa982011-11-07 21:58:03 -08003777 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003778 if (mInterceptor->isEnabled()) {
3779 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003780 }
Irvel468051e2016-06-13 16:44:44 -07003781
Mathias Agopian386aa982011-11-07 21:58:03 -08003782 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003783 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3784 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003785 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003786
3787 // if this is a synchronous transaction, wait for it to take effect
3788 // before returning.
3789 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003790 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003791 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003792 if (flags & eAnimation) {
3793 mAnimTransactionPending = true;
3794 }
chaviw4fe36852019-04-15 16:25:49 -07003795 if (mPendingInputWindowCommands.syncInputWindows) {
3796 mPendingSyncInputWindows = true;
3797 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003798
3799 // applyTransactionState can be called by either the main SF thread or by
3800 // another process through setTransactionState. While a given process may wish
3801 // to wait on synchronous transactions, the main SF thread should never
3802 // be blocked. Therefore, we only wait if isMainThread is false.
3803 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003804 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3805 if (CC_UNLIKELY(err != NO_ERROR)) {
3806 // just in case something goes wrong in SF, return to the
3807 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003808 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3809 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003810 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003811 break;
3812 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003813 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814 }
3815}
3816
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003817uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3818 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3819 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003820
Mathias Agopiane57f2922012-08-09 16:29:12 -07003821 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003822 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3823
3824 const uint32_t what = s.what;
3825 if (what & DisplayState::eSurfaceChanged) {
3826 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3827 state.surface = s.surface;
3828 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003829 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003830 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003831 if (what & DisplayState::eLayerStackChanged) {
3832 if (state.layerStack != s.layerStack) {
3833 state.layerStack = s.layerStack;
3834 flags |= eDisplayTransactionNeeded;
3835 }
3836 }
3837 if (what & DisplayState::eDisplayProjectionChanged) {
3838 if (state.orientation != s.orientation) {
3839 state.orientation = s.orientation;
3840 flags |= eDisplayTransactionNeeded;
3841 }
3842 if (state.frame != s.frame) {
3843 state.frame = s.frame;
3844 flags |= eDisplayTransactionNeeded;
3845 }
3846 if (state.viewport != s.viewport) {
3847 state.viewport = s.viewport;
3848 flags |= eDisplayTransactionNeeded;
3849 }
3850 }
3851 if (what & DisplayState::eDisplaySizeChanged) {
3852 if (state.width != s.width) {
3853 state.width = s.width;
3854 flags |= eDisplayTransactionNeeded;
3855 }
3856 if (state.height != s.height) {
3857 state.height = s.height;
3858 flags |= eDisplayTransactionNeeded;
3859 }
3860 }
3861
Mathias Agopiane57f2922012-08-09 16:29:12 -07003862 return flags;
3863}
3864
Robert Carr14167e02019-02-13 13:50:55 -08003865bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003866 IPCThreadState* ipc = IPCThreadState::self();
3867 const int pid = ipc->getCallingPid();
3868 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003869 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003870 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003871 return false;
3872 }
3873 return true;
3874}
3875
Marissa Wall3dad52d2019-03-22 14:03:19 -07003876uint32_t SurfaceFlinger::setClientStateLocked(
3877 const ComposerState& composerState, int64_t desiredPresentTime,
3878 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3879 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003880 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003881
Vishnu Nairf03652d2019-07-16 17:56:56 -07003882 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003883 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003884 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003885 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003886 new CallbackHandle(listenerCallback.transactionCompletedListener,
3887 listenerCallback.callbackIds, s.surface));
3888 }
chaviw8b3871a2017-11-01 17:41:01 -07003889 return 0;
3890 }
3891
chaviw8b3871a2017-11-01 17:41:01 -07003892 uint32_t flags = 0;
3893
Garfield Tan8a3083e2018-12-03 13:21:07 -08003894 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003895 bool geometryAppliesWithResize =
3896 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003897
3898 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3899 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003900 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003901 layer->pushPendingState();
3902 }
3903
chaviw8b3871a2017-11-01 17:41:01 -07003904 if (what & layer_state_t::ePositionChanged) {
3905 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3906 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003907 }
chaviw8b3871a2017-11-01 17:41:01 -07003908 }
3909 if (what & layer_state_t::eLayerChanged) {
3910 // NOTE: index needs to be calculated before we update the state
3911 const auto& p = layer->getParent();
3912 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003913 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003914 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003915 mCurrentState.layersSortedByZ.removeAt(idx);
3916 mCurrentState.layersSortedByZ.add(layer);
3917 // we need traversal (state changed)
3918 // AND transaction (list changed)
3919 flags |= eTransactionNeeded|eTraversalNeeded;
3920 }
chaviw8b3871a2017-11-01 17:41:01 -07003921 } else {
3922 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003923 flags |= eTransactionNeeded|eTraversalNeeded;
3924 }
3925 }
chaviw8b3871a2017-11-01 17:41:01 -07003926 }
3927 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003928 // NOTE: index needs to be calculated before we update the state
3929 const auto& p = layer->getParent();
3930 if (p == nullptr) {
3931 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3932 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3933 mCurrentState.layersSortedByZ.removeAt(idx);
3934 mCurrentState.layersSortedByZ.add(layer);
3935 // we need traversal (state changed)
3936 // AND transaction (list changed)
3937 flags |= eTransactionNeeded|eTraversalNeeded;
3938 }
3939 } else {
3940 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3941 flags |= eTransactionNeeded|eTraversalNeeded;
3942 }
chaviw8b3871a2017-11-01 17:41:01 -07003943 }
3944 }
3945 if (what & layer_state_t::eSizeChanged) {
3946 if (layer->setSize(s.w, s.h)) {
3947 flags |= eTraversalNeeded;
3948 }
3949 }
3950 if (what & layer_state_t::eAlphaChanged) {
3951 if (layer->setAlpha(s.alpha))
3952 flags |= eTraversalNeeded;
3953 }
3954 if (what & layer_state_t::eColorChanged) {
3955 if (layer->setColor(s.color))
3956 flags |= eTraversalNeeded;
3957 }
Peiyong Lind3788632018-09-18 16:01:31 -07003958 if (what & layer_state_t::eColorTransformChanged) {
3959 if (layer->setColorTransform(s.colorTransform)) {
3960 flags |= eTraversalNeeded;
3961 }
3962 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003963 if (what & layer_state_t::eBackgroundColorChanged) {
3964 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3965 flags |= eTraversalNeeded;
3966 }
3967 }
chaviw8b3871a2017-11-01 17:41:01 -07003968 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003969 // TODO: b/109894387
3970 //
3971 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3972 // rotation. To see the problem observe that if we have a square parent, and a child
3973 // of the same size, then we rotate the child 45 degrees around it's center, the child
3974 // must now be cropped to a non rectangular 8 sided region.
3975 //
3976 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3977 // private API, and the WindowManager only uses rotation in one case, which is on a top
3978 // level layer in which cropping is not an issue.
3979 //
3980 // However given that abuse of rotation matrices could lead to surfaces extending outside
3981 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3982 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3983 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003984 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003985 flags |= eTraversalNeeded;
3986 }
3987 if (what & layer_state_t::eTransparentRegionChanged) {
3988 if (layer->setTransparentRegionHint(s.transparentRegion))
3989 flags |= eTraversalNeeded;
3990 }
3991 if (what & layer_state_t::eFlagsChanged) {
3992 if (layer->setFlags(s.flags, s.mask))
3993 flags |= eTraversalNeeded;
3994 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003995 if (what & layer_state_t::eCropChanged_legacy) {
3996 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003997 flags |= eTraversalNeeded;
3998 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003999 if (what & layer_state_t::eCornerRadiusChanged) {
4000 if (layer->setCornerRadius(s.cornerRadius))
4001 flags |= eTraversalNeeded;
4002 }
chaviw8b3871a2017-11-01 17:41:01 -07004003 if (what & layer_state_t::eLayerStackChanged) {
4004 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4005 // We only allow setting layer stacks for top level layers,
4006 // everything else inherits layer stack from its parent.
4007 if (layer->hasParent()) {
4008 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4009 layer->getName().string());
4010 } else if (idx < 0) {
4011 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4012 "that also does not appear in the top level layer list. Something"
4013 " has gone wrong.", layer->getName().string());
4014 } else if (layer->setLayerStack(s.layerStack)) {
4015 mCurrentState.layersSortedByZ.removeAt(idx);
4016 mCurrentState.layersSortedByZ.add(layer);
4017 // we need traversal (state changed)
4018 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004019 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004020 }
4021 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004022 if (what & layer_state_t::eDeferTransaction_legacy) {
4023 if (s.barrierHandle_legacy != nullptr) {
4024 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4025 } else if (s.barrierGbp_legacy != nullptr) {
4026 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004027 if (authenticateSurfaceTextureLocked(gbp)) {
4028 const auto& otherLayer =
4029 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004030 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004031 } else {
4032 ALOGE("Attempt to defer transaction to to an"
4033 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004034 }
4035 }
chaviw8b3871a2017-11-01 17:41:01 -07004036 // We don't trigger a traversal here because if no other state is
4037 // changed, we don't want this to cause any more work
4038 }
4039 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004040 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004041 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004042 if (!hadParent) {
4043 mCurrentState.layersSortedByZ.remove(layer);
4044 }
chaviw8b3871a2017-11-01 17:41:01 -07004045 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004046 }
chaviw8b3871a2017-11-01 17:41:01 -07004047 }
4048 if (what & layer_state_t::eReparentChildren) {
4049 if (layer->reparentChildren(s.reparentHandle)) {
4050 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004051 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004052 }
chaviw8b3871a2017-11-01 17:41:01 -07004053 if (what & layer_state_t::eDetachChildren) {
4054 layer->detachChildren();
4055 }
4056 if (what & layer_state_t::eOverrideScalingModeChanged) {
4057 layer->setOverrideScalingMode(s.overrideScalingMode);
4058 // We don't trigger a traversal here because if no other state is
4059 // changed, we don't want this to cause any more work
4060 }
Marissa Wall61c58622018-07-18 10:12:20 -07004061 if (what & layer_state_t::eTransformChanged) {
4062 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4063 }
4064 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4065 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4066 flags |= eTraversalNeeded;
4067 }
4068 if (what & layer_state_t::eCropChanged) {
4069 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4070 }
Marissa Wall861616d2018-10-22 12:52:23 -07004071 if (what & layer_state_t::eFrameChanged) {
4072 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4073 }
Marissa Wall61c58622018-07-18 10:12:20 -07004074 if (what & layer_state_t::eAcquireFenceChanged) {
4075 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4076 }
4077 if (what & layer_state_t::eDataspaceChanged) {
4078 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4079 }
4080 if (what & layer_state_t::eHdrMetadataChanged) {
4081 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4082 }
4083 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4084 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4085 }
4086 if (what & layer_state_t::eApiChanged) {
4087 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4088 }
4089 if (what & layer_state_t::eSidebandStreamChanged) {
4090 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4091 }
Robert Carr720e5062018-07-30 17:45:14 -07004092 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004093 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004094 layer->setInputInfo(s.inputInfo);
4095 flags |= eTraversalNeeded;
4096 } else {
4097 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4098 }
Robert Carr720e5062018-07-30 17:45:14 -07004099 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004100 if (what & layer_state_t::eMetadataChanged) {
4101 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4102 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004103 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4104 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4105 flags |= eTraversalNeeded;
4106 }
4107 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004108 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004109 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004110 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004111 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4112 }
4113 }
Marissa Wall78b72202019-03-15 14:58:34 -07004114 bool bufferChanged = what & layer_state_t::eBufferChanged;
4115 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4116 sp<GraphicBuffer> buffer;
4117 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004118 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri1c8d7202019-06-01 18:51:35 -07004119 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4120 wp<ClientCache::ErasedRecipient>(layer));
4121 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004122 buffer = s.buffer;
4123 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004124 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004125 } else if (bufferChanged) {
4126 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004127 }
Marissa Wall78b72202019-03-15 14:58:34 -07004128 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004129 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004130 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004131 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004132 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004133 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4134 // Do not put anything that updates layer state or modifies flags after
4135 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004136 return flags;
4137}
4138
chaviw273171b2018-12-26 11:46:30 -08004139uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4140 uint32_t flags = 0;
4141 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4142 flags |= eTraversalNeeded;
4143 }
4144
chaviwa911b102019-02-14 10:18:33 -08004145 if (inputWindowCommands.syncInputWindows) {
4146 flags |= eTraversalNeeded;
4147 }
4148
Vishnu Nairec0ab382019-02-13 15:32:56 -08004149 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004150 return flags;
4151}
4152
Marissa Wall2d814fb2019-04-09 18:52:57 +00004153status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4154 uint32_t h, PixelFormat format, uint32_t flags,
4155 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004156 sp<IGraphicBufferProducer>* gbp,
4157 const sp<IBinder>& parentHandle,
4158 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004159 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004160 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004161 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004162 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004163 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004164
Robert Carrc0df3122019-04-11 13:18:21 -07004165 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4166 "Expected only one of parentLayer or parentHandle to be non-null. "
4167 "Programmer error?");
4168
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004169 status_t result = NO_ERROR;
4170
4171 sp<Layer> layer;
4172
Cody Northropbc755282017-03-31 12:00:08 -06004173 String8 uniqueName = getUniqueLayerName(name);
4174
Evan Roskya1f1e152019-01-24 16:17:46 -08004175 bool primaryDisplayOnly = false;
4176
4177 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4178 // TODO b/64227542
4179 if (metadata.has(METADATA_WINDOW_TYPE)) {
4180 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4181 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004182 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004183 primaryDisplayOnly = true;
4184 }
4185 }
4186
Mathias Agopian3165cc22012-08-08 19:42:09 -07004187 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004188 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004189 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4190 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004192 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004193 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004194 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4195 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004196 break;
chaviw13fdc492017-06-27 12:40:18 -07004197 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004198 // check if buffer size is set for color layer.
4199 if (w > 0 || h > 0) {
4200 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4201 int(w), int(h));
4202 return BAD_VALUE;
4203 }
4204
Evan Roskya1f1e152019-01-24 16:17:46 -08004205 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4206 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004207 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004208 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004209 // check if buffer size is set for container layer.
4210 if (w > 0 || h > 0) {
4211 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4212 int(w), int(h));
4213 return BAD_VALUE;
4214 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004215 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4216 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004217 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004218 default:
4219 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004220 break;
4221 }
4222
Dan Stoza7d89d062015-04-30 13:29:25 -07004223 if (result != NO_ERROR) {
4224 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004225 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004226
Evan Roskya1f1e152019-01-24 16:17:46 -08004227 if (primaryDisplayOnly) {
4228 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004229 }
4230
Robert Carrb89ea9d2018-12-10 13:01:14 -08004231 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004232 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4233 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004234 if (result != NO_ERROR) {
4235 return result;
4236 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004237 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004238
4239 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004240 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004241}
4242
Cody Northropbc755282017-03-31 12:00:08 -06004243String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4244{
4245 bool matchFound = true;
4246 uint32_t dupeCounter = 0;
4247
4248 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4249 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4250
Dan Stoza436ccf32018-06-21 12:10:12 -07004251 // Grab the state lock since we're accessing mCurrentState
4252 Mutex::Autolock lock(mStateLock);
4253
Cody Northropbc755282017-03-31 12:00:08 -06004254 // Loop over layers until we're sure there is no matching name
4255 while (matchFound) {
4256 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004257 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004258 if (layer->getName() == uniqueName) {
4259 matchFound = true;
4260 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4261 }
4262 });
4263 }
4264
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004265 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4266 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004267
4268 return uniqueName;
4269}
4270
Marissa Wallfd668622018-05-10 10:21:13 -07004271status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4272 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004273 LayerMetadata metadata, PixelFormat& format,
4274 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004275 sp<IGraphicBufferProducer>* gbp,
4276 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004277 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004278 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004279 case PIXEL_FORMAT_TRANSPARENT:
4280 case PIXEL_FORMAT_TRANSLUCENT:
4281 format = PIXEL_FORMAT_RGBA_8888;
4282 break;
4283 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004284 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004285 break;
4286 }
4287
Evan Roskya1f1e152019-01-24 16:17:46 -08004288 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4289 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004290 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004291 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004292 *handle = layer->getHandle();
4293 *gbp = layer->getProducer();
4294 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004295 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004296
Marissa Wallfd668622018-05-10 10:21:13 -07004297 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004298 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299}
4300
Marissa Wall61c58622018-07-18 10:12:20 -07004301status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4302 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004303 LayerMetadata metadata, sp<IBinder>* handle,
4304 sp<Layer>* outLayer) {
4305 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4306 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004307 *handle = layer->getHandle();
4308 *outLayer = layer;
4309
4310 return NO_ERROR;
4311}
4312
Evan Roskya1f1e152019-01-24 16:17:46 -08004313status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4314 uint32_t h, uint32_t flags, LayerMetadata metadata,
4315 sp<IBinder>* handle, sp<Layer>* outLayer) {
4316 *outLayer = getFactory().createColorLayer(
4317 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004318 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004319 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004320}
4321
Evan Roskya1f1e152019-01-24 16:17:46 -08004322status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4323 uint32_t w, uint32_t h, uint32_t flags,
4324 LayerMetadata metadata, sp<IBinder>* handle,
4325 sp<Layer>* outLayer) {
4326 *outLayer = getFactory().createContainerLayer(
4327 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004328 *handle = (*outLayer)->getHandle();
4329 return NO_ERROR;
4330}
4331
4332
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004333void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004334 mLayersPendingRemoval.add(layer);
4335 mLayersRemoved = true;
4336 setTransactionFlags(eTransactionNeeded);
4337}
4338
Robert Carr695d5282018-12-18 15:27:58 -08004339void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004340{
Robert Carr2e102c92018-10-23 12:11:15 -07004341 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004342 // If a layer has a parent, we allow it to out-live it's handle
4343 // with the idea that the parent holds a reference and will eventually
4344 // be cleaned up. However no one cleans up the top-level so we do so
4345 // here.
4346 if (layer->getParent() == nullptr) {
4347 mCurrentState.layersSortedByZ.remove(layer);
4348 }
4349 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004350
4351 auto it = mLayersByLocalBinderToken.begin();
4352 while (it != mLayersByLocalBinderToken.end()) {
4353 if (it->second == layer) {
4354 it = mLayersByLocalBinderToken.erase(it);
4355 } else {
4356 it++;
4357 }
4358 }
4359
Robert Carr695d5282018-12-18 15:27:58 -08004360 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004361}
4362
Mathias Agopianb60314a2012-04-10 22:09:54 -07004363// ---------------------------------------------------------------------------
4364
Andy McFadden13a082e2012-08-24 10:16:42 -07004365void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004366 const auto display = getDefaultDisplayDeviceLocked();
4367 if (!display) return;
4368
4369 const sp<IBinder> token = display->getDisplayToken().promote();
4370 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004371
Jesse Hall01e29052013-02-19 16:13:35 -08004372 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004373 Vector<ComposerState> state;
4374 Vector<DisplayState> displays;
4375 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004376 d.what = DisplayState::eDisplayProjectionChanged |
4377 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004378 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004379 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004380 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004381 d.frame.makeInvalid();
4382 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004383 d.width = 0;
4384 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004385 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004386 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004387
Dominik Laskowskie9774092018-12-11 10:04:24 -08004388 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004389
Dominik Laskowski83b88212018-12-11 13:34:06 -08004390 const nsecs_t vsyncPeriod = getVsyncPeriod();
4391 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004392
Brian Andersond0010582017-03-07 13:20:31 -08004393 // Use phase of 0 since phase is not known.
4394 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004395 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004396 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004397}
4398
4399void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004400 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004401 postMessageAsync(
4402 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004403}
4404
Ady Abraham27c70212019-06-11 10:52:26 -07004405void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4406 if (mHWCVsyncState != enabled) {
4407 getHwComposer().setVsyncEnabled(displayId, enabled);
4408 mHWCVsyncState = enabled;
4409 }
4410}
4411
Dominik Laskowskie9774092018-12-11 10:04:24 -08004412void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004413 if (display->isVirtual()) {
4414 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004415 return;
4416 }
4417
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418 const auto displayId = display->getId();
4419 LOG_ALWAYS_FATAL_IF(!displayId);
4420
Dominik Laskowski34157762018-10-31 13:07:19 -07004421 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004422
4423 int currentMode = display->getPowerMode();
4424 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004425 return;
4426 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004427
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004428 display->setPowerMode(mode);
4429
Lloyd Pique4dccc412018-01-22 17:21:36 -08004430 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004431 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004432 }
4433
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004434 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004435 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004436 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004437 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004438 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004439 mScheduler->onScreenAcquired(mAppConnectionHandle);
4440 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004441 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004442
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004443 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004444 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004445 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004446
4447 struct sched_param param = {0};
4448 param.sched_priority = 1;
4449 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4450 ALOGW("Couldn't set SCHED_FIFO on display on");
4451 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004452 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004453 // Turn off the display
4454 struct sched_param param = {0};
4455 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4456 ALOGW("Couldn't set SCHED_OTHER on display off");
4457 }
4458
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004459 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004460 mScheduler->disableHardwareVsync(true);
4461 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004462 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004463
Ady Abraham27c70212019-06-11 10:52:26 -07004464 // Make sure HWVsync is disabled before turning off the display
4465 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4466
Dominik Laskowski075d3172018-05-24 15:50:06 -07004467 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004468 mVisibleRegionsDirty = true;
4469 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004470 } else if (mode == HWC_POWER_MODE_DOZE ||
4471 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004472 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004473 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004474 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004475 mScheduler->onScreenAcquired(mAppConnectionHandle);
4476 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004477 }
4478 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4479 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004480 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004481 mScheduler->disableHardwareVsync(true);
4482 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004483 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004484 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004485 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004486 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004487 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004488 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004489
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004490 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004491 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004492 mRefreshRateStats.setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004493 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004494 }
4495
Dominik Laskowski34157762018-10-31 13:07:19 -07004496 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004497}
4498
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004499void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004500 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004501 const auto display = getDisplayDevice(displayToken);
4502 if (!display) {
4503 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4504 displayToken.get());
4505 } else if (display->isVirtual()) {
4506 ALOGW("Attempt to set power mode %d for virtual display", mode);
4507 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004508 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004509 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004510 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004511}
4512
4513// ---------------------------------------------------------------------------
4514
Dominik Laskowskic2867142019-01-21 11:33:38 -08004515status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4516 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004517 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004518
Mathias Agopianbd115332013-04-18 16:41:04 -07004519 IPCThreadState* ipc = IPCThreadState::self();
4520 const int pid = ipc->getCallingPid();
4521 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004522
Mathias Agopianbd115332013-04-18 16:41:04 -07004523 if ((uid != AID_SHELL) &&
4524 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4526 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004528 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004529 // (this would indicate SF is stuck, but we want to be able to
4530 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004531 status_t err = mStateLock.timedLock(s2ns(1));
4532 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004533 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004534 StringAppendF(&result,
4535 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4536 "(no locks held)\n",
4537 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004538 }
4539
Dominik Laskowskic2867142019-01-21 11:33:38 -08004540 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004541
Dominik Laskowskic2867142019-01-21 11:33:38 -08004542 static const std::unordered_map<std::string, Dumper> dumpers = {
4543 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4544 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4545 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004546 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004547 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004548 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004549 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4550 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004551 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4552 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4553 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4554 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4555 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4556 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004557 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004558 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4559 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004560
Dominik Laskowskic2867142019-01-21 11:33:38 -08004561 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004562
Dominik Laskowskic2867142019-01-21 11:33:38 -08004563 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4564 (it->second)(args, asProto, result);
4565 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004566 if (asProto) {
4567 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4568 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4569 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004570 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004571 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004572 }
4573
Mathias Agopian9795c422009-08-26 16:36:26 -07004574 if (locked) {
4575 mStateLock.unlock();
4576 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004577 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004579 return NO_ERROR;
4580}
4581
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004582status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4583 if (asProto && mTracing.isEnabled()) {
4584 mTracing.writeToFileAsync();
4585 }
4586
4587 return doDump(fd, DumpArgs(), asProto);
4588}
4589
Dominik Laskowskic2867142019-01-21 11:33:38 -08004590void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004591 mCurrentState.traverseInZOrder(
4592 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004593}
4594
Dominik Laskowskic2867142019-01-21 11:33:38 -08004595void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004596 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004597
Dominik Laskowskic2867142019-01-21 11:33:38 -08004598 if (args.size() > 1) {
4599 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004600 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004601 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004602 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004603 }
Robert Carr2047fae2016-11-28 14:09:09 -08004604 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004605 } else {
4606 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004607 }
4608}
4609
Dominik Laskowskic2867142019-01-21 11:33:38 -08004610void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004611 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004612 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004613 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004614 }
Robert Carr2047fae2016-11-28 14:09:09 -08004615 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004616
Svetoslavd85084b2014-03-20 10:28:31 -07004617 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004618}
4619
Dominik Laskowskic2867142019-01-21 11:33:38 -08004620void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4621 mTimeStats->parseArgs(asProto, args, result);
4622}
4623
Jamie Gennis6547ff42013-07-16 20:12:42 -07004624// This should only be called from the main thread. Otherwise it would need
4625// the lock and should use mCurrentState rather than mDrawingState.
4626void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004627 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004628 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004629 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004630
4631 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4632}
4633
Yiwei Zhang5434a782018-12-05 18:06:32 -08004634void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004635 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004636
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004637 if (isLayerTripleBufferingDisabled())
4638 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004639
Yiwei Zhang5434a782018-12-05 18:06:32 -08004640 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4641 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4642 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4643 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4644 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4645 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004646 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004647}
4648
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004649void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004650 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004651 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004652 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004653 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004654
Ady Abraham97d04232019-03-05 19:48:12 -08004655 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004656 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4657 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004658 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham261614e2019-07-10 17:53:12 -07004659 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4660 if (refresh.second && isDisplayConfigAllowed(refresh.second->configId)) {
4661 StringAppendF(&result, "%dHz, ", refresh.second->fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004662 }
4663 }
4664 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4665 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004666 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004667}
4668
Yiwei Zhang5434a782018-12-05 18:06:32 -08004669void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4670 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004671 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4672 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004673 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004674 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004676 }
David Sodman4a36e932017-11-07 14:29:47 -08004677 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004678 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004679 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4681 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004682}
4683
Dan Stozae77c7662016-05-13 11:37:28 -07004684void SurfaceFlinger::recordBufferingStats(const char* layerName,
4685 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004686 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4687 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004688 for (const auto& segment : history) {
4689 if (!segment.usedThirdBuffer) {
4690 stats.twoBufferTime += segment.totalTime;
4691 }
4692 if (segment.occupancyAverage < 1.0f) {
4693 stats.doubleBufferedTime += segment.totalTime;
4694 } else if (segment.occupancyAverage < 2.0f) {
4695 stats.tripleBufferedTime += segment.totalTime;
4696 }
4697 ++stats.numSegments;
4698 stats.totalTime += segment.totalTime;
4699 }
4700}
4701
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4703 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004704
4705 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4706 const size_t count = currentLayers.size();
4707 for (size_t i=0 ; i<count ; i++) {
4708 currentLayers[i]->dumpFrameEvents(result);
4709 }
4710}
4711
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004713 result.append("Buffering stats:\n");
4714 result.append(" [Layer name] <Active time> <Two buffer> "
4715 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004716 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004717 typedef std::tuple<std::string, float, float, float> BufferTuple;
4718 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004719 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004720 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004721 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004722 if (stats.numSegments == 0) {
4723 continue;
4724 }
4725 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4726 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4727 stats.totalTime;
4728 float doubleBufferRatio = static_cast<float>(
4729 stats.doubleBufferedTime) / stats.totalTime;
4730 float tripleBufferRatio = static_cast<float>(
4731 stats.tripleBufferedTime) / stats.totalTime;
4732 sorted.insert({activeTime, {name, twoBufferRatio,
4733 doubleBufferRatio, tripleBufferRatio}});
4734 }
4735 for (const auto& sortedPair : sorted) {
4736 float activeTime = sortedPair.first;
4737 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4739 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004740 }
4741 result.append("\n");
4742}
4743
Yiwei Zhang5434a782018-12-05 18:06:32 -08004744void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004745 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004746 const auto displayId = display->getId();
4747 if (!displayId) {
4748 continue;
4749 }
4750 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004751 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004752 continue;
4753 }
4754
Yiwei Zhang5434a782018-12-05 18:06:32 -08004755 StringAppendF(&result,
4756 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4757 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004758 uint8_t port;
4759 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004760 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004761 result.append("no identification data\n");
4762 continue;
4763 }
4764
4765 if (!isEdid(data)) {
4766 result.append("unknown identification data: ");
4767 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004768 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004769 }
4770 result.append("\n");
4771 continue;
4772 }
4773
4774 const auto edid = parseEdid(data);
4775 if (!edid) {
4776 result.append("invalid EDID: ");
4777 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004778 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004779 }
4780 result.append("\n");
4781 continue;
4782 }
4783
Yiwei Zhang5434a782018-12-05 18:06:32 -08004784 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004785 result.append(edid->displayName.data(), edid->displayName.length());
4786 result.append("\"\n");
4787 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004788}
4789
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004791 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004792 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4793 StringAppendF(&result, "DisplayColorSetting: %s\n",
4794 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004795
4796 // TODO: print out if wide-color mode is active or not
4797
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004798 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004799 const auto displayId = display->getId();
4800 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004801 continue;
4802 }
4803
Yiwei Zhang5434a782018-12-05 18:06:32 -08004804 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004805 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004806 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004807 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004808 }
4809
Lloyd Pique32cbe282018-10-19 13:09:22 -07004810 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004811 StringAppendF(&result, " Current color mode: %s (%d)\n",
4812 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004813 }
4814 result.append("\n");
4815}
4816
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004817LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4818 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004819 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004820 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4821 const State& state = useDrawing ? mDrawingState : mCurrentState;
4822 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004823 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004824 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004825 });
4826
4827 return layersProto;
4828}
4829
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004830LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4831 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004832 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004833
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004834 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004835 resolution->set_w(displayDevice->getWidth());
4836 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004837
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004838 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004839 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004840
Lloyd Pique32cbe282018-10-19 13:09:22 -07004841 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4842 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4843 layersProto.set_global_transform(displayState.orientation);
4844
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004845 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004846 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004847 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004848 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004849 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004850 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004851 }
4852 });
4853
4854 return layersProto;
4855}
4856
Dominik Laskowskic2867142019-01-21 11:33:38 -08004857void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4858 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004859 Colorizer colorizer(colorize);
4860
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004861 // figure out if we're stuck somewhere
4862 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004863 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004864 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4865
4866 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004867 * Dump library configuration.
4868 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004869
4870 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004871 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004872 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004873 appendSfConfigString(result);
4874 appendUiConfigString(result);
4875 appendGuiConfigString(result);
4876 result.append("\n");
4877
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004878 result.append("\nDisplay identification data:\n");
4879 dumpDisplayIdentificationData(result);
4880
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004881 result.append("\nWide-Color information:\n");
4882 dumpWideColorInfo(result);
4883
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004884 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004885 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004886 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004887 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004888 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004889
Andy McFadden41d67d72014-04-25 16:58:34 -07004890 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004891 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004892 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004893 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004894 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004895
Dan Stozab90cf072015-03-05 11:05:59 -08004896 dumpStaticScreenStats(result);
4897 result.append("\n");
4898
Alec Mouri40189b02019-03-05 15:07:54 -08004899 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4900 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4901 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004902
Dan Stozae77c7662016-05-13 11:37:28 -07004903 dumpBufferingStats(result);
4904
Andy McFadden4803b742012-09-24 19:07:20 -07004905 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004906 * Dump the visible layer list
4907 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004908 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004909 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4910 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4911 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004912 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004913
Chia-I Wu2f884132018-09-13 15:17:58 -07004914 {
4915 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4916 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004917 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004918 result.append("\n");
4919 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004920
Lloyd Pique207def92019-02-28 16:09:52 -08004921 {
4922 StringAppendF(&result, "Composition layers\n");
4923 mDrawingState.traverseInZOrder([&](Layer* layer) {
4924 auto compositionLayer = layer->getCompositionLayer();
4925 if (compositionLayer) compositionLayer->dump(result);
4926 });
4927 }
4928
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004929 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004930 * Dump Display state
4931 */
4932
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004933 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004934 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004935 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004936 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004937 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004938 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004939 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004940
4941 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004942 * Dump SurfaceFlinger global state
4943 */
4944
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004945 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004946 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004947 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004948
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004949 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004950
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004951 DebugEGLImageTracker::getInstance()->dump(result);
4952
Dominik Laskowski075d3172018-05-24 15:50:06 -07004953 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004954 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4955 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004956 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4957 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004958 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004959 StringAppendF(&result,
4960 " transaction-flags : %08x\n"
4961 " gpu_to_cpu_unsupported : %d\n",
4962 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004963
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004964 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004965 displayId && getHwComposer().isConnected(*displayId)) {
4966 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004967 StringAppendF(&result,
4968 " refresh-rate : %f fps\n"
4969 " x-dpi : %f\n"
4970 " y-dpi : %f\n",
4971 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4972 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004973 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004974
Yiwei Zhang5434a782018-12-05 18:06:32 -08004975 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004976
Dan Stozae22aec72016-08-01 13:20:59 -07004977 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004978 * Tracing state
4979 */
4980 mTracing.dump(result);
4981 result.append("\n");
4982
4983 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004984 * HWC layer minidump
4985 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004986 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004987 const auto displayId = display->getId();
4988 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004989 continue;
4990 }
4991
Yiwei Zhang5434a782018-12-05 18:06:32 -08004992 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004993 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004994 const sp<DisplayDevice> displayDevice = display;
4995 mCurrentState.traverseInZOrder(
4996 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004997 result.append("\n");
4998 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004999
5000 /*
5001 * Dump HWComposer state
5002 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005003 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005004 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005005 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005006 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005007 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005008 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005009
5010 /*
5011 * Dump gralloc state
5012 */
5013 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5014 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005015
5016 /*
5017 * Dump VrFlinger state if in use.
5018 */
5019 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5020 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005021 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005022 result.append("\n");
5023 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005024
5025 /**
5026 * Scheduler dump state.
5027 */
Ana Krulecc2870422019-01-29 19:00:58 -08005028 result.append("\nScheduler state:\n");
5029 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005030 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005031 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005032
5033 result.append(mTimeStats->miniDump());
5034 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005035}
5036
Dominik Laskowski075d3172018-05-24 15:50:06 -07005037const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005038 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005039 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005040 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005041 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005042 }
5043 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005044
Dominik Laskowski34157762018-10-31 13:07:19 -07005045 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005046 static const Vector<sp<Layer>> empty;
5047 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005048}
5049
Chia-I Wu28f320b2018-05-03 11:02:56 -07005050void SurfaceFlinger::updateColorMatrixLocked() {
5051 mat4 colorMatrix;
5052 if (mGlobalSaturationFactor != 1.0f) {
5053 // Rec.709 luma coefficients
5054 float3 luminance{0.213f, 0.715f, 0.072f};
5055 luminance *= 1.0f - mGlobalSaturationFactor;
5056 mat4 saturationMatrix = mat4(
5057 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5058 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5059 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5060 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5061 );
5062 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5063 } else {
5064 colorMatrix = mClientColorMatrix * mDaltonizer();
5065 }
5066
5067 if (mCurrentState.colorMatrix != colorMatrix) {
5068 mCurrentState.colorMatrix = colorMatrix;
5069 mCurrentState.colorMatrixChanged = true;
5070 setTransactionFlags(eTransactionNeeded);
5071 }
5072}
5073
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005074status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005075#pragma clang diagnostic push
5076#pragma clang diagnostic error "-Wswitch-enum"
5077 switch (static_cast<ISurfaceComposerTag>(code)) {
5078 // These methods should at minimum make sure that the client requested
5079 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005080 case BOOT_FINISHED:
5081 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005082 case CREATE_DISPLAY:
5083 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005084 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005085 case GET_ANIMATION_FRAME_STATS:
5086 case GET_HDR_CAPABILITIES:
5087 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005088 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005089 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005090 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005091 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005092 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005093 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005094 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005095 case GET_DISPLAYED_CONTENT_SAMPLE:
5096 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005097 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5098 IPCThreadState* ipc = IPCThreadState::self();
5099 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5100 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005101 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005102 }
Robert Carr1db73f62016-12-21 12:58:51 -08005103 return OK;
5104 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005105 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005106 IPCThreadState* ipc = IPCThreadState::self();
5107 const int pid = ipc->getCallingPid();
5108 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005109 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5110 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005111 return PERMISSION_DENIED;
5112 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005113 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005114 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005115 // Used by apps to hook Choreographer to SurfaceFlinger.
5116 case CREATE_DISPLAY_EVENT_CONNECTION:
5117 // The following calls are currently used by clients that do not
5118 // request necessary permissions. However, they do not expose any secret
5119 // information, so it is OK to pass them.
5120 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005121 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005122 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005123 case GET_PHYSICAL_DISPLAY_IDS:
5124 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005125 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005126 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005127 case GET_DISPLAY_CONFIGS:
5128 case GET_DISPLAY_STATS:
5129 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5130 // Calling setTransactionState is safe, because you need to have been
5131 // granted a reference to Client* and Handle* to do anything with it.
5132 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005133 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005134 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005135 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005136 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005137 case IS_WIDE_COLOR_DISPLAY:
5138 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5139 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005140 return OK;
5141 }
Chong Zhangda6c1592019-07-16 13:45:06 -07005142 case CAPTURE_LAYERS: {
5143 IPCThreadState* ipc = IPCThreadState::self();
5144 const int pid = ipc->getCallingPid();
5145 const int uid = ipc->getCallingUid();
5146 // allow media to capture layer for video thumbnails
5147 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
5148 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5149 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
5150 return PERMISSION_DENIED;
5151 }
5152 return OK;
5153 }
Dan Stoza84ab9372018-12-17 15:27:57 -08005154 case CAPTURE_SCREEN:
5155 case ADD_REGION_SAMPLING_LISTENER:
5156 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005157 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005158 IPCThreadState* ipc = IPCThreadState::self();
5159 const int pid = ipc->getCallingPid();
5160 const int uid = ipc->getCallingUid();
5161 if ((uid != AID_GRAPHICS) &&
5162 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5163 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5164 return PERMISSION_DENIED;
5165 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005166 return OK;
5167 }
5168 // The following codes are deprecated and should never be allowed to access SF.
5169 case CONNECT_DISPLAY_UNUSED:
5170 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5171 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5172 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005173 }
chaviw93df2ea2019-04-30 16:45:12 -07005174 case CAPTURE_SCREEN_BY_ID: {
5175 IPCThreadState* ipc = IPCThreadState::self();
5176 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005177 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005178 return OK;
5179 }
5180 return PERMISSION_DENIED;
5181 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005182 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005183
5184 // These codes are used for the IBinder protocol to either interrogate the recipient
5185 // side of the transaction for its canonical interface descriptor or to dump its state.
5186 // We let them pass by default.
5187 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5188 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5189 code == IBinder::SYSPROPS_TRANSACTION) {
5190 return OK;
5191 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005192 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005193 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005194 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005195 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5196 return OK;
5197 }
5198 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5199 return PERMISSION_DENIED;
5200#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005201}
5202
Ana Krulec13be8ad2018-08-21 02:43:56 +00005203status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5204 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005205 status_t credentialCheck = CheckTransactCodeCredentials(code);
5206 if (credentialCheck != OK) {
5207 return credentialCheck;
5208 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005210 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5211 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005212 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005213 IPCThreadState* ipc = IPCThreadState::self();
5214 const int uid = ipc->getCallingUid();
5215 if (CC_UNLIKELY(uid != AID_SYSTEM
5216 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005217 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005218 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005219 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005220 return PERMISSION_DENIED;
5221 }
5222 int n;
5223 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005224 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005225 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005226 return NO_ERROR;
5227 case 1002: // SHOW_UPDATES
5228 n = data.readInt32();
5229 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005230 invalidateHwcGeometry();
5231 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005232 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005233 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005234 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005235 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005236 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005237 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005238 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005239 setTransactionFlags(
5240 eTransactionNeeded|
5241 eDisplayTransactionNeeded|
5242 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005243 return NO_ERROR;
5244 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005245 case 1006:{ // send empty update
5246 signalRefresh();
5247 return NO_ERROR;
5248 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005249 case 1008: // toggle use of hw composer
5250 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005251 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005252 invalidateHwcGeometry();
5253 repaintEverything();
5254 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005255 case 1009: // toggle use of transform hint
5256 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005257 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005258 invalidateHwcGeometry();
5259 repaintEverything();
5260 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005261 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005262 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005263 reply->writeInt32(0);
5264 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005265 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005266 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005267 return NO_ERROR;
5268 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005269 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005270 if (!display) {
5271 return NAME_NOT_FOUND;
5272 }
5273
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005274 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005275 return NO_ERROR;
5276 }
5277 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005278 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005279 // daltonize
5280 n = data.readInt32();
5281 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005282 case 1:
5283 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5284 break;
5285 case 2:
5286 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5287 break;
5288 case 3:
5289 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5290 break;
5291 default:
5292 mDaltonizer.setType(ColorBlindnessType::None);
5293 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005294 }
5295 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005296 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005297 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005298 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005299 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005300
5301 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005302 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005303 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005304 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005305 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005306 // apply a color matrix
5307 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005308 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005309 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005310 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005311 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005312 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005313 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005314 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005315 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005316 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005317 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005318
5319 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5320 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005321 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005322 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5323 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5324 }
5325
Chia-I Wu28f320b2018-05-03 11:02:56 -07005326 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005327 return NO_ERROR;
5328 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005329 // This is an experimental interface
5330 // Needs to be shifted to proper binder interface when we productize
5331 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005332 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005333 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005334 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005335 return NO_ERROR;
5336 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005337 case 1017: {
5338 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005339 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005340 return NO_ERROR;
5341 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005342 case 1018: { // Modify Choreographer's phase offset
5343 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005344 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005345 return NO_ERROR;
5346 }
5347 case 1019: { // Modify SurfaceFlinger's phase offset
5348 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005349 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005350 return NO_ERROR;
5351 }
Irvel468051e2016-06-13 16:44:44 -07005352 case 1020: { // Layer updates interceptor
5353 n = data.readInt32();
5354 if (n) {
5355 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005356 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005357 }
5358 else{
5359 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005360 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005361 }
5362 return NO_ERROR;
5363 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005364 case 1021: { // Disable HWC virtual displays
5365 n = data.readInt32();
5366 mUseHwcVirtualDisplays = !n;
5367 return NO_ERROR;
5368 }
Romain Guy0147a172017-06-01 13:53:56 -07005369 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005370 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005371 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005372
Chia-I Wu28f320b2018-05-03 11:02:56 -07005373 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005374 return NO_ERROR;
5375 }
Romain Guy54f154a2017-10-24 21:40:32 +01005376 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005377 int32_t colorMode;
5378
Chia-I Wu0d711262018-05-21 15:19:35 -07005379 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005380 if (data.readInt32(&colorMode) == NO_ERROR) {
5381 mForceColorMode = static_cast<ColorMode>(colorMode);
5382 }
Romain Guy54f154a2017-10-24 21:40:32 +01005383 invalidateHwcGeometry();
5384 repaintEverything();
5385 return NO_ERROR;
5386 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005387 // Deprecate, use 1030 to check whether the device is color managed.
5388 case 1024: {
5389 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005390 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005391 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005392 n = data.readInt32();
5393 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005394 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005395 Mutex::Autolock lock(mStateLock);
5396 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005397 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005398 reply->writeInt32(NO_ERROR);
5399 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005400 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005401 bool writeFile = false;
5402 {
5403 Mutex::Autolock lock(mStateLock);
5404 mTracingEnabledChanged = true;
5405 writeFile = mTracing.disable();
5406 }
5407
5408 if (writeFile) {
5409 reply->writeInt32(mTracing.writeToFile());
5410 } else {
5411 reply->writeInt32(NO_ERROR);
5412 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005413 }
5414 return NO_ERROR;
5415 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005416 case 1026: { // Get layer tracing status
5417 reply->writeBool(mTracing.isEnabled());
5418 return NO_ERROR;
5419 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005420 // Is a DisplayColorSetting supported?
5421 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005422 const auto display = getDefaultDisplayDevice();
5423 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005424 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005425 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005426
5427 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5428 switch (setting) {
5429 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005430 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005431 break;
5432 case DisplayColorSetting::UNMANAGED:
5433 reply->writeBool(true);
5434 break;
5435 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005436 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005437 break;
5438 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005439 reply->writeBool(
5440 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005441 break;
5442 }
5443 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005444 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005445 // Is VrFlinger active?
5446 case 1028: {
5447 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005448 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005449 return NO_ERROR;
5450 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005451 // Set buffer size for SF tracing (value in KB)
5452 case 1029: {
5453 n = data.readInt32();
5454 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5455 ALOGW("Invalid buffer size: %d KB", n);
5456 reply->writeInt32(BAD_VALUE);
5457 return BAD_VALUE;
5458 }
5459
5460 ALOGD("Updating trace buffer to %d KB", n);
5461 mTracing.setBufferSize(n * 1024);
5462 reply->writeInt32(NO_ERROR);
5463 return NO_ERROR;
5464 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005465 // Is device color managed?
5466 case 1030: {
5467 reply->writeBool(useColorManagement);
5468 return NO_ERROR;
5469 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005470 // Override default composition data space
5471 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5472 // && adb shell stop zygote && adb shell start zygote
5473 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5474 // adb shell stop zygote && adb shell start zygote
5475 case 1031: {
5476 Mutex::Autolock _l(mStateLock);
5477 n = data.readInt32();
5478 if (n) {
5479 n = data.readInt32();
5480 if (n) {
5481 Dataspace dataspace = static_cast<Dataspace>(n);
5482 if (!validateCompositionDataspace(dataspace)) {
5483 return BAD_VALUE;
5484 }
5485 mDefaultCompositionDataspace = dataspace;
5486 }
5487 n = data.readInt32();
5488 if (n) {
5489 Dataspace dataspace = static_cast<Dataspace>(n);
5490 if (!validateCompositionDataspace(dataspace)) {
5491 return BAD_VALUE;
5492 }
5493 mWideColorGamutCompositionDataspace = dataspace;
5494 }
5495 } else {
5496 // restore composition data space.
5497 mDefaultCompositionDataspace = defaultCompositionDataspace;
5498 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5499 }
5500 return NO_ERROR;
5501 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005502 // Set trace flags
5503 case 1033: {
5504 n = data.readUint32();
5505 ALOGD("Updating trace flags to 0x%x", n);
5506 mTracing.setTraceFlags(n);
5507 reply->writeInt32(NO_ERROR);
5508 return NO_ERROR;
5509 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005510 case 1034: {
5511 // TODO(b/129297325): expose this via developer menu option
5512 n = data.readInt32();
5513 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005514 RefreshRateType type;
5515 {
5516 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5517 type = mDesiredActiveConfig.type;
5518 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005519 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005520 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005521 } else if (!n) {
5522 mRefreshRateOverlay.reset();
5523 }
5524 return NO_ERROR;
5525 }
Ady Abraham34392f72019-04-10 11:29:27 -07005526 case 1035: {
5527 n = data.readInt32();
5528 mDebugDisplayConfigSetByBackdoor = false;
5529 if (n >= 0) {
5530 const auto displayToken = getInternalDisplayToken();
5531 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5532 if (result != NO_ERROR) {
5533 return result;
5534 }
5535 mDebugDisplayConfigSetByBackdoor = true;
5536 }
5537 return NO_ERROR;
5538 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005539 }
5540 }
5541 return err;
5542}
5543
Steven Thomas6d8110b2017-08-31 18:24:21 -07005544void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005545 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005546 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005547}
5548
Ana Krulec7d1d6832018-12-27 11:10:09 -08005549void SurfaceFlinger::repaintEverythingForHWC() {
5550 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005551 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005552}
5553
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005554// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5555class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005556public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005557 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5558 ~WindowDisconnector() {
5559 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005560 }
5561
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005562private:
5563 ANativeWindow* mWindow;
5564 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005565};
5566
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005567status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005568 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5569 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005570 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005571 uint32_t reqWidth, uint32_t reqHeight,
5572 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005573 ISurfaceComposer::Rotation rotation,
5574 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005575 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005576
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005577 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005578
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005579 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5580
Chia-I Wu20261cb2018-08-23 12:55:44 -07005581 sp<DisplayDevice> display;
5582 {
5583 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005584
Chia-I Wu20261cb2018-08-23 12:55:44 -07005585 display = getDisplayDeviceLocked(displayToken);
5586 if (!display) return BAD_VALUE;
5587
Chia-I Wucb023152018-08-28 12:57:23 -07005588 // set the requested width/height to the logical display viewport size
5589 // by default
5590 if (reqWidth == 0 || reqHeight == 0) {
5591 reqWidth = uint32_t(display->getViewport().width());
5592 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005593 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005594 }
5595
Peiyong Lin0e003c92018-09-17 11:09:51 -07005596 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005597 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005598
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005599 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5600 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005601 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005602 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005603}
5604
chaviw93df2ea2019-04-30 16:45:12 -07005605static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5606 switch (colorMode) {
5607 case ColorMode::DISPLAY_P3:
5608 case ColorMode::BT2100_PQ:
5609 case ColorMode::BT2100_HLG:
5610 case ColorMode::DISPLAY_BT2020:
5611 return Dataspace::DISPLAY_P3;
5612 default:
5613 return Dataspace::V0_SRGB;
5614 }
5615}
5616
5617const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5618 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5619 if (displayToken) {
5620 return getDisplayDeviceLocked(displayToken);
5621 }
5622 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5623 // may not have a displayId.
5624 for (const auto& [token, display] : mDisplays) {
5625 if (display->getLayerStack() == displayOrLayerStack) {
5626 return display;
5627 }
5628 }
5629 return nullptr;
5630}
5631
5632status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5633 sp<GraphicBuffer>* outBuffer) {
5634 sp<DisplayDevice> display;
5635 uint32_t width;
5636 uint32_t height;
5637 ui::Transform::orientation_flags captureOrientation;
5638 {
5639 Mutex::Autolock _l(mStateLock);
5640 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5641 if (!display) {
5642 return BAD_VALUE;
5643 }
5644
5645 width = uint32_t(display->getViewport().width());
5646 height = uint32_t(display->getViewport().height());
5647
5648 captureOrientation = fromSurfaceComposerRotation(
5649 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005650 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5651 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5652 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5653 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5654 }
chaviw93df2ea2019-04-30 16:45:12 -07005655 *outDataspace =
5656 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5657 }
5658
5659 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5660 false /* captureSecureLayers */);
5661
5662 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5663 std::placeholders::_1);
5664 bool ignored = false;
5665 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5666 false /* useIdentityTransform */,
5667 ignored /* outCapturedSecureLayers */);
5668}
5669
Robert Carr866455f2019-04-02 16:28:26 -07005670status_t SurfaceFlinger::captureLayers(
5671 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5672 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5673 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5674 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005675 ATRACE_CALL();
5676
5677 class LayerRenderArea : public RenderArea {
5678 public:
Robert Carr578038f2018-03-09 12:25:24 -08005679 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005680 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5681 bool childrenOnly)
5682 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005683 mLayer(layer),
5684 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005685 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005686 mFlinger(flinger),
5687 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005688 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005689 Rect getBounds() const override {
5690 const Layer::State& layerState(mLayer->getDrawingState());
5691 return mLayer->getBufferSize(layerState);
5692 }
Marissa Wall61c58622018-07-18 10:12:20 -07005693 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005694 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005695 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005696 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005697 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005698 }
chaviwa76b2712017-09-20 12:02:26 -07005699 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005700 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005701 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005702 Rect getSourceCrop() const override {
5703 if (mCrop.isEmpty()) {
5704 return getBounds();
5705 } else {
5706 return mCrop;
5707 }
5708 }
Robert Carr578038f2018-03-09 12:25:24 -08005709 class ReparentForDrawing {
5710 public:
5711 const sp<Layer>& oldParent;
5712 const sp<Layer>& newParent;
5713
Vishnu Nair4351ad52019-02-11 14:13:02 -08005714 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5715 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005716 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005717 // Compute and cache the bounds for the new parent layer.
5718 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005719 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005720 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005721 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005722 };
5723
5724 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005725 const Rect sourceCrop = getSourceCrop();
5726 // no need to check rotation because there is none
5727 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5728 sourceCrop.height() != getReqHeight();
5729
Robert Carr578038f2018-03-09 12:25:24 -08005730 if (!mChildrenOnly) {
5731 mTransform = mLayer->getTransform().inverse();
5732 drawLayers();
5733 } else {
5734 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005735 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005736 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005737 bounds.getWidth(), bounds.getHeight(), 0,
5738 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005739
Vishnu Nair4351ad52019-02-11 14:13:02 -08005740 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005741 drawLayers();
5742 }
5743 }
chaviwa76b2712017-09-20 12:02:26 -07005744
chaviwa76b2712017-09-20 12:02:26 -07005745 private:
chaviw7206d492017-11-10 16:16:12 -08005746 const sp<Layer> mLayer;
5747 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005748
5749 // In the "childrenOnly" case we reparent the children to a screenshot
5750 // layer which has no properties set and which does not draw.
5751 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005752 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005753 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005754
5755 SurfaceFlinger* mFlinger;
5756 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005757 };
5758
Robert Carrc0df3122019-04-11 13:18:21 -07005759 int reqWidth = 0;
5760 int reqHeight = 0;
5761 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005762 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005763 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005764
Robert Carrc0df3122019-04-11 13:18:21 -07005765 {
5766 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005767
Robert Carrc0df3122019-04-11 13:18:21 -07005768 parent = fromHandle(layerHandleBinder);
5769 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5770 ALOGE("captureLayers called with an invalid or removed parent");
5771 return NAME_NOT_FOUND;
5772 }
5773
5774 const int uid = IPCThreadState::self()->getCallingUid();
5775 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5776 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5777 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5778 return PERMISSION_DENIED;
5779 }
5780
5781 if (sourceCrop.width() <= 0) {
5782 crop.left = 0;
5783 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5784 }
5785
5786 if (sourceCrop.height() <= 0) {
5787 crop.top = 0;
5788 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5789 }
5790 reqWidth = crop.width() * frameScale;
5791 reqHeight = crop.height() * frameScale;
5792
5793 for (const auto& handle : excludeHandles) {
5794 sp<Layer> excludeLayer = fromHandle(handle);
5795 if (excludeLayer != nullptr) {
5796 excludeLayers.emplace(excludeLayer);
5797 } else {
5798 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5799 return NAME_NOT_FOUND;
5800 }
5801 }
5802 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005803
Chia-I Wu20261cb2018-08-23 12:55:44 -07005804 // really small crop or frameScale
5805 if (reqWidth <= 0) {
5806 reqWidth = 1;
5807 }
5808 if (reqHeight <= 0) {
5809 reqHeight = 1;
5810 }
5811
Robert Carr866455f2019-04-02 16:28:26 -07005812 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5813 auto traverseLayers = [parent, childrenOnly,
5814 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005815 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5816 if (!layer->isVisible()) {
5817 return;
Robert Carr578038f2018-03-09 12:25:24 -08005818 } else if (childrenOnly && layer == parent.get()) {
5819 return;
chaviwa76b2712017-09-20 12:02:26 -07005820 }
Robert Carr866455f2019-04-02 16:28:26 -07005821
5822 sp<Layer> p = layer;
5823 while (p != nullptr) {
5824 if (excludeLayers.count(p) != 0) {
5825 return;
5826 }
5827 p = p->getParent();
5828 }
5829
chaviwa76b2712017-09-20 12:02:26 -07005830 visitor(layer);
5831 });
5832 };
Robert Carr108b2c72019-04-02 16:32:58 -07005833
5834 bool outCapturedSecureLayers = false;
5835 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5836 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005837}
5838
5839status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5840 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005841 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005842 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005843 bool useIdentityTransform,
5844 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005845 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005846
Peiyong Lin0e003c92018-09-17 11:09:51 -07005847 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005848 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5849 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005850 *outBuffer =
5851 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5852 static_cast<android_pixel_format>(reqPixelFormat), 1,
5853 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005854
Robert Carr108b2c72019-04-02 16:32:58 -07005855 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5856 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005857}
5858
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005859status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5860 TraverseLayersFunction traverseLayers,
5861 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005862 bool useIdentityTransform,
5863 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005864 // This mutex protects syncFd and captureResult for communication of the return values from the
5865 // main thread back to this Binder thread
5866 std::mutex captureMutex;
5867 std::condition_variable captureCondition;
5868 std::unique_lock<std::mutex> captureLock(captureMutex);
5869 int syncFd = -1;
5870 std::optional<status_t> captureResult;
5871
Robert Carr03480e22018-01-04 16:02:06 -08005872 const int uid = IPCThreadState::self()->getCallingUid();
5873 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5874
Dominik Laskowski8c001672018-05-30 16:52:06 -07005875 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005876 // If there is a refresh pending, bug out early and tell the binder thread to try again
5877 // after the refresh.
5878 if (mRefreshPending) {
5879 ATRACE_NAME("Skipping screenshot for now");
5880 std::unique_lock<std::mutex> captureLock(captureMutex);
5881 captureResult = std::make_optional<status_t>(EAGAIN);
5882 captureCondition.notify_one();
5883 return;
5884 }
5885
5886 status_t result = NO_ERROR;
5887 int fd = -1;
5888 {
5889 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005890 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005891 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005892 useIdentityTransform, forSystem, &fd,
5893 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005894 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005895 }
5896
5897 {
5898 std::unique_lock<std::mutex> captureLock(captureMutex);
5899 syncFd = fd;
5900 captureResult = std::make_optional<status_t>(result);
5901 captureCondition.notify_one();
5902 }
5903 });
5904
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005905 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005906 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005907 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005908 while (*captureResult == EAGAIN) {
5909 captureResult.reset();
5910 result = postMessageAsync(message);
5911 if (result != NO_ERROR) {
5912 return result;
5913 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005914 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005915 }
5916 result = *captureResult;
5917 }
5918
5919 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005920 sync_wait(syncFd, -1);
5921 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005922 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005923
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005924 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005925}
5926
chaviwa76b2712017-09-20 12:02:26 -07005927void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005928 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005929 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5930 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005931 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005932
chaviwa76b2712017-09-20 12:02:26 -07005933 const auto reqWidth = renderArea.getReqWidth();
5934 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005935 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005936 const auto transform = renderArea.getTransform();
5937 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005938
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005939 renderengine::DisplaySettings clientCompositionDisplay;
5940 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005941
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005942 // assume that bounds are never offset, and that they are the same as the
5943 // buffer bounds.
5944 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005945 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005946 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005947
5948 // Now take into account the rotation flag. We append a transform that
5949 // rotates the layer stack about the origin, then translate by buffer
5950 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005951 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005952 int displacementX = 0;
5953 int displacementY = 0;
5954 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5955 switch (rotation) {
5956 case ui::Transform::ROT_90:
5957 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005958 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005959 break;
5960 case ui::Transform::ROT_180:
5961 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005962 displacementY = renderArea.getBounds().getWidth();
5963 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005964 break;
5965 case ui::Transform::ROT_270:
5966 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005967 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005968 break;
5969 default:
5970 break;
5971 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005972
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005973 // We need to transform the clipping window into the right spot.
5974 // First, rotate the clipping rectangle by the rotation hint to get the
5975 // right orientation
5976 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5977 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5978 const vec4 rotClipTL = rotMatrix * clipTL;
5979 const vec4 rotClipBR = rotMatrix * clipBR;
5980 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5981 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5982 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5983 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5984
5985 // Now reposition the clipping rectangle with the displacement vector
5986 // computed above.
5987 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005988 clientCompositionDisplay.clip =
5989 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5990 newClipRight + displacementX, newClipBottom + displacementY);
5991
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005992 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005993 clientCompositionDisplay.globalTransform =
5994 clipTransform * clientCompositionDisplay.globalTransform;
5995
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005996 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5997 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005998
chaviw50da5042018-04-09 13:49:37 -07005999 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006000
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006001 renderengine::LayerSettings fillLayer;
6002 fillLayer.source.buffer.buffer = nullptr;
6003 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6004 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6005 fillLayer.alpha = half(alpha);
6006 clientCompositionLayers.push_back(fillLayer);
6007
6008 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006009 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006010 renderengine::LayerSettings layerSettings;
6011 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006012 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006013 if (prepared) {
6014 clientCompositionLayers.push_back(layerSettings);
6015 }
chaviwa76b2712017-09-20 12:02:26 -07006016 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006017
6018 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006019 // Use an empty fence for the buffer fence, since we just created the buffer so
6020 // there is no need for synchronization with the GPU.
6021 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006022 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006023 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006024 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006025 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006026
6027 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006028}
6029
chaviwa76b2712017-09-20 12:02:26 -07006030status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6031 TraverseLayersFunction traverseLayers,
6032 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006033 bool useIdentityTransform, bool forSystem,
6034 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006035 ATRACE_CALL();
6036
chaviwa76b2712017-09-20 12:02:26 -07006037 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006038 outCapturedSecureLayers =
6039 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006040 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006041
Robert Carr03480e22018-01-04 16:02:06 -08006042 // We allow the system server to take screenshots of secure layers for
6043 // use in situations like the Screen-rotation animation and place
6044 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006045 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006046 ALOGW("FB is protected: PERMISSION_DENIED");
6047 return PERMISSION_DENIED;
6048 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006049 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006050 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006051}
6052
chaviw95ef3c42019-02-14 10:55:09 -08006053void SurfaceFlinger::setInputWindowsFinished() {
6054 Mutex::Autolock _l(mStateLock);
6055
6056 mPendingSyncInputWindows = false;
6057 mTransactionCV.broadcast();
6058}
chaviw5f21a5e2019-02-14 10:00:34 -08006059
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006060// ---------------------------------------------------------------------------
6061
Dan Stoza412903f2017-04-27 13:42:17 -07006062void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6063 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006064}
6065
Dan Stoza412903f2017-04-27 13:42:17 -07006066void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6067 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006068}
6069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006070void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006071 const LayerVector::Visitor& visitor) {
6072 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006073 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006074 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006075 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006076 continue;
6077 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006078 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006079 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006080 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006081 return;
6082 }
chaviwa76b2712017-09-20 12:02:26 -07006083 if (!layer->isVisible()) {
6084 return;
6085 }
6086 visitor(layer);
6087 });
6088 }
6089}
6090
Dominik Laskowski22488f62019-03-28 09:53:04 -07006091void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6092 const std::vector<int32_t>& allowedConfigs) {
6093 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006094 return;
6095 }
6096
6097 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006098 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006099
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006100 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006101 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006102 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006103 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006104 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006105 setDesiredActiveConfig(
6106 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006107 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006108 }
6109 }
Ady Abraham838de062019-02-04 10:24:03 -08006110}
6111
Dominik Laskowski22488f62019-03-28 09:53:04 -07006112status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006113 const std::vector<int32_t>& allowedConfigs) {
6114 ATRACE_CALL();
6115
Dominik Laskowski22488f62019-03-28 09:53:04 -07006116 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006117 return BAD_VALUE;
6118 }
6119
Ady Abraham34392f72019-04-10 11:29:27 -07006120 if (mDebugDisplayConfigSetByBackdoor) {
6121 // ignore this request as config is overridden by backdoor
6122 return NO_ERROR;
6123 }
6124
Ady Abraham838de062019-02-04 10:24:03 -08006125 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006126 const auto display = getDisplayDeviceLocked(displayToken);
6127 if (!display) {
6128 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6129 displayToken.get());
6130 } else if (display->isVirtual()) {
6131 ALOGW("Attempt to set allowed display configs for virtual display");
6132 } else {
6133 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6134 }
Ady Abraham838de062019-02-04 10:24:03 -08006135 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006136
Ady Abraham838de062019-02-04 10:24:03 -08006137 return NO_ERROR;
6138}
6139
Dominik Laskowski22488f62019-03-28 09:53:04 -07006140status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006141 std::vector<int32_t>* outAllowedConfigs) {
6142 ATRACE_CALL();
6143
Dominik Laskowski22488f62019-03-28 09:53:04 -07006144 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006145 return BAD_VALUE;
6146 }
6147
Dominik Laskowski22488f62019-03-28 09:53:04 -07006148 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006149
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006150 const auto display = getDisplayDeviceLocked(displayToken);
6151 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006152 return NAME_NOT_FOUND;
6153 }
6154
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006155 if (display->isPrimary()) {
6156 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6157 }
6158
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006159 return NO_ERROR;
6160}
6161
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006162void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006163 mFlinger->setInputWindowsFinished();
6164}
6165
Robert Carrc0df3122019-04-11 13:18:21 -07006166sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6167 BBinder *b = handle->localBinder();
6168 if (b == nullptr) {
6169 return nullptr;
6170 }
6171 auto it = mLayersByLocalBinderToken.find(b);
6172 if (it != mLayersByLocalBinderToken.end()) {
6173 return it->second.promote();
6174 }
6175 return nullptr;
6176}
6177
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006178} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006179
Mathias Agopian3f844832013-08-07 21:24:32 -07006180#if defined(__gl_h_)
6181#error "don't include gl/gl.h in this file"
6182#endif
6183
6184#if defined(__gl2_h_)
6185#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006186#endif