• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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 ATRACE_TAG ATRACE_TAG_GRAPHICS
18 
19 #include <android-base/stringprintf.h>
20 #include <android/native_window.h>
21 #include <compositionengine/CompositionEngine.h>
22 #include <compositionengine/Display.h>
23 #include <compositionengine/DisplaySurface.h>
24 #include <compositionengine/RenderSurfaceCreationArgs.h>
25 #include <compositionengine/impl/DumpHelpers.h>
26 #include <compositionengine/impl/OutputCompositionState.h>
27 #include <compositionengine/impl/RenderSurface.h>
28 #include <log/log.h>
29 #include <renderengine/ExternalTexture.h>
30 #include <renderengine/RenderEngine.h>
31 #include <system/window.h>
32 #include <ui/GraphicBuffer.h>
33 #include <ui/Rect.h>
34 #include <utils/Trace.h>
35 
36 // TODO(b/129481165): remove the #pragma below and fix conversion issues
37 #pragma clang diagnostic push
38 #pragma clang diagnostic ignored "-Wconversion"
39 
40 #include "DisplayHardware/HWComposer.h"
41 
42 // TODO(b/129481165): remove the #pragma below and fix conversion issues
43 #pragma clang diagnostic pop // ignored "-Wconversion"
44 
45 namespace android::compositionengine {
46 
47 RenderSurface::~RenderSurface() = default;
48 
49 namespace impl {
50 
51 constexpr auto DEFAULT_USAGE = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
52 
createRenderSurface(const compositionengine::CompositionEngine & compositionEngine,compositionengine::Display & display,const compositionengine::RenderSurfaceCreationArgs & args)53 std::unique_ptr<compositionengine::RenderSurface> createRenderSurface(
54         const compositionengine::CompositionEngine& compositionEngine,
55         compositionengine::Display& display,
56         const compositionengine::RenderSurfaceCreationArgs& args) {
57     return std::make_unique<RenderSurface>(compositionEngine, display, args);
58 }
59 
RenderSurface(const CompositionEngine & compositionEngine,Display & display,const RenderSurfaceCreationArgs & args)60 RenderSurface::RenderSurface(const CompositionEngine& compositionEngine, Display& display,
61                              const RenderSurfaceCreationArgs& args)
62       : mCompositionEngine(compositionEngine),
63         mDisplay(display),
64         mNativeWindow(args.nativeWindow),
65         mDisplaySurface(args.displaySurface),
66         mSize(args.displayWidth, args.displayHeight),
67         mMaxTextureCacheSize(args.maxTextureCacheSize) {
68     LOG_ALWAYS_FATAL_IF(!mNativeWindow);
69 }
70 
~RenderSurface()71 RenderSurface::~RenderSurface() {
72     ANativeWindow* const window = mNativeWindow.get();
73     native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
74 }
75 
isValid() const76 bool RenderSurface::isValid() const {
77     return mSize.isValid();
78 }
79 
initialize()80 void RenderSurface::initialize() {
81     ANativeWindow* const window = mNativeWindow.get();
82 
83     int status = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
84     ALOGE_IF(status != NO_ERROR, "Unable to connect BQ producer: %d", status);
85     status = native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
86     ALOGE_IF(status != NO_ERROR, "Unable to set BQ format to RGBA888: %d", status);
87     status = native_window_set_usage(window, DEFAULT_USAGE);
88     ALOGE_IF(status != NO_ERROR, "Unable to set BQ usage bits for GPU rendering: %d", status);
89 }
90 
getSize() const91 const ui::Size& RenderSurface::getSize() const {
92     return mSize;
93 }
94 
getClientTargetAcquireFence() const95 const sp<Fence>& RenderSurface::getClientTargetAcquireFence() const {
96     return mDisplaySurface->getClientTargetAcquireFence();
97 }
98 
setDisplaySize(const ui::Size & size)99 void RenderSurface::setDisplaySize(const ui::Size& size) {
100     mDisplaySurface->resizeBuffers(size);
101     mSize = size;
102 }
103 
setBufferDataspace(ui::Dataspace dataspace)104 void RenderSurface::setBufferDataspace(ui::Dataspace dataspace) {
105     native_window_set_buffers_data_space(mNativeWindow.get(),
106                                          static_cast<android_dataspace>(dataspace));
107 }
108 
setBufferPixelFormat(ui::PixelFormat pixelFormat)109 void RenderSurface::setBufferPixelFormat(ui::PixelFormat pixelFormat) {
110     native_window_set_buffers_format(mNativeWindow.get(), static_cast<int32_t>(pixelFormat));
111 }
112 
setProtected(bool useProtected)113 void RenderSurface::setProtected(bool useProtected) {
114     uint64_t usageFlags = DEFAULT_USAGE;
115     if (useProtected) {
116         usageFlags |= GRALLOC_USAGE_PROTECTED;
117     }
118     const int status = native_window_set_usage(mNativeWindow.get(), usageFlags);
119     ALOGE_IF(status != NO_ERROR, "Unable to set BQ usage bits for protected content: %d", status);
120     if (status == NO_ERROR) {
121         mProtected = useProtected;
122     }
123 }
124 
beginFrame(bool mustRecompose)125 status_t RenderSurface::beginFrame(bool mustRecompose) {
126     return mDisplaySurface->beginFrame(mustRecompose);
127 }
128 
prepareFrame(bool usesClientComposition,bool usesDeviceComposition)129 void RenderSurface::prepareFrame(bool usesClientComposition, bool usesDeviceComposition) {
130     DisplaySurface::CompositionType compositionType;
131     if (usesClientComposition && usesDeviceComposition) {
132         compositionType = DisplaySurface::COMPOSITION_MIXED;
133     } else if (usesClientComposition) {
134         compositionType = DisplaySurface::COMPOSITION_GPU;
135     } else if (usesDeviceComposition) {
136         compositionType = DisplaySurface::COMPOSITION_HWC;
137     } else {
138         // Nothing to do -- when turning the screen off we get a frame like
139         // this. Call it a HWC frame since we won't be doing any GPU work but
140         // will do a prepare/set cycle.
141         compositionType = DisplaySurface::COMPOSITION_HWC;
142     }
143 
144     if (status_t result = mDisplaySurface->prepareFrame(compositionType); result != NO_ERROR) {
145         ALOGE("updateCompositionType failed for %s: %d (%s)", mDisplay.getName().c_str(), result,
146               strerror(-result));
147     }
148 }
149 
dequeueBuffer(base::unique_fd * bufferFence)150 std::shared_ptr<renderengine::ExternalTexture> RenderSurface::dequeueBuffer(
151         base::unique_fd* bufferFence) {
152     ATRACE_CALL();
153     int fd = -1;
154     ANativeWindowBuffer* buffer = nullptr;
155 
156     status_t result = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buffer, &fd);
157 
158     if (result != NO_ERROR) {
159         ALOGE("ANativeWindow::dequeueBuffer failed for display [%s] with error: %d",
160               mDisplay.getName().c_str(), result);
161         // Return fast here as we can't do much more - any rendering we do
162         // now will just be wrong.
163         return mTexture;
164     }
165 
166     ALOGW_IF(mTexture != nullptr, "Clobbering a non-null pointer to a buffer [%p].",
167              mTexture->getBuffer()->getNativeBuffer()->handle);
168 
169     sp<GraphicBuffer> newBuffer = GraphicBuffer::from(buffer);
170 
171     std::shared_ptr<renderengine::ExternalTexture> texture;
172 
173     for (auto it = mTextureCache.begin(); it != mTextureCache.end(); it++) {
174         const auto& cachedTexture = *it;
175         if (cachedTexture->getBuffer()->getId() == newBuffer->getId()) {
176             texture = cachedTexture;
177             mTextureCache.erase(it);
178             break;
179         }
180     }
181 
182     if (texture) {
183         mTexture = texture;
184     } else {
185         mTexture = std::make_shared<
186                 renderengine::ExternalTexture>(GraphicBuffer::from(buffer),
187                                                mCompositionEngine.getRenderEngine(),
188                                                renderengine::ExternalTexture::Usage::WRITEABLE);
189     }
190     mTextureCache.push_back(mTexture);
191     if (mTextureCache.size() > mMaxTextureCacheSize) {
192         mTextureCache.erase(mTextureCache.begin());
193     }
194 
195     *bufferFence = base::unique_fd(fd);
196 
197     return mTexture;
198 }
199 
queueBuffer(base::unique_fd readyFence)200 void RenderSurface::queueBuffer(base::unique_fd readyFence) {
201     auto& state = mDisplay.getState();
202 
203     if (state.usesClientComposition || state.flipClientTarget) {
204         // hasFlipClientTargetRequest could return true even if we haven't
205         // dequeued a buffer before. Try dequeueing one if we don't have a
206         // buffer ready.
207         if (mTexture == nullptr) {
208             ALOGI("Attempting to queue a client composited buffer without one "
209                   "previously dequeued for display [%s]. Attempting to dequeue "
210                   "a scratch buffer now",
211                   mDisplay.getName().c_str());
212             // We shouldn't deadlock here, since mTexture == nullptr only
213             // after a successful call to queueBuffer, or if dequeueBuffer has
214             // never been called.
215             base::unique_fd unused;
216             dequeueBuffer(&unused);
217         }
218 
219         if (mTexture == nullptr) {
220             ALOGE("No buffer is ready for display [%s]", mDisplay.getName().c_str());
221         } else {
222             status_t result = mNativeWindow->queueBuffer(mNativeWindow.get(),
223                                                          mTexture->getBuffer()->getNativeBuffer(),
224                                                          dup(readyFence));
225             if (result != NO_ERROR) {
226                 ALOGE("Error when queueing buffer for display [%s]: %d", mDisplay.getName().c_str(),
227                       result);
228                 // We risk blocking on dequeueBuffer if the primary display failed
229                 // to queue up its buffer, so crash here.
230                 if (!mDisplay.isVirtual()) {
231                     LOG_ALWAYS_FATAL("ANativeWindow::queueBuffer failed with error: %d", result);
232                 } else {
233                     mNativeWindow->cancelBuffer(mNativeWindow.get(),
234                                                 mTexture->getBuffer()->getNativeBuffer(),
235                                                 dup(readyFence));
236                 }
237             }
238 
239             mTexture = nullptr;
240         }
241     }
242 
243     status_t result = mDisplaySurface->advanceFrame();
244     if (result != NO_ERROR) {
245         ALOGE("[%s] failed pushing new frame to HWC: %d", mDisplay.getName().c_str(), result);
246     }
247 }
248 
onPresentDisplayCompleted()249 void RenderSurface::onPresentDisplayCompleted() {
250     mDisplaySurface->onFrameCommitted();
251 }
252 
flip()253 void RenderSurface::flip() {
254     mPageFlipCount++;
255 }
256 
dump(std::string & out) const257 void RenderSurface::dump(std::string& out) const {
258     using android::base::StringAppendF;
259 
260     out.append("   Composition RenderSurface State:");
261 
262     out.append("\n   ");
263 
264     dumpVal(out, "size", mSize);
265     StringAppendF(&out, "ANativeWindow=%p (format %d) ", mNativeWindow.get(),
266                   ANativeWindow_getFormat(mNativeWindow.get()));
267     dumpVal(out, "flips", mPageFlipCount);
268     out.append("\n");
269 
270     String8 surfaceDump;
271     mDisplaySurface->dumpAsString(surfaceDump);
272     out.append(surfaceDump);
273 }
274 
getPageFlipCount() const275 std::uint32_t RenderSurface::getPageFlipCount() const {
276     return mPageFlipCount;
277 }
278 
setPageFlipCountForTest(std::uint32_t count)279 void RenderSurface::setPageFlipCountForTest(std::uint32_t count) {
280     mPageFlipCount = count;
281 }
282 
setSizeForTest(const ui::Size & size)283 void RenderSurface::setSizeForTest(const ui::Size& size) {
284     mSize = size;
285 }
286 
mutableTextureForTest()287 std::shared_ptr<renderengine::ExternalTexture>& RenderSurface::mutableTextureForTest() {
288     return mTexture;
289 }
290 
291 } // namespace impl
292 } // namespace android::compositionengine
293