1 /*
2  * Copyright (C) 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 #include "VulkanSurface.h"
18 
19 #include <GrDirectContext.h>
20 #include <SkSurface.h>
21 #include <algorithm>
22 
23 #include <gui/TraceUtils.h>
24 #include "VulkanManager.h"
25 #include "utils/Color.h"
26 
27 #undef LOG_TAG
28 #define LOG_TAG "VulkanSurface"
29 
30 namespace android {
31 namespace uirenderer {
32 namespace renderthread {
33 
InvertTransform(int transform)34 static int InvertTransform(int transform) {
35     switch (transform) {
36         case ANATIVEWINDOW_TRANSFORM_ROTATE_90:
37             return ANATIVEWINDOW_TRANSFORM_ROTATE_270;
38         case ANATIVEWINDOW_TRANSFORM_ROTATE_180:
39             return ANATIVEWINDOW_TRANSFORM_ROTATE_180;
40         case ANATIVEWINDOW_TRANSFORM_ROTATE_270:
41             return ANATIVEWINDOW_TRANSFORM_ROTATE_90;
42         default:
43             return 0;
44     }
45 }
46 
GetPreTransformMatrix(SkISize windowSize,int transform)47 static SkMatrix GetPreTransformMatrix(SkISize windowSize, int transform) {
48     const int width = windowSize.width();
49     const int height = windowSize.height();
50 
51     switch (transform) {
52         case 0:
53             return SkMatrix::I();
54         case ANATIVEWINDOW_TRANSFORM_ROTATE_90:
55             return SkMatrix::MakeAll(0, -1, height, 1, 0, 0, 0, 0, 1);
56         case ANATIVEWINDOW_TRANSFORM_ROTATE_180:
57             return SkMatrix::MakeAll(-1, 0, width, 0, -1, height, 0, 0, 1);
58         case ANATIVEWINDOW_TRANSFORM_ROTATE_270:
59             return SkMatrix::MakeAll(0, 1, 0, -1, 0, width, 0, 0, 1);
60         default:
61             LOG_ALWAYS_FATAL("Unsupported Window Transform (%d)", transform);
62     }
63     return SkMatrix::I();
64 }
65 
GetPixelSnapMatrix(SkISize windowSize,int transform)66 static SkM44 GetPixelSnapMatrix(SkISize windowSize, int transform) {
67     // Small (~1/16th) nudge to ensure that pixel-aligned non-AA'd draws fill the
68     // desired fragment
69     static const SkScalar kOffset = 0.063f;
70     SkMatrix preRotation = GetPreTransformMatrix(windowSize, transform);
71     SkMatrix invert;
72     LOG_ALWAYS_FATAL_IF(!preRotation.invert(&invert));
73     return SkM44::Translate(kOffset, kOffset)
74             .postConcat(SkM44(preRotation))
75             .preConcat(SkM44(invert));
76 }
77 
ConnectAndSetWindowDefaults(ANativeWindow * window)78 static bool ConnectAndSetWindowDefaults(ANativeWindow* window) {
79     ATRACE_CALL();
80 
81     int err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
82     if (err != 0) {
83         ALOGE("native_window_api_connect failed: %s (%d)", strerror(-err), err);
84         return false;
85     }
86 
87     // this will match what we do on GL so pick that here.
88     err = window->setSwapInterval(window, 1);
89     if (err != 0) {
90         ALOGE("native_window->setSwapInterval(1) failed: %s (%d)", strerror(-err), err);
91         return false;
92     }
93 
94     err = native_window_set_shared_buffer_mode(window, false);
95     if (err != 0) {
96         ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)", strerror(-err), err);
97         return false;
98     }
99 
100     err = native_window_set_auto_refresh(window, false);
101     if (err != 0) {
102         ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)", strerror(-err), err);
103         return false;
104     }
105 
106     err = native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_FREEZE);
107     if (err != 0) {
108         ALOGE("native_window_set_scaling_mode(NATIVE_WINDOW_SCALING_MODE_FREEZE) failed: %s (%d)",
109               strerror(-err), err);
110         return false;
111     }
112 
113     // Let consumer drive the size of the buffers.
114     err = native_window_set_buffers_dimensions(window, 0, 0);
115     if (err != 0) {
116         ALOGE("native_window_set_buffers_dimensions(0,0) failed: %s (%d)", strerror(-err), err);
117         return false;
118     }
119 
120     // Enable auto prerotation, so when buffer size is driven by the consumer
121     // and the transform hint specifies a 90 or 270 degree rotation, the width
122     // and height used for buffer pre-allocation and dequeueBuffer will be
123     // additionally swapped.
124     err = native_window_set_auto_prerotation(window, true);
125     if (err != 0) {
126         ALOGE("VulkanSurface::UpdateWindow() native_window_set_auto_prerotation failed: %s (%d)",
127               strerror(-err), err);
128         return false;
129     }
130 
131     return true;
132 }
133 
Create(ANativeWindow * window,ColorMode colorMode,SkColorType colorType,sk_sp<SkColorSpace> colorSpace,GrDirectContext * grContext,const VulkanManager & vkManager,uint32_t extraBuffers)134 VulkanSurface* VulkanSurface::Create(ANativeWindow* window, ColorMode colorMode,
135                                      SkColorType colorType, sk_sp<SkColorSpace> colorSpace,
136                                      GrDirectContext* grContext, const VulkanManager& vkManager,
137                                      uint32_t extraBuffers) {
138     // Connect and set native window to default configurations.
139     if (!ConnectAndSetWindowDefaults(window)) {
140         return nullptr;
141     }
142 
143     // Initialize WindowInfo struct.
144     WindowInfo windowInfo;
145     if (!InitializeWindowInfoStruct(window, colorMode, colorType, colorSpace, vkManager,
146                                     extraBuffers, &windowInfo)) {
147         return nullptr;
148     }
149 
150     // Now we attempt to modify the window.
151     if (!UpdateWindow(window, windowInfo)) {
152         return nullptr;
153     }
154 
155     return new VulkanSurface(window, windowInfo, grContext);
156 }
157 
InitializeWindowInfoStruct(ANativeWindow * window,ColorMode colorMode,SkColorType colorType,sk_sp<SkColorSpace> colorSpace,const VulkanManager & vkManager,uint32_t extraBuffers,WindowInfo * outWindowInfo)158 bool VulkanSurface::InitializeWindowInfoStruct(ANativeWindow* window, ColorMode colorMode,
159                                                SkColorType colorType,
160                                                sk_sp<SkColorSpace> colorSpace,
161                                                const VulkanManager& vkManager,
162                                                uint32_t extraBuffers, WindowInfo* outWindowInfo) {
163     ATRACE_CALL();
164 
165     int width, height;
166     int err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
167     if (err != 0 || width < 0) {
168         ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err, width);
169         return false;
170     }
171     err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
172     if (err != 0 || height < 0) {
173         ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err, height);
174         return false;
175     }
176     outWindowInfo->size = SkISize::Make(width, height);
177 
178     int query_value;
179     err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &query_value);
180     if (err != 0 || query_value < 0) {
181         ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err, query_value);
182         return false;
183     }
184     outWindowInfo->transform = query_value;
185 
186     outWindowInfo->actualSize = outWindowInfo->size;
187     if (outWindowInfo->transform & ANATIVEWINDOW_TRANSFORM_ROTATE_90) {
188         outWindowInfo->actualSize.set(outWindowInfo->size.height(), outWindowInfo->size.width());
189     }
190 
191     outWindowInfo->preTransform =
192             GetPreTransformMatrix(outWindowInfo->size, outWindowInfo->transform);
193     outWindowInfo->pixelSnapMatrix =
194             GetPixelSnapMatrix(outWindowInfo->size, outWindowInfo->transform);
195 
196     err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &query_value);
197     if (err != 0 || query_value < 0) {
198         ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err, query_value);
199         return false;
200     }
201     outWindowInfo->bufferCount =
202             static_cast<uint32_t>(query_value) + sTargetBufferCount + extraBuffers;
203 
204     err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
205     if (err != 0 || query_value < 0) {
206         ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err, query_value);
207         return false;
208     }
209     if (outWindowInfo->bufferCount > static_cast<uint32_t>(query_value)) {
210         // Application must settle for fewer images than desired:
211         outWindowInfo->bufferCount = static_cast<uint32_t>(query_value);
212     }
213 
214     outWindowInfo->bufferFormat = ColorTypeToBufferFormat(colorType);
215     outWindowInfo->colorspace = colorSpace;
216     outWindowInfo->colorMode = colorMode;
217 
218     if (colorMode == ColorMode::Hdr || colorMode == ColorMode::Hdr10) {
219         outWindowInfo->dataspace =
220                 static_cast<android_dataspace>(STANDARD_DCI_P3 | TRANSFER_SRGB | RANGE_EXTENDED);
221     } else {
222         outWindowInfo->dataspace = ColorSpaceToADataSpace(colorSpace.get(), colorType);
223     }
224     LOG_ALWAYS_FATAL_IF(
225             outWindowInfo->dataspace == HAL_DATASPACE_UNKNOWN && colorType != kAlpha_8_SkColorType,
226             "Unsupported colorspace");
227 
228     VkFormat vkPixelFormat;
229     switch (colorType) {
230         case kRGBA_8888_SkColorType:
231             vkPixelFormat = VK_FORMAT_R8G8B8A8_UNORM;
232             break;
233         case kRGBA_F16_SkColorType:
234             vkPixelFormat = VK_FORMAT_R16G16B16A16_SFLOAT;
235             break;
236         case kRGBA_1010102_SkColorType:
237             vkPixelFormat = VK_FORMAT_A2B10G10R10_UNORM_PACK32;
238             break;
239         case kAlpha_8_SkColorType:
240             vkPixelFormat = VK_FORMAT_R8_UNORM;
241             break;
242         default:
243             LOG_ALWAYS_FATAL("Unsupported colorType: %d", (int)colorType);
244     }
245 
246     LOG_ALWAYS_FATAL_IF(nullptr == vkManager.mGetPhysicalDeviceImageFormatProperties2,
247                         "vkGetPhysicalDeviceImageFormatProperties2 is missing");
248     VkPhysicalDeviceExternalImageFormatInfo externalImageFormatInfo;
249     externalImageFormatInfo.sType =
250             VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO;
251     externalImageFormatInfo.pNext = nullptr;
252     externalImageFormatInfo.handleType =
253             VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
254 
255     VkPhysicalDeviceImageFormatInfo2 imageFormatInfo;
256     imageFormatInfo.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
257     imageFormatInfo.pNext = &externalImageFormatInfo;
258     imageFormatInfo.format = vkPixelFormat;
259     imageFormatInfo.type = VK_IMAGE_TYPE_2D;
260     imageFormatInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
261     // Currently Skia requires the images to be color attachments and support all transfer
262     // operations.
263     imageFormatInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
264                             VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
265     imageFormatInfo.flags = 0;
266 
267     VkAndroidHardwareBufferUsageANDROID hwbUsage;
268     hwbUsage.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_USAGE_ANDROID;
269     hwbUsage.pNext = nullptr;
270 
271     VkImageFormatProperties2 imgFormProps;
272     imgFormProps.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2;
273     imgFormProps.pNext = &hwbUsage;
274 
275     VkResult res = vkManager.mGetPhysicalDeviceImageFormatProperties2(
276             vkManager.mPhysicalDevice, &imageFormatInfo, &imgFormProps);
277     if (VK_SUCCESS != res) {
278         ALOGE("Failed to query GetPhysicalDeviceImageFormatProperties2");
279         return false;
280     }
281 
282     uint64_t consumerUsage;
283     err = native_window_get_consumer_usage(window, &consumerUsage);
284     if (err != 0) {
285         ALOGE("native_window_get_consumer_usage failed: %s (%d)", strerror(-err), err);
286         return false;
287     }
288     outWindowInfo->windowUsageFlags = consumerUsage | hwbUsage.androidHardwareBufferUsage;
289 
290     return true;
291 }
292 
UpdateWindow(ANativeWindow * window,const WindowInfo & windowInfo)293 bool VulkanSurface::UpdateWindow(ANativeWindow* window, const WindowInfo& windowInfo) {
294     ATRACE_CALL();
295 
296     int err = native_window_set_buffers_format(window, windowInfo.bufferFormat);
297     if (err != 0) {
298         ALOGE("VulkanSurface::UpdateWindow() native_window_set_buffers_format(%d) failed: %s (%d)",
299               windowInfo.bufferFormat, strerror(-err), err);
300         return false;
301     }
302 
303     err = native_window_set_buffers_data_space(window, windowInfo.dataspace);
304     if (err != 0) {
305         ALOGE("VulkanSurface::UpdateWindow() native_window_set_buffers_data_space(%d) "
306               "failed: %s (%d)",
307               windowInfo.dataspace, strerror(-err), err);
308         return false;
309     }
310 
311     // native_window_set_buffers_transform() expects the transform the app is requesting that
312     // the compositor perform during composition. With native windows, pre-transform works by
313     // rendering with the same transform the compositor is applying (as in Vulkan), but
314     // then requesting the inverse transform, so that when the compositor does
315     // it's job the two transforms cancel each other out and the compositor ends
316     // up applying an identity transform to the app's buffer.
317     err = native_window_set_buffers_transform(window, InvertTransform(windowInfo.transform));
318     if (err != 0) {
319         ALOGE("VulkanSurface::UpdateWindow() native_window_set_buffers_transform(%d) "
320               "failed: %s (%d)",
321               windowInfo.transform, strerror(-err), err);
322         return false;
323     }
324 
325     err = native_window_set_buffer_count(window, windowInfo.bufferCount);
326     if (err != 0) {
327         ALOGE("VulkanSurface::UpdateWindow() native_window_set_buffer_count(%zu) failed: %s (%d)",
328               windowInfo.bufferCount, strerror(-err), err);
329         return false;
330     }
331 
332     err = native_window_set_usage(window, windowInfo.windowUsageFlags);
333     if (err != 0) {
334         ALOGE("VulkanSurface::UpdateWindow() native_window_set_usage failed: %s (%d)",
335               strerror(-err), err);
336         return false;
337     }
338 
339     return true;
340 }
341 
VulkanSurface(ANativeWindow * window,const WindowInfo & windowInfo,GrDirectContext * grContext)342 VulkanSurface::VulkanSurface(ANativeWindow* window, const WindowInfo& windowInfo,
343                              GrDirectContext* grContext)
344         : mNativeWindow(window), mWindowInfo(windowInfo), mGrContext(grContext) {}
345 
~VulkanSurface()346 VulkanSurface::~VulkanSurface() {
347     releaseBuffers();
348 
349     // release the native window to be available for use by other clients
350     int err = native_window_api_disconnect(mNativeWindow.get(), NATIVE_WINDOW_API_EGL);
351     ALOGW_IF(err != 0, "native_window_api_disconnect failed: %s (%d)", strerror(-err), err);
352 }
353 
releaseBuffers()354 void VulkanSurface::releaseBuffers() {
355     for (uint32_t i = 0; i < mWindowInfo.bufferCount; i++) {
356         VulkanSurface::NativeBufferInfo& bufferInfo = mNativeBuffers[i];
357 
358         if (bufferInfo.buffer.get() != nullptr && bufferInfo.dequeued) {
359             int err = mNativeWindow->cancelBuffer(mNativeWindow.get(), bufferInfo.buffer.get(),
360                                                   bufferInfo.dequeue_fence.release());
361             if (err != 0) {
362                 ALOGE("cancelBuffer[%u] failed during destroy: %s (%d)", i, strerror(-err), err);
363             }
364             bufferInfo.dequeued = false;
365             bufferInfo.dequeue_fence.reset();
366         }
367 
368         LOG_ALWAYS_FATAL_IF(bufferInfo.dequeued);
369         LOG_ALWAYS_FATAL_IF(bufferInfo.dequeue_fence.ok());
370 
371         bufferInfo.skSurface.reset();
372         bufferInfo.buffer.clear();
373         bufferInfo.hasValidContents = false;
374         bufferInfo.lastPresentedCount = 0;
375     }
376 }
377 
invalidateBuffers()378 void VulkanSurface::invalidateBuffers() {
379     for (uint32_t i = 0; i < mWindowInfo.bufferCount; i++) {
380         VulkanSurface::NativeBufferInfo& bufferInfo = mNativeBuffers[i];
381         bufferInfo.hasValidContents = false;
382         bufferInfo.lastPresentedCount = 0;
383     }
384 }
385 
dequeueNativeBuffer()386 VulkanSurface::NativeBufferInfo* VulkanSurface::dequeueNativeBuffer() {
387     // Set the mCurrentBufferInfo to invalid in case of error and only reset it to the correct
388     // value at the end of the function if everything dequeued correctly.
389     mCurrentBufferInfo = nullptr;
390 
391     // Query the transform hint synced from the initial Surface connect or last queueBuffer. The
392     // auto prerotation on the buffer is based on the same transform hint in use by the producer.
393     int transformHint = 0;
394     int err =
395             mNativeWindow->query(mNativeWindow.get(), NATIVE_WINDOW_TRANSFORM_HINT, &transformHint);
396 
397     // Since auto pre-rotation is enabled, dequeueBuffer to get the consumer driven buffer size
398     // from ANativeWindowBuffer.
399     ANativeWindowBuffer* buffer;
400     base::unique_fd fence_fd;
401     {
402         int rawFd = -1;
403         err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buffer, &rawFd);
404         fence_fd.reset(rawFd);
405     }
406     if (err != 0) {
407         ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
408         return nullptr;
409     }
410 
411     SkISize actualSize = SkISize::Make(buffer->width, buffer->height);
412     if (actualSize != mWindowInfo.actualSize || transformHint != mWindowInfo.transform) {
413         if (actualSize != mWindowInfo.actualSize) {
414             // reset the NativeBufferInfo (including SkSurface) associated with the old buffers. The
415             // new NativeBufferInfo storage will be populated lazily as we dequeue each new buffer.
416             mWindowInfo.actualSize = actualSize;
417             releaseBuffers();
418         } else {
419             // A change in transform means we need to repaint the entire buffer area as the damage
420             // rects have just moved about.
421             invalidateBuffers();
422         }
423 
424         if (transformHint != mWindowInfo.transform) {
425             err = native_window_set_buffers_transform(mNativeWindow.get(),
426                                                       InvertTransform(transformHint));
427             if (err != 0) {
428                 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)", transformHint,
429                       strerror(-err), err);
430                 mNativeWindow->cancelBuffer(mNativeWindow.get(), buffer, fence_fd.release());
431                 return nullptr;
432             }
433             mWindowInfo.transform = transformHint;
434         }
435 
436         mWindowInfo.size = actualSize;
437         if (mWindowInfo.transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
438             mWindowInfo.size.set(actualSize.height(), actualSize.width());
439         }
440 
441         mWindowInfo.preTransform = GetPreTransformMatrix(mWindowInfo.size, mWindowInfo.transform);
442         mWindowInfo.pixelSnapMatrix = GetPixelSnapMatrix(mWindowInfo.size, mWindowInfo.transform);
443     }
444 
445     uint32_t idx;
446     for (idx = 0; idx < mWindowInfo.bufferCount; idx++) {
447         if (mNativeBuffers[idx].buffer.get() == buffer) {
448             mNativeBuffers[idx].dequeued = true;
449             mNativeBuffers[idx].dequeue_fence = std::move(fence_fd);
450             break;
451         } else if (mNativeBuffers[idx].buffer.get() == nullptr) {
452             // increasing the number of buffers we have allocated
453             mNativeBuffers[idx].buffer = buffer;
454             mNativeBuffers[idx].dequeued = true;
455             mNativeBuffers[idx].dequeue_fence = std::move(fence_fd);
456             break;
457         }
458     }
459     if (idx == mWindowInfo.bufferCount) {
460         ALOGE("dequeueBuffer returned unrecognized buffer");
461         mNativeWindow->cancelBuffer(mNativeWindow.get(), buffer, fence_fd.release());
462         return nullptr;
463     }
464 
465     VulkanSurface::NativeBufferInfo* bufferInfo = &mNativeBuffers[idx];
466 
467     if (bufferInfo->skSurface.get() == nullptr) {
468         SkSurfaceProps surfaceProps;
469         if (mWindowInfo.colorMode != ColorMode::Default) {
470             surfaceProps = SkSurfaceProps(SkSurfaceProps::kAlwaysDither_Flag | surfaceProps.flags(),
471                                           surfaceProps.pixelGeometry());
472         }
473         bufferInfo->skSurface = SkSurface::MakeFromAHardwareBuffer(
474                 mGrContext, ANativeWindowBuffer_getHardwareBuffer(bufferInfo->buffer.get()),
475                 kTopLeft_GrSurfaceOrigin, mWindowInfo.colorspace, &surfaceProps,
476                 /*from_window=*/true);
477         if (bufferInfo->skSurface.get() == nullptr) {
478             ALOGE("SkSurface::MakeFromAHardwareBuffer failed");
479             mNativeWindow->cancelBuffer(mNativeWindow.get(), buffer,
480                                         mNativeBuffers[idx].dequeue_fence.release());
481             mNativeBuffers[idx].dequeued = false;
482             return nullptr;
483         }
484     }
485 
486     mCurrentBufferInfo = bufferInfo;
487     return bufferInfo;
488 }
489 
presentCurrentBuffer(const SkRect & dirtyRect,int semaphoreFd)490 bool VulkanSurface::presentCurrentBuffer(const SkRect& dirtyRect, int semaphoreFd) {
491     if (!dirtyRect.isEmpty()) {
492 
493         // native_window_set_surface_damage takes a rectangle in prerotated space
494         // with a bottom-left origin. That is, top > bottom.
495         // The dirtyRect is also in prerotated space, so we just need to switch it to
496         // a bottom-left origin space.
497 
498         SkIRect irect;
499         dirtyRect.roundOut(&irect);
500         android_native_rect_t aRect;
501         aRect.left = irect.left();
502         aRect.top = logicalHeight() - irect.top();
503         aRect.right = irect.right();
504         aRect.bottom = logicalHeight() - irect.bottom();
505 
506         int err = native_window_set_surface_damage(mNativeWindow.get(), &aRect, 1);
507         ALOGE_IF(err != 0, "native_window_set_surface_damage failed: %s (%d)", strerror(-err), err);
508     }
509 
510     LOG_ALWAYS_FATAL_IF(!mCurrentBufferInfo);
511     VulkanSurface::NativeBufferInfo& currentBuffer = *mCurrentBufferInfo;
512     // queueBuffer always closes fence, even on error
513     int queuedFd = (semaphoreFd != -1) ? semaphoreFd : currentBuffer.dequeue_fence.release();
514     int err = mNativeWindow->queueBuffer(mNativeWindow.get(), currentBuffer.buffer.get(), queuedFd);
515 
516     currentBuffer.dequeued = false;
517     if (err != 0) {
518         ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
519         // cancelBuffer takes ownership of the fence
520         mNativeWindow->cancelBuffer(mNativeWindow.get(), currentBuffer.buffer.get(),
521                                     currentBuffer.dequeue_fence.release());
522     } else {
523         currentBuffer.hasValidContents = true;
524         currentBuffer.lastPresentedCount = mPresentCount;
525         mPresentCount++;
526     }
527 
528     currentBuffer.dequeue_fence.reset();
529 
530     return err == 0;
531 }
532 
getCurrentBuffersAge()533 int VulkanSurface::getCurrentBuffersAge() {
534     LOG_ALWAYS_FATAL_IF(!mCurrentBufferInfo);
535     VulkanSurface::NativeBufferInfo& currentBuffer = *mCurrentBufferInfo;
536     return currentBuffer.hasValidContents ? (mPresentCount - currentBuffer.lastPresentedCount) : 0;
537 }
538 
setColorSpace(sk_sp<SkColorSpace> colorSpace)539 void VulkanSurface::setColorSpace(sk_sp<SkColorSpace> colorSpace) {
540     mWindowInfo.colorspace = std::move(colorSpace);
541     for (int i = 0; i < kNumBufferSlots; i++) {
542         mNativeBuffers[i].skSurface.reset();
543     }
544 
545     if (mWindowInfo.colorMode == ColorMode::Hdr || mWindowInfo.colorMode == ColorMode::Hdr10) {
546         mWindowInfo.dataspace =
547                 static_cast<android_dataspace>(STANDARD_DCI_P3 | TRANSFER_SRGB | RANGE_EXTENDED);
548     } else {
549         mWindowInfo.dataspace = ColorSpaceToADataSpace(
550                 mWindowInfo.colorspace.get(), BufferFormatToColorType(mWindowInfo.bufferFormat));
551     }
552     LOG_ALWAYS_FATAL_IF(mWindowInfo.dataspace == HAL_DATASPACE_UNKNOWN &&
553                                 mWindowInfo.bufferFormat != AHARDWAREBUFFER_FORMAT_R8_UNORM,
554                         "Unsupported colorspace");
555 
556     if (mNativeWindow) {
557         int err = ANativeWindow_setBuffersDataSpace(mNativeWindow.get(), mWindowInfo.dataspace);
558         if (err != 0) {
559             ALOGE("VulkanSurface::setColorSpace() native_window_set_buffers_data_space(%d) "
560                   "failed: %s (%d)",
561                   mWindowInfo.dataspace, strerror(-err), err);
562         }
563     }
564 }
565 
566 } /* namespace renderthread */
567 } /* namespace uirenderer */
568 } /* namespace android */
569