blob: 8d5984157a505c6f33b279026eb02234b25c8213 [file] [log] [blame]
Marissa Wall61c58622018-07-18 10:12:20 -07001/*
2 * Copyright (C) 2017 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//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "BufferStateLayer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
22#include "BufferStateLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070023
24#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070025#include <renderengine/Image.h>
Marissa Wall61c58622018-07-18 10:12:20 -070026
27namespace android {
28
Lloyd Pique42ab75e2018-09-12 20:46:03 -070029// clang-format off
30const std::array<float, 16> BufferStateLayer::IDENTITY_MATRIX{
31 1, 0, 0, 0,
32 0, 1, 0, 0,
33 0, 0, 1, 0,
34 0, 0, 0, 1
35};
36// clang-format on
Marissa Wall61c58622018-07-18 10:12:20 -070037
Lloyd Pique42ab75e2018-09-12 20:46:03 -070038BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args) : BufferLayer(args) {}
39BufferStateLayer::~BufferStateLayer() = default;
Marissa Wall61c58622018-07-18 10:12:20 -070040
41// -----------------------------------------------------------------------
42// Interface implementation for Layer
43// -----------------------------------------------------------------------
44void BufferStateLayer::onLayerDisplayed(const sp<Fence>& /*releaseFence*/) {
45 // TODO(marissaw): send the release fence back to buffer owner
46 return;
47}
48
49void BufferStateLayer::setTransformHint(uint32_t /*orientation*/) const {
50 // TODO(marissaw): send the transform hint to buffer owner
51 return;
52}
53
54void BufferStateLayer::releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) {
55 // TODO(marissaw): use this to signal the buffer owner
56 return;
57}
58
Ana Krulec010d2192018-10-08 06:29:54 -070059bool BufferStateLayer::shouldPresentNow(nsecs_t /*expectedPresentTime*/) const {
Marissa Wall61c58622018-07-18 10:12:20 -070060 if (getSidebandStreamChanged() || getAutoRefresh()) {
61 return true;
62 }
63
64 return hasDrawingBuffer();
65}
66
67bool BufferStateLayer::getTransformToDisplayInverse() const {
68 return mCurrentState.transformToDisplayInverse;
69}
70
71void BufferStateLayer::pushPendingState() {
72 if (!mCurrentState.modified) {
73 return;
74 }
75 mPendingStates.push_back(mCurrentState);
76 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
77}
78
79bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
80 const bool stateUpdateAvailable = !mPendingStates.empty();
81 while (!mPendingStates.empty()) {
82 popPendingState(stateToCommit);
83 }
84 mCurrentState.modified = false;
85 return stateUpdateAvailable;
86}
87
88Rect BufferStateLayer::getCrop(const Layer::State& s) const {
89 return (getEffectiveScalingMode() == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP)
90 ? GLConsumer::scaleDownCrop(s.crop, s.active.w, s.active.h)
91 : s.crop;
92}
93
94bool BufferStateLayer::setTransform(uint32_t transform) {
95 if (mCurrentState.transform == transform) return false;
96 mCurrentState.sequence++;
97 mCurrentState.transform = transform;
98 mCurrentState.modified = true;
99 setTransactionFlags(eTransactionNeeded);
100 return true;
101}
102
103bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
104 if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
105 mCurrentState.sequence++;
106 mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
107 mCurrentState.modified = true;
108 setTransactionFlags(eTransactionNeeded);
109 return true;
110}
111
112bool BufferStateLayer::setCrop(const Rect& crop) {
113 if (mCurrentState.crop == crop) return false;
114 mCurrentState.sequence++;
115 mCurrentState.crop = crop;
116 mCurrentState.modified = true;
117 setTransactionFlags(eTransactionNeeded);
118 return true;
119}
120
121bool BufferStateLayer::setBuffer(sp<GraphicBuffer> buffer) {
122 mCurrentState.sequence++;
123 mCurrentState.buffer = buffer;
124 mCurrentState.modified = true;
125 setTransactionFlags(eTransactionNeeded);
126 return true;
127}
128
129bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
130 mCurrentState.acquireFence = fence;
131 mCurrentState.modified = true;
132 setTransactionFlags(eTransactionNeeded);
133 return true;
134}
135
136bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
137 if (mCurrentState.dataspace == dataspace) return false;
138 mCurrentState.sequence++;
139 mCurrentState.dataspace = dataspace;
140 mCurrentState.modified = true;
141 setTransactionFlags(eTransactionNeeded);
142 return true;
143}
144
145bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
146 if (mCurrentState.hdrMetadata == hdrMetadata) return false;
147 mCurrentState.sequence++;
148 mCurrentState.hdrMetadata = hdrMetadata;
149 mCurrentState.modified = true;
150 setTransactionFlags(eTransactionNeeded);
151 return true;
152}
153
154bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
155 mCurrentState.sequence++;
156 mCurrentState.surfaceDamageRegion = surfaceDamage;
157 mCurrentState.modified = true;
158 setTransactionFlags(eTransactionNeeded);
159 return true;
160}
161
162bool BufferStateLayer::setApi(int32_t api) {
163 if (mCurrentState.api == api) return false;
164 mCurrentState.sequence++;
165 mCurrentState.api = api;
166 mCurrentState.modified = true;
167 setTransactionFlags(eTransactionNeeded);
168 return true;
169}
170
171bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
172 if (mCurrentState.sidebandStream == sidebandStream) return false;
173 mCurrentState.sequence++;
174 mCurrentState.sidebandStream = sidebandStream;
175 mCurrentState.modified = true;
176 setTransactionFlags(eTransactionNeeded);
177
178 if (!mSidebandStreamChanged.exchange(true)) {
179 // mSidebandStreamChanged was false
180 mFlinger->signalLayerUpdate();
181 }
182 return true;
183}
184
185bool BufferStateLayer::setSize(uint32_t w, uint32_t h) {
186 if (mCurrentState.active.w == w && mCurrentState.active.h == h) return false;
187 mCurrentState.active.w = w;
188 mCurrentState.active.h = h;
189 mCurrentState.modified = true;
190 setTransactionFlags(eTransactionNeeded);
191 return true;
192}
193
194bool BufferStateLayer::setPosition(float x, float y, bool /*immediate*/) {
195 if (mCurrentState.active.transform.tx() == x && mCurrentState.active.transform.ty() == y)
196 return false;
197
198 mCurrentState.active.transform.set(x, y);
199
200 mCurrentState.sequence++;
201 mCurrentState.modified = true;
202 setTransactionFlags(eTransactionNeeded);
203 return true;
204}
205
206bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
207 mCurrentState.transparentRegionHint = transparent;
208 mCurrentState.modified = true;
209 setTransactionFlags(eTransactionNeeded);
210 return true;
211}
212
213bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
214 bool allowNonRectPreservingTransforms) {
Peiyong Linefefaac2018-08-17 12:27:51 -0700215 ui::Transform t;
Marissa Wall61c58622018-07-18 10:12:20 -0700216 t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
217
218 if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
219 ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
220 return false;
221 }
222
223 mCurrentState.sequence++;
224 mCurrentState.active.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
225 mCurrentState.modified = true;
226 setTransactionFlags(eTransactionNeeded);
227 return true;
228}
229// -----------------------------------------------------------------------
230
231// -----------------------------------------------------------------------
232// Interface implementation for BufferLayer
233// -----------------------------------------------------------------------
234bool BufferStateLayer::fenceHasSignaled() const {
235 if (latchUnsignaledBuffers()) {
236 return true;
237 }
238
239 return getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
240}
241
242nsecs_t BufferStateLayer::getDesiredPresentTime() {
243 // TODO(marissaw): support an equivalent to desiredPresentTime for timestats metrics
244 return 0;
245}
246
247std::shared_ptr<FenceTime> BufferStateLayer::getCurrentFenceTime() const {
248 return std::make_shared<FenceTime>(getDrawingState().acquireFence);
249}
250
251void BufferStateLayer::getDrawingTransformMatrix(float *matrix) {
252 std::copy(std::begin(mTransformMatrix), std::end(mTransformMatrix), matrix);
253}
254
255uint32_t BufferStateLayer::getDrawingTransform() const {
256 return getDrawingState().transform;
257}
258
259ui::Dataspace BufferStateLayer::getDrawingDataSpace() const {
260 return getDrawingState().dataspace;
261}
262
263Rect BufferStateLayer::getDrawingCrop() const {
264 return Rect::INVALID_RECT;
265}
266
267uint32_t BufferStateLayer::getDrawingScalingMode() const {
268 return NATIVE_WINDOW_SCALING_MODE_FREEZE;
269}
270
271Region BufferStateLayer::getDrawingSurfaceDamage() const {
272 return getDrawingState().surfaceDamageRegion;
273}
274
275const HdrMetadata& BufferStateLayer::getDrawingHdrMetadata() const {
276 return getDrawingState().hdrMetadata;
277}
278
279int BufferStateLayer::getDrawingApi() const {
280 return getDrawingState().api;
281}
282
283PixelFormat BufferStateLayer::getPixelFormat() const {
284 return mActiveBuffer->format;
285}
286
287uint64_t BufferStateLayer::getFrameNumber() const {
288 return mFrameNumber;
289}
290
291bool BufferStateLayer::getAutoRefresh() const {
292 // TODO(marissaw): support shared buffer mode
293 return false;
294}
295
296bool BufferStateLayer::getSidebandStreamChanged() const {
297 return mSidebandStreamChanged.load();
298}
299
300std::optional<Region> BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
301 if (mSidebandStreamChanged.exchange(false)) {
302 const State& s(getDrawingState());
303 // mSidebandStreamChanged was true
304 // replicated in LayerBE until FE/BE is ready to be synchronized
305 getBE().compositionInfo.hwc.sidebandStream = s.sidebandStream;
306 if (getBE().compositionInfo.hwc.sidebandStream != nullptr) {
307 setTransactionFlags(eTransactionNeeded);
308 mFlinger->setTransactionFlags(eTraversalNeeded);
309 }
310 recomputeVisibleRegions = true;
311
312 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
313 }
314 return {};
315}
316
317bool BufferStateLayer::hasDrawingBuffer() const {
318 return getDrawingState().buffer != nullptr;
319}
320
321void BufferStateLayer::setFilteringEnabled(bool enabled) {
322 GLConsumer::computeTransformMatrix(mTransformMatrix.data(), mActiveBuffer, mCurrentCrop,
323 mCurrentTransform, enabled);
324}
325
Alec Mouri39801c02018-10-10 10:44:47 -0700326status_t BufferStateLayer::bindTextureImage() {
Marissa Wall61c58622018-07-18 10:12:20 -0700327 const State& s(getDrawingState());
328 auto& engine(mFlinger->getRenderEngine());
329
Marissa Wall61c58622018-07-18 10:12:20 -0700330 engine.checkErrors();
331
Alec Mouri39801c02018-10-10 10:44:47 -0700332 // TODO(marissaw): once buffers are cached, don't create a new image everytime
333 mTextureImage = engine.createImage();
Marissa Wall61c58622018-07-18 10:12:20 -0700334
335 bool created =
336 mTextureImage->setNativeWindowBuffer(s.buffer->getNativeBuffer(),
337 s.buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
338 if (!created) {
339 ALOGE("Failed to create image. size=%ux%u st=%u usage=%#" PRIx64 " fmt=%d",
340 s.buffer->getWidth(), s.buffer->getHeight(), s.buffer->getStride(),
341 s.buffer->getUsage(), s.buffer->getPixelFormat());
342 engine.bindExternalTextureImage(mTextureName, *engine.createImage());
343 return NO_INIT;
344 }
345
346 engine.bindExternalTextureImage(mTextureName, *mTextureImage);
347
348 // Wait for the new buffer to be ready.
349 if (s.acquireFence->isValid()) {
350 if (SyncFeatures::getInstance().useWaitSync()) {
351 base::unique_fd fenceFd(s.acquireFence->dup());
352 if (fenceFd == -1) {
353 ALOGE("error dup'ing fence fd: %d", errno);
354 return -errno;
355 }
356 if (!engine.waitFence(std::move(fenceFd))) {
357 ALOGE("failed to wait on fence fd");
358 return UNKNOWN_ERROR;
359 }
360 } else {
361 status_t err = s.acquireFence->waitForever("BufferStateLayer::bindTextureImage");
362 if (err != NO_ERROR) {
363 ALOGE("error waiting for fence: %d", err);
364 return err;
365 }
366 }
367 }
368
369 return NO_ERROR;
370}
371
Alec Mouri86770e52018-09-24 22:40:58 +0000372status_t BufferStateLayer::updateTexImage(bool& /*recomputeVisibleRegions*/, nsecs_t latchTime,
373 const sp<Fence>& releaseFence) {
Marissa Wall61c58622018-07-18 10:12:20 -0700374 const State& s(getDrawingState());
375
376 if (!s.buffer) {
377 return NO_ERROR;
378 }
379
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700380 const int32_t layerID = getSequence();
381
Marissa Wall61c58622018-07-18 10:12:20 -0700382 // Reject if the layer is invalid
383 uint32_t bufferWidth = s.buffer->width;
384 uint32_t bufferHeight = s.buffer->height;
385
Peiyong Linefefaac2018-08-17 12:27:51 -0700386 if (s.transform & ui::Transform::ROT_90) {
Peiyong Lin3db42342018-08-16 09:15:59 -0700387 std::swap(bufferWidth, bufferHeight);
Marissa Wall61c58622018-07-18 10:12:20 -0700388 }
389
390 if (s.transformToDisplayInverse) {
391 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
Peiyong Linefefaac2018-08-17 12:27:51 -0700392 if (invTransform & ui::Transform::ROT_90) {
Peiyong Lin3db42342018-08-16 09:15:59 -0700393 std::swap(bufferWidth, bufferHeight);
Marissa Wall61c58622018-07-18 10:12:20 -0700394 }
395 }
396
397 if (mOverrideScalingMode == NATIVE_WINDOW_SCALING_MODE_FREEZE &&
398 (s.active.w != bufferWidth || s.active.h != bufferHeight)) {
399 ALOGE("[%s] rejecting buffer: "
400 "bufferWidth=%d, bufferHeight=%d, front.active.{w=%d, h=%d}",
401 mName.string(), bufferWidth, bufferHeight, s.active.w, s.active.h);
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700402 mTimeStats.removeTimeRecord(layerID, getFrameNumber());
Marissa Wall61c58622018-07-18 10:12:20 -0700403 return BAD_VALUE;
404 }
405
406 // Handle sync fences
Alec Mouri86770e52018-09-24 22:40:58 +0000407 if (SyncFeatures::getInstance().useNativeFenceSync() && releaseFence != Fence::NO_FENCE) {
408 // TODO(alecmouri): Fail somewhere upstream if the fence is invalid.
409 if (!releaseFence->isValid()) {
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700410 mTimeStats.clearLayerRecord(layerID);
Marissa Wall61c58622018-07-18 10:12:20 -0700411 return UNKNOWN_ERROR;
412 }
413
Marissa Wall61c58622018-07-18 10:12:20 -0700414 // Check status of fences first because merging is expensive.
415 // Merging an invalid fence with any other fence results in an
416 // invalid fence.
417 auto currentStatus = s.acquireFence->getStatus();
418 if (currentStatus == Fence::Status::Invalid) {
419 ALOGE("Existing fence has invalid state");
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700420 mTimeStats.clearLayerRecord(layerID);
Marissa Wall61c58622018-07-18 10:12:20 -0700421 return BAD_VALUE;
422 }
423
Alec Mouri86770e52018-09-24 22:40:58 +0000424 auto incomingStatus = releaseFence->getStatus();
Marissa Wall61c58622018-07-18 10:12:20 -0700425 if (incomingStatus == Fence::Status::Invalid) {
426 ALOGE("New fence has invalid state");
Alec Mouri86770e52018-09-24 22:40:58 +0000427 mDrawingState.acquireFence = releaseFence;
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700428 mTimeStats.clearLayerRecord(layerID);
Marissa Wall61c58622018-07-18 10:12:20 -0700429 return BAD_VALUE;
430 }
431
432 // If both fences are signaled or both are unsignaled, we need to merge
433 // them to get an accurate timestamp.
434 if (currentStatus == incomingStatus) {
435 char fenceName[32] = {};
436 snprintf(fenceName, 32, "%.28s:%d", mName.string(), mFrameNumber);
Alec Mouri86770e52018-09-24 22:40:58 +0000437 sp<Fence> mergedFence =
438 Fence::merge(fenceName, mDrawingState.acquireFence, releaseFence);
Marissa Wall61c58622018-07-18 10:12:20 -0700439 if (!mergedFence.get()) {
440 ALOGE("failed to merge release fences");
441 // synchronization is broken, the best we can do is hope fences
442 // signal in order so the new fence will act like a union
Alec Mouri86770e52018-09-24 22:40:58 +0000443 mDrawingState.acquireFence = releaseFence;
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700444 mTimeStats.clearLayerRecord(layerID);
Marissa Wall61c58622018-07-18 10:12:20 -0700445 return BAD_VALUE;
446 }
447 mDrawingState.acquireFence = mergedFence;
448 } else if (incomingStatus == Fence::Status::Unsignaled) {
449 // If one fence has signaled and the other hasn't, the unsignaled
450 // fence will approximately correspond with the correct timestamp.
451 // There's a small race if both fences signal at about the same time
452 // and their statuses are retrieved with unfortunate timing. However,
453 // by this point, they will have both signaled and only the timestamp
454 // will be slightly off; any dependencies after this point will
455 // already have been met.
Alec Mouri86770e52018-09-24 22:40:58 +0000456 mDrawingState.acquireFence = releaseFence;
Marissa Wall61c58622018-07-18 10:12:20 -0700457 }
458 } else {
459 // Bind the new buffer to the GL texture.
460 //
461 // Older devices require the "implicit" synchronization provided
462 // by glEGLImageTargetTexture2DOES, which this method calls. Newer
463 // devices will either call this in Layer::onDraw, or (if it's not
464 // a GL-composited layer) not at all.
465 status_t err = bindTextureImage();
466 if (err != NO_ERROR) {
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700467 mTimeStats.clearLayerRecord(layerID);
Marissa Wall61c58622018-07-18 10:12:20 -0700468 return BAD_VALUE;
469 }
470 }
471
472 // TODO(marissaw): properly support mTimeStats
Yiwei Zhang8e8fe522018-11-02 18:34:07 -0700473 mTimeStats.setPostTime(layerID, getFrameNumber(), getName().c_str(), latchTime);
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700474 mTimeStats.setAcquireFence(layerID, getFrameNumber(), getCurrentFenceTime());
475 mTimeStats.setLatchTime(layerID, getFrameNumber(), latchTime);
Marissa Wall61c58622018-07-18 10:12:20 -0700476
477 return NO_ERROR;
478}
479
480status_t BufferStateLayer::updateActiveBuffer() {
481 const State& s(getDrawingState());
482
483 if (s.buffer == nullptr) {
484 return BAD_VALUE;
485 }
486
487 mActiveBuffer = s.buffer;
488 getBE().compositionInfo.mBuffer = mActiveBuffer;
489 getBE().compositionInfo.mBufferSlot = 0;
490
491 return NO_ERROR;
492}
493
494status_t BufferStateLayer::updateFrameNumber(nsecs_t /*latchTime*/) {
495 // TODO(marissaw): support frame history events
496 mCurrentFrameNumber = mFrameNumber;
497 return NO_ERROR;
498}
499
Dominik Laskowski075d3172018-05-24 15:50:06 -0700500void BufferStateLayer::setHwcLayerBuffer(DisplayId displayId) {
Marissa Wall61c58622018-07-18 10:12:20 -0700501 auto& hwcInfo = getBE().mHwcLayers[displayId];
502 auto& hwcLayer = hwcInfo.layer;
503
504 const State& s(getDrawingState());
505
506 // TODO(marissaw): support more than one slot
507 uint32_t hwcSlot = 0;
508
509 auto error = hwcLayer->setBuffer(hwcSlot, s.buffer, s.acquireFence);
510 if (error != HWC2::Error::None) {
511 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
512 s.buffer->handle, to_string(error).c_str(), static_cast<int32_t>(error));
513 }
514
515 mFrameNumber++;
516}
517
518void BufferStateLayer::onFirstRef() {
Dan Stoza7b1b5a82018-07-31 16:00:21 -0700519 BufferLayer::onFirstRef();
520
Marissa Wall61c58622018-07-18 10:12:20 -0700521 if (const auto display = mFlinger->getDefaultDisplayDevice()) {
522 updateTransformHint(display);
523 }
524}
525
526} // namespace android