1 /*
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
17 // TODO(b/129481165): remove the #pragma below and fix conversion issues
18 #pragma clang diagnostic push
19 #pragma clang diagnostic ignored "-Wconversion"
20
21 // #define LOG_NDEBUG 0
22 #undef LOG_TAG
23 #define LOG_TAG "DisplayDevice"
24
25 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
26
27 #include <android-base/stringprintf.h>
28 #include <compositionengine/CompositionEngine.h>
29 #include <compositionengine/Display.h>
30 #include <compositionengine/DisplayColorProfile.h>
31 #include <compositionengine/DisplayColorProfileCreationArgs.h>
32 #include <compositionengine/DisplayCreationArgs.h>
33 #include <compositionengine/DisplaySurface.h>
34 #include <compositionengine/ProjectionSpace.h>
35 #include <compositionengine/RenderSurface.h>
36 #include <compositionengine/RenderSurfaceCreationArgs.h>
37 #include <compositionengine/impl/OutputCompositionState.h>
38 #include <configstore/Utils.h>
39 #include <log/log.h>
40 #include <system/window.h>
41 #include <ui/GraphicTypes.h>
42
43 #include "DisplayDevice.h"
44 #include "Layer.h"
45 #include "RefreshRateOverlay.h"
46 #include "SurfaceFlinger.h"
47
48 namespace android {
49
50 namespace hal = hardware::graphics::composer::hal;
51
52 using android::base::StringAppendF;
53
54 ui::Transform::RotationFlags DisplayDevice::sPrimaryDisplayRotationFlags = ui::Transform::ROT_0;
55
DisplayDeviceCreationArgs(const sp<SurfaceFlinger> & flinger,HWComposer & hwComposer,const wp<IBinder> & displayToken,std::shared_ptr<compositionengine::Display> compositionDisplay)56 DisplayDeviceCreationArgs::DisplayDeviceCreationArgs(
57 const sp<SurfaceFlinger>& flinger, HWComposer& hwComposer, const wp<IBinder>& displayToken,
58 std::shared_ptr<compositionengine::Display> compositionDisplay)
59 : flinger(flinger),
60 hwComposer(hwComposer),
61 displayToken(displayToken),
62 compositionDisplay(compositionDisplay) {}
63
DisplayDevice(DisplayDeviceCreationArgs & args)64 DisplayDevice::DisplayDevice(DisplayDeviceCreationArgs& args)
65 : mFlinger(args.flinger),
66 mHwComposer(args.hwComposer),
67 mDisplayToken(args.displayToken),
68 mSequenceId(args.sequenceId),
69 mConnectionType(args.connectionType),
70 mCompositionDisplay{args.compositionDisplay},
71 mActiveModeFPSTrace("ActiveModeFPS -" + to_string(getId())),
72 mActiveModeFPSHwcTrace("ActiveModeFPS_HWC -" + to_string(getId())),
73 mPhysicalOrientation(args.physicalOrientation),
74 mSupportedModes(std::move(args.supportedModes)),
75 mIsPrimary(args.isPrimary),
76 mRefreshRateConfigs(std::move(args.refreshRateConfigs)) {
77 mCompositionDisplay->editState().isSecure = args.isSecure;
78 mCompositionDisplay->createRenderSurface(
79 compositionengine::RenderSurfaceCreationArgsBuilder()
80 .setDisplayWidth(ANativeWindow_getWidth(args.nativeWindow.get()))
81 .setDisplayHeight(ANativeWindow_getHeight(args.nativeWindow.get()))
82 .setNativeWindow(std::move(args.nativeWindow))
83 .setDisplaySurface(std::move(args.displaySurface))
84 .setMaxTextureCacheSize(
85 static_cast<size_t>(SurfaceFlinger::maxFrameBufferAcquiredBuffers))
86 .build());
87
88 if (!mFlinger->mDisableClientCompositionCache &&
89 SurfaceFlinger::maxFrameBufferAcquiredBuffers > 0) {
90 mCompositionDisplay->createClientCompositionCache(
91 static_cast<uint32_t>(SurfaceFlinger::maxFrameBufferAcquiredBuffers));
92 }
93
94 mCompositionDisplay->createDisplayColorProfile(
95 compositionengine::DisplayColorProfileCreationArgs{args.hasWideColorGamut,
96 std::move(args.hdrCapabilities),
97 args.supportedPerFrameMetadata,
98 args.hwcColorModes});
99
100 if (!mCompositionDisplay->isValid()) {
101 ALOGE("Composition Display did not validate!");
102 }
103
104 mCompositionDisplay->getRenderSurface()->initialize();
105
106 setPowerMode(args.initialPowerMode);
107
108 // initialize the display orientation transform.
109 setProjection(ui::ROTATION_0, Rect::INVALID_RECT, Rect::INVALID_RECT);
110 }
111
112 DisplayDevice::~DisplayDevice() = default;
113
disconnect()114 void DisplayDevice::disconnect() {
115 mCompositionDisplay->disconnect();
116 }
117
getWidth() const118 int DisplayDevice::getWidth() const {
119 return mCompositionDisplay->getState().displaySpace.bounds.getWidth();
120 }
121
getHeight() const122 int DisplayDevice::getHeight() const {
123 return mCompositionDisplay->getState().displaySpace.bounds.getHeight();
124 }
125
setDisplayName(const std::string & displayName)126 void DisplayDevice::setDisplayName(const std::string& displayName) {
127 if (!displayName.empty()) {
128 // never override the name with an empty name
129 mDisplayName = displayName;
130 mCompositionDisplay->setName(displayName);
131 }
132 }
133
setDeviceProductInfo(std::optional<DeviceProductInfo> info)134 void DisplayDevice::setDeviceProductInfo(std::optional<DeviceProductInfo> info) {
135 mDeviceProductInfo = std::move(info);
136 }
137
getPageFlipCount() const138 uint32_t DisplayDevice::getPageFlipCount() const {
139 return mCompositionDisplay->getRenderSurface()->getPageFlipCount();
140 }
141
142 // ----------------------------------------------------------------------------
setPowerMode(hal::PowerMode mode)143 void DisplayDevice::setPowerMode(hal::PowerMode mode) {
144 mPowerMode = mode;
145 getCompositionDisplay()->setCompositionEnabled(mPowerMode != hal::PowerMode::OFF);
146 }
147
enableLayerCaching(bool enable)148 void DisplayDevice::enableLayerCaching(bool enable) {
149 getCompositionDisplay()->setLayerCachingEnabled(enable);
150 }
151
getPowerMode() const152 hal::PowerMode DisplayDevice::getPowerMode() const {
153 return mPowerMode;
154 }
155
isPoweredOn() const156 bool DisplayDevice::isPoweredOn() const {
157 return mPowerMode != hal::PowerMode::OFF;
158 }
159
setActiveMode(DisplayModeId id)160 void DisplayDevice::setActiveMode(DisplayModeId id) {
161 const auto mode = getMode(id);
162 LOG_FATAL_IF(!mode, "Cannot set active mode which is not supported.");
163 ATRACE_INT(mActiveModeFPSTrace.c_str(), mode->getFps().getIntValue());
164 mActiveMode = mode;
165 if (mRefreshRateConfigs) {
166 mRefreshRateConfigs->setCurrentModeId(mActiveMode->getId());
167 }
168 if (mRefreshRateOverlay) {
169 mRefreshRateOverlay->changeRefreshRate(mActiveMode->getFps());
170 }
171 }
172
initiateModeChange(const ActiveModeInfo & info,const hal::VsyncPeriodChangeConstraints & constraints,hal::VsyncPeriodChangeTimeline * outTimeline)173 status_t DisplayDevice::initiateModeChange(const ActiveModeInfo& info,
174 const hal::VsyncPeriodChangeConstraints& constraints,
175 hal::VsyncPeriodChangeTimeline* outTimeline) {
176 if (!info.mode || info.mode->getPhysicalDisplayId() != getPhysicalId()) {
177 ALOGE("Trying to initiate a mode change to invalid mode %s on display %s",
178 info.mode ? std::to_string(info.mode->getId().value()).c_str() : "null",
179 to_string(getId()).c_str());
180 return BAD_VALUE;
181 }
182 mUpcomingActiveMode = info;
183 ATRACE_INT(mActiveModeFPSHwcTrace.c_str(), info.mode->getFps().getIntValue());
184 return mHwComposer.setActiveModeWithConstraints(getPhysicalId(), info.mode->getHwcId(),
185 constraints, outTimeline);
186 }
187
getActiveMode() const188 const DisplayModePtr& DisplayDevice::getActiveMode() const {
189 return mActiveMode;
190 }
191
getSupportedModes() const192 const DisplayModes& DisplayDevice::getSupportedModes() const {
193 return mSupportedModes;
194 }
195
getMode(DisplayModeId modeId) const196 DisplayModePtr DisplayDevice::getMode(DisplayModeId modeId) const {
197 const auto it = std::find_if(mSupportedModes.begin(), mSupportedModes.end(),
198 [&](DisplayModePtr mode) { return mode->getId() == modeId; });
199 if (it != mSupportedModes.end()) {
200 return *it;
201 }
202 return nullptr;
203 }
204
getVsyncPeriodFromHWC() const205 nsecs_t DisplayDevice::getVsyncPeriodFromHWC() const {
206 const auto physicalId = getPhysicalId();
207 if (!mHwComposer.isConnected(physicalId)) {
208 return 0;
209 }
210
211 nsecs_t vsyncPeriod;
212 const auto status = mHwComposer.getDisplayVsyncPeriod(physicalId, &vsyncPeriod);
213 if (status == NO_ERROR) {
214 return vsyncPeriod;
215 }
216
217 return getActiveMode()->getFps().getPeriodNsecs();
218 }
219
getRefreshTimestamp() const220 nsecs_t DisplayDevice::getRefreshTimestamp() const {
221 const nsecs_t now = systemTime(CLOCK_MONOTONIC);
222 const auto vsyncPeriodNanos = getVsyncPeriodFromHWC();
223 return now - ((now - mLastHwVsync) % vsyncPeriodNanos);
224 }
225
onVsync(nsecs_t timestamp)226 void DisplayDevice::onVsync(nsecs_t timestamp) {
227 mLastHwVsync = timestamp;
228 }
229
getCompositionDataSpace() const230 ui::Dataspace DisplayDevice::getCompositionDataSpace() const {
231 return mCompositionDisplay->getState().dataspace;
232 }
233
setLayerStack(ui::LayerStack stack)234 void DisplayDevice::setLayerStack(ui::LayerStack stack) {
235 mCompositionDisplay->setLayerStackFilter(stack, isInternal());
236 if (mRefreshRateOverlay) {
237 mRefreshRateOverlay->setLayerStack(stack);
238 }
239 }
240
setFlags(uint32_t flags)241 void DisplayDevice::setFlags(uint32_t flags) {
242 mFlags = flags;
243 }
244
setDisplaySize(int width,int height)245 void DisplayDevice::setDisplaySize(int width, int height) {
246 LOG_FATAL_IF(!isVirtual(), "Changing the display size is supported only for virtual displays.");
247 const auto size = ui::Size(width, height);
248 mCompositionDisplay->setDisplaySize(size);
249 if (mRefreshRateOverlay) {
250 mRefreshRateOverlay->setViewport(size);
251 }
252 }
253
setProjection(ui::Rotation orientation,Rect layerStackSpaceRect,Rect orientedDisplaySpaceRect)254 void DisplayDevice::setProjection(ui::Rotation orientation, Rect layerStackSpaceRect,
255 Rect orientedDisplaySpaceRect) {
256 mOrientation = orientation;
257
258 if (isPrimary()) {
259 sPrimaryDisplayRotationFlags = ui::Transform::toRotationFlags(orientation);
260 }
261
262 if (!orientedDisplaySpaceRect.isValid()) {
263 // The destination frame can be invalid if it has never been set,
264 // in that case we assume the whole display size.
265 orientedDisplaySpaceRect = getCompositionDisplay()->getState().displaySpace.bounds;
266 }
267
268 if (layerStackSpaceRect.isEmpty()) {
269 // The layerStackSpaceRect can be invalid if it has never been set, in that case
270 // we assume the whole framebuffer size.
271 layerStackSpaceRect = getCompositionDisplay()->getState().framebufferSpace.bounds;
272 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
273 std::swap(layerStackSpaceRect.right, layerStackSpaceRect.bottom);
274 }
275 }
276
277 // We need to take care of display rotation for globalTransform for case if the panel is not
278 // installed aligned with device orientation.
279 const auto transformOrientation = orientation + mPhysicalOrientation;
280 getCompositionDisplay()->setProjection(transformOrientation, layerStackSpaceRect,
281 orientedDisplaySpaceRect);
282 }
283
getPrimaryDisplayRotationFlags()284 ui::Transform::RotationFlags DisplayDevice::getPrimaryDisplayRotationFlags() {
285 return sPrimaryDisplayRotationFlags;
286 }
287
getDebugName() const288 std::string DisplayDevice::getDebugName() const {
289 const char* type = "virtual";
290 if (mConnectionType) {
291 type = isInternal() ? "internal" : "external";
292 }
293
294 return base::StringPrintf("DisplayDevice{%s, %s%s, \"%s\"}", to_string(getId()).c_str(), type,
295 isPrimary() ? ", primary" : "", mDisplayName.c_str());
296 }
297
dump(std::string & result) const298 void DisplayDevice::dump(std::string& result) const {
299 StringAppendF(&result, "+ %s\n", getDebugName().c_str());
300 StringAppendF(&result, " powerMode=%s (%d)\n", to_string(mPowerMode).c_str(),
301 static_cast<int32_t>(mPowerMode));
302 const auto activeMode = getActiveMode();
303 StringAppendF(&result, " activeMode=%s\n",
304 activeMode ? to_string(*activeMode).c_str() : "none");
305
306 result.append(" supportedModes=\n");
307
308 for (const auto& mode : mSupportedModes) {
309 result.append(" ");
310 result.append(to_string(*mode));
311 result.append("\n");
312 }
313 StringAppendF(&result, " deviceProductInfo=");
314 if (mDeviceProductInfo) {
315 mDeviceProductInfo->dump(result);
316 } else {
317 result.append("{}");
318 }
319 result.append("\n");
320 getCompositionDisplay()->dump(result);
321
322 if (mRefreshRateConfigs) {
323 mRefreshRateConfigs->dump(result);
324 }
325 }
326
hasRenderIntent(ui::RenderIntent intent) const327 bool DisplayDevice::hasRenderIntent(ui::RenderIntent intent) const {
328 return mCompositionDisplay->getDisplayColorProfile()->hasRenderIntent(intent);
329 }
330
getId() const331 DisplayId DisplayDevice::getId() const {
332 return mCompositionDisplay->getId();
333 }
334
isSecure() const335 bool DisplayDevice::isSecure() const {
336 return mCompositionDisplay->isSecure();
337 }
338
getBounds() const339 const Rect& DisplayDevice::getBounds() const {
340 return mCompositionDisplay->getState().displaySpace.bounds;
341 }
342
getUndefinedRegion() const343 const Region& DisplayDevice::getUndefinedRegion() const {
344 return mCompositionDisplay->getState().undefinedRegion;
345 }
346
needsFiltering() const347 bool DisplayDevice::needsFiltering() const {
348 return mCompositionDisplay->getState().needsFiltering;
349 }
350
getLayerStack() const351 ui::LayerStack DisplayDevice::getLayerStack() const {
352 return mCompositionDisplay->getState().layerStackId;
353 }
354
getTransformHint() const355 ui::Transform::RotationFlags DisplayDevice::getTransformHint() const {
356 return mCompositionDisplay->getTransformHint();
357 }
358
getTransform() const359 const ui::Transform& DisplayDevice::getTransform() const {
360 return mCompositionDisplay->getState().transform;
361 }
362
getLayerStackSpaceRect() const363 const Rect& DisplayDevice::getLayerStackSpaceRect() const {
364 return mCompositionDisplay->getState().layerStackSpace.content;
365 }
366
getOrientedDisplaySpaceRect() const367 const Rect& DisplayDevice::getOrientedDisplaySpaceRect() const {
368 return mCompositionDisplay->getState().orientedDisplaySpace.content;
369 }
370
hasWideColorGamut() const371 bool DisplayDevice::hasWideColorGamut() const {
372 return mCompositionDisplay->getDisplayColorProfile()->hasWideColorGamut();
373 }
374
hasHDR10PlusSupport() const375 bool DisplayDevice::hasHDR10PlusSupport() const {
376 return mCompositionDisplay->getDisplayColorProfile()->hasHDR10PlusSupport();
377 }
378
hasHDR10Support() const379 bool DisplayDevice::hasHDR10Support() const {
380 return mCompositionDisplay->getDisplayColorProfile()->hasHDR10Support();
381 }
382
hasHLGSupport() const383 bool DisplayDevice::hasHLGSupport() const {
384 return mCompositionDisplay->getDisplayColorProfile()->hasHLGSupport();
385 }
386
hasDolbyVisionSupport() const387 bool DisplayDevice::hasDolbyVisionSupport() const {
388 return mCompositionDisplay->getDisplayColorProfile()->hasDolbyVisionSupport();
389 }
390
getSupportedPerFrameMetadata() const391 int DisplayDevice::getSupportedPerFrameMetadata() const {
392 return mCompositionDisplay->getDisplayColorProfile()->getSupportedPerFrameMetadata();
393 }
394
overrideHdrTypes(const std::vector<ui::Hdr> & hdrTypes)395 void DisplayDevice::overrideHdrTypes(const std::vector<ui::Hdr>& hdrTypes) {
396 mOverrideHdrTypes = hdrTypes;
397 }
398
getHdrCapabilities() const399 HdrCapabilities DisplayDevice::getHdrCapabilities() const {
400 const HdrCapabilities& capabilities =
401 mCompositionDisplay->getDisplayColorProfile()->getHdrCapabilities();
402 std::vector<ui::Hdr> hdrTypes = capabilities.getSupportedHdrTypes();
403 if (!mOverrideHdrTypes.empty()) {
404 hdrTypes = mOverrideHdrTypes;
405 }
406 return HdrCapabilities(hdrTypes, capabilities.getDesiredMaxLuminance(),
407 capabilities.getDesiredMaxAverageLuminance(),
408 capabilities.getDesiredMinLuminance());
409 }
410
enableRefreshRateOverlay(bool enable,bool showSpinnner)411 void DisplayDevice::enableRefreshRateOverlay(bool enable, bool showSpinnner) {
412 if (!enable) {
413 mRefreshRateOverlay.reset();
414 return;
415 }
416
417 const auto [lowFps, highFps] = mRefreshRateConfigs->getSupportedRefreshRateRange();
418 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*mFlinger, lowFps.getIntValue(),
419 highFps.getIntValue(), showSpinnner);
420 mRefreshRateOverlay->setLayerStack(getLayerStack());
421 mRefreshRateOverlay->setViewport(getSize());
422 mRefreshRateOverlay->changeRefreshRate(getActiveMode()->getFps());
423 }
424
onKernelTimerChanged(std::optional<DisplayModeId> desiredModeId,bool timerExpired)425 bool DisplayDevice::onKernelTimerChanged(std::optional<DisplayModeId> desiredModeId,
426 bool timerExpired) {
427 if (mRefreshRateConfigs && mRefreshRateOverlay) {
428 const auto newRefreshRate =
429 mRefreshRateConfigs->onKernelTimerChanged(desiredModeId, timerExpired);
430 if (newRefreshRate) {
431 mRefreshRateOverlay->changeRefreshRate(*newRefreshRate);
432 return true;
433 }
434 }
435
436 return false;
437 }
438
onInvalidate()439 void DisplayDevice::onInvalidate() {
440 if (mRefreshRateOverlay) {
441 mRefreshRateOverlay->onInvalidate();
442 }
443 }
444
setDesiredActiveMode(const ActiveModeInfo & info)445 bool DisplayDevice::setDesiredActiveMode(const ActiveModeInfo& info) {
446 ATRACE_CALL();
447
448 LOG_ALWAYS_FATAL_IF(!info.mode, "desired mode not provided");
449 LOG_ALWAYS_FATAL_IF(getPhysicalId() != info.mode->getPhysicalDisplayId(), "DisplayId mismatch");
450
451 ALOGV("%s(%s)", __func__, to_string(*info.mode).c_str());
452
453 std::scoped_lock lock(mActiveModeLock);
454 if (mDesiredActiveModeChanged) {
455 // If a mode change is pending, just cache the latest request in mDesiredActiveMode
456 const Scheduler::ModeEvent prevConfig = mDesiredActiveMode.event;
457 mDesiredActiveMode = info;
458 mDesiredActiveMode.event = mDesiredActiveMode.event | prevConfig;
459 return false;
460 }
461
462 // Check if we are already at the desired mode
463 if (getActiveMode()->getId() == info.mode->getId()) {
464 return false;
465 }
466
467 // Initiate a mode change.
468 mDesiredActiveModeChanged = true;
469 mDesiredActiveMode = info;
470 return true;
471 }
472
getDesiredActiveMode() const473 std::optional<DisplayDevice::ActiveModeInfo> DisplayDevice::getDesiredActiveMode() const {
474 std::scoped_lock lock(mActiveModeLock);
475 if (mDesiredActiveModeChanged) return mDesiredActiveMode;
476 return std::nullopt;
477 }
478
clearDesiredActiveModeState()479 void DisplayDevice::clearDesiredActiveModeState() {
480 std::scoped_lock lock(mActiveModeLock);
481 mDesiredActiveMode.event = Scheduler::ModeEvent::None;
482 mDesiredActiveModeChanged = false;
483 }
484
485 std::atomic<int32_t> DisplayDeviceState::sNextSequenceId(1);
486
487 } // namespace android
488
489 // TODO(b/129481165): remove the #pragma below and fix conversion issues
490 #pragma clang diagnostic pop // ignored "-Wconversion"
491