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