blob: dec3b20831cff573fd968f3d4669b8c59738b527 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 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
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Yiwei Zhang0f475222019-04-11 19:38:00 -070019#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070020#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070021#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040022#include <hardware/gralloc.h>
23#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070025#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070026#include <system/window.h>
27#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050028#include <ui/DebugUtils.h>
29#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080030#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080031#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080032#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070033
34#include <algorithm>
35#include <unordered_set>
36#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Chia-I Wu4a6a9162016-03-26 07:17:34 +080038#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Daniel Kochf25f5bb2017-10-05 00:26:58 -040040using android::hardware::graphics::common::V1_0::BufferUsage;
41
Chia-I Wu62262232016-03-26 07:06:44 +080042namespace vulkan {
43namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070044
Jesse Halld7b994a2015-09-07 14:17:37 -070045namespace {
46
John Reck97678d42022-08-23 11:24:51 -040047static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
48 uint64_t consumerUsage) {
49 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
50 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
51 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
52 "bits to match");
53 uint64_t merged = producerUsage | consumerUsage;
54 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
55 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
56 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
57 merged |= BufferUsage::CPU_READ_OFTEN;
58 }
59 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
60 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
61 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
62 merged |= BufferUsage::CPU_WRITE_OFTEN;
63 }
64 return merged;
65}
66
Jesse Hall55bc0972016-02-23 16:43:29 -080067const VkSurfaceTransformFlagsKHR kSupportedTransforms =
68 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
69 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
70 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
71 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
73 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080076 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
77
78VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
79 // Native and Vulkan transforms are isomorphic, but are represented
80 // differently. Vulkan transforms are built up of an optional horizontal
81 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
82 // transforms are built up from a horizontal flip, vertical flip, and
83 // 90-degree rotation, all optional but always in that order.
84
Jesse Hall55bc0972016-02-23 16:43:29 -080085 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070086 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080087 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070088 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
89 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
90 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
91 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
92 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080093 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070094 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080095 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070096 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
97 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
98 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
99 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
100 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800101 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
103 default:
104 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
105 }
106}
107
Yiwei Zhang70a21962019-05-31 17:26:52 -0700108int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
109 switch (transform) {
110 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
111 return NATIVE_WINDOW_TRANSFORM_ROT_90;
112 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
113 return NATIVE_WINDOW_TRANSFORM_ROT_180;
114 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_270;
116 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
118 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
120 NATIVE_WINDOW_TRANSFORM_ROT_90;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
123 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
124 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
125 NATIVE_WINDOW_TRANSFORM_ROT_90;
126 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
127 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
128 default:
129 return 0;
130 }
131}
132
Jesse Hall178b6962016-02-24 15:39:50 -0800133int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
134 switch (transform) {
135 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
136 return NATIVE_WINDOW_TRANSFORM_ROT_270;
137 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
138 return NATIVE_WINDOW_TRANSFORM_ROT_180;
139 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700141 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
143 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
145 NATIVE_WINDOW_TRANSFORM_ROT_90;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
148 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
149 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
150 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800151 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
152 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
153 default:
154 return 0;
155 }
156}
157
Ian Elliott8a977262017-01-19 09:05:58 -0700158class TimingInfo {
159 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800160 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700161 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800162 native_frame_id_(nativeFrameId) {}
163 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700164 return (timestamp_desired_present_time_ !=
165 NATIVE_WINDOW_TIMESTAMP_PENDING &&
166 timestamp_actual_present_time_ !=
167 NATIVE_WINDOW_TIMESTAMP_PENDING &&
168 timestamp_render_complete_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_composition_latch_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700172 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700173 void calculate(int64_t rdur) {
174 bool anyTimestampInvalid =
175 (timestamp_actual_present_time_ ==
176 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
177 (timestamp_render_complete_time_ ==
178 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
179 (timestamp_composition_latch_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID);
181 if (anyTimestampInvalid) {
182 ALOGE("Unexpectedly received invalid timestamp.");
183 vals_.actualPresentTime = 0;
184 vals_.earliestPresentTime = 0;
185 vals_.presentMargin = 0;
186 return;
187 }
188
189 vals_.actualPresentTime =
190 static_cast<uint64_t>(timestamp_actual_present_time_);
191 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700192 timestamp_render_complete_time_);
193 // Calculate vals_.earliestPresentTime, and potentially adjust
194 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
195 // is vals_.actualPresentTime. If we can subtract rdur (the duration
196 // of a refresh cycle) from vals_.earliestPresentTime (and also from
197 // vals_.presentMargin) and still leave a positive margin, then we can
198 // report to the application that it could have presented earlier than
199 // it did (per the extension specification). If for some reason, we
200 // can do this subtraction repeatedly, we do, since
201 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700202 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700203 while ((margin > rdur) &&
204 ((early_time - rdur) > timestamp_composition_latch_time_)) {
205 early_time -= rdur;
206 margin -= rdur;
207 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700208 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
209 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700210 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800211 void get_values(VkPastPresentationTimingGOOGLE* values) const {
212 *values = vals_;
213 }
Ian Elliott8a977262017-01-19 09:05:58 -0700214
215 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800216 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700217
Brian Anderson1049d1d2016-12-16 17:25:57 -0800218 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700219 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
220 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
221 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
222 int64_t timestamp_composition_latch_time_
223 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700224};
225
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800227 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700228 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700229 uint64_t consumer_usage;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230};
231
232VkSurfaceKHR HandleFromSurface(Surface* surface) {
233 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
234}
235
236Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800237 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800238}
239
Ian Elliott8a977262017-01-19 09:05:58 -0700240// Maximum number of TimingInfo structs to keep per swapchain:
241enum { MAX_TIMING_INFOS = 10 };
242// Minimum number of frames to look for in the past (so we don't cause
243// syncronous requests to Surface Flinger):
244enum { MIN_NUM_FRAMES_AGO = 5 };
245
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300246bool IsSharedPresentMode(VkPresentModeKHR mode) {
247 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
248 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
249}
250
Jesse Hall1356b0d2015-11-23 17:24:58 -0800251struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700252 Swapchain(Surface& surface_,
253 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700254 VkPresentModeKHR present_mode,
255 int pre_transform_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700256 : surface(surface_),
257 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700258 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700259 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300260 frame_timestamps_enabled(false),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800261 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300262 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700263 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700264 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700265 window,
Brian Andersondc96fdf2017-03-20 16:54:25 -0700266 &refresh_duration);
Ian Elliott8a977262017-01-19 09:05:58 -0700267 }
Ian Elliott3568bfe2019-05-03 15:54:46 -0600268 uint64_t get_refresh_duration()
269 {
270 ANativeWindow* window = surface.window.get();
271 native_window_get_refresh_cycle_duration(
272 window,
273 &refresh_duration);
274 return static_cast<uint64_t>(refresh_duration);
275
276 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800277
278 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700279 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700280 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700281 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700282 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700283 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800284 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300285 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700286
287 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700288 Image()
289 : image(VK_NULL_HANDLE),
290 dequeue_fence(-1),
291 release_fence(-1),
292 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700293 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000294 // If the image is bound to memory, an sp to the underlying gralloc buffer.
295 // Otherwise, nullptr; the image will be bound to memory as part of
296 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800297 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700298 // The fence is only valid when the buffer is dequeued, and should be
299 // -1 any other time. When valid, we own the fd, and must ensure it is
300 // closed: either by closing it explicitly when queueing the buffer,
301 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
302 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700303 // This fence is a dup of the sync fd returned from the driver via
304 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
305 // ensure it is closed upon re-presenting or releasing the image.
306 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700307 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800308 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700309
Yiwei Zhang5e862202019-06-21 14:59:16 -0700310 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700311};
312
313VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
314 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
315}
316
317Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800318 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700319}
320
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700321static bool IsFencePending(int fd) {
322 if (fd < 0)
323 return false;
324
325 errno = 0;
326 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
327}
328
Jesse Halldc225072016-05-30 22:40:14 -0700329void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000330 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700331 ANativeWindow* window,
332 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700333 Swapchain::Image& image,
334 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700335 ATRACE_CALL();
336
Jesse Halldc225072016-05-30 22:40:14 -0700337 ALOG_ASSERT(release_fence == -1 || image.dequeued,
338 "ReleaseSwapchainImage: can't provide a release fence for "
339 "non-dequeued images");
340
341 if (image.dequeued) {
342 if (release_fence >= 0) {
343 // We get here from vkQueuePresentKHR. The application is
344 // responsible for creating an execution dependency chain from
345 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
346 // (release_fence), so we can drop the dequeue_fence here.
347 if (image.dequeue_fence >= 0)
348 close(image.dequeue_fence);
349 } else {
350 // We get here during swapchain destruction, or various serious
351 // error cases e.g. when we can't create the release_fence during
352 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
353 // have already signalled, since the swapchain images are supposed
354 // to be idle before the swapchain is destroyed. In error cases,
355 // there may be rendering in flight to the image, but since we
356 // weren't able to create a release_fence, waiting for the
357 // dequeue_fence is about the best we can do.
358 release_fence = image.dequeue_fence;
359 }
360 image.dequeue_fence = -1;
361
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000362 // It's invalid to call cancelBuffer on a shared buffer
363 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700364 window->cancelBuffer(window, image.buffer.get(), release_fence);
365 } else {
366 if (release_fence >= 0) {
367 sync_wait(release_fence, -1 /* forever */);
368 close(release_fence);
369 }
370 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700371 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700372 image.dequeued = false;
373 }
374
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700375 if (defer_if_pending && IsFencePending(image.release_fence))
376 return;
377
378 if (image.release_fence >= 0) {
379 close(image.release_fence);
380 image.release_fence = -1;
381 }
382
Jesse Halldc225072016-05-30 22:40:14 -0700383 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700384 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700385 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700386 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700387 image.image = VK_NULL_HANDLE;
388 }
389
390 image.buffer.clear();
391}
392
393void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
394 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
395 return;
Jesse Halldc225072016-05-30 22:40:14 -0700396 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000397 if (!swapchain->images[i].dequeued) {
398 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
399 swapchain->images[i], true);
400 }
Jesse Halldc225072016-05-30 22:40:14 -0700401 }
402 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700403 swapchain->timing.clear();
404}
405
406uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800407 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
408 return 0;
409 }
Ian Elliott8a977262017-01-19 09:05:58 -0700410
Brian Anderson1049d1d2016-12-16 17:25:57 -0800411 uint32_t num_ready = 0;
412 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
413 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700414 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800415 if (ti.ready()) {
416 // This TimingInfo is ready to be reported to the user. Add it
417 // to the num_ready.
418 num_ready++;
419 continue;
420 }
421 // This TimingInfo is not yet ready to be reported to the user,
422 // and so we should look for any available timestamps that
423 // might make it ready.
424 int64_t desired_present_time = 0;
425 int64_t render_complete_time = 0;
426 int64_t composition_latch_time = 0;
427 int64_t actual_present_time = 0;
428 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800429 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800430 swapchain.surface.window.get(), ti.native_frame_id_,
431 &desired_present_time, &render_complete_time,
432 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700433 nullptr, //&first_composition_start_time,
434 nullptr, //&last_composition_start_time,
435 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800436 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700437 nullptr, //&dequeue_ready_time,
438 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800439
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800440 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800441 continue;
442 }
443
444 // Record the timestamp(s) we received, and then see if this TimingInfo
445 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700446 ti.timestamp_desired_present_time_ = desired_present_time;
447 ti.timestamp_actual_present_time_ = actual_present_time;
448 ti.timestamp_render_complete_time_ = render_complete_time;
449 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800450
451 if (ti.ready()) {
452 // The TimingInfo has received enough timestamps, and should now
453 // use those timestamps to calculate the info that should be
454 // reported to the user:
455 ti.calculate(swapchain.refresh_duration);
456 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700457 }
458 }
459 return num_ready;
460}
461
Ian Elliott8a977262017-01-19 09:05:58 -0700462void copy_ready_timings(Swapchain& swapchain,
463 uint32_t* count,
464 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800465 if (swapchain.timing.empty()) {
466 *count = 0;
467 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700468 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800469
470 size_t last_ready = swapchain.timing.size() - 1;
471 while (!swapchain.timing[last_ready].ready()) {
472 if (last_ready == 0) {
473 *count = 0;
474 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700475 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800476 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700477 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800478
479 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700480 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800481 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
482 const TimingInfo& ti = swapchain.timing[i];
483 if (ti.ready()) {
484 ti.get_values(&timings[num_copied]);
485 num_copied++;
486 }
487 num_to_remove++;
488 }
489
490 // Discard old frames that aren't ready if newer frames are ready.
491 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700492 swapchain.timing.erase(swapchain.timing.begin(),
493 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800494
Ian Elliott8a977262017-01-19 09:05:58 -0700495 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700496}
497
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500498android::PixelFormat GetNativePixelFormat(VkFormat format) {
499 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700500 switch (format) {
501 case VK_FORMAT_R8G8B8A8_UNORM:
502 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500503 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700504 break;
505 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500506 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700507 break;
508 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500509 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700510 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800511 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500512 native_format = android::PIXEL_FORMAT_RGBA_1010102;
513 break;
514 case VK_FORMAT_R8_UNORM:
515 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700516 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000517 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
518 native_format = android::PIXEL_FORMAT_RGBA_10101010;
519 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700520 default:
521 ALOGV("unsupported swapchain format %d", format);
522 break;
523 }
524 return native_format;
525}
526
527android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
528 switch (colorspace) {
529 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
530 return HAL_DATASPACE_V0_SRGB;
531 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
532 return HAL_DATASPACE_DISPLAY_P3;
533 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
534 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600535 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
536 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700537 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
538 return HAL_DATASPACE_DCI_P3_LINEAR;
539 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
540 return HAL_DATASPACE_DCI_P3;
541 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
542 return HAL_DATASPACE_V0_SRGB_LINEAR;
543 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
544 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600545 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
546 return HAL_DATASPACE_BT2020_LINEAR;
547 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700548 return static_cast<android_dataspace>(
549 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
550 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600551 case VK_COLOR_SPACE_DOLBYVISION_EXT:
552 return static_cast<android_dataspace>(
553 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
554 HAL_DATASPACE_RANGE_FULL);
555 case VK_COLOR_SPACE_HDR10_HLG_EXT:
556 return static_cast<android_dataspace>(
557 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
558 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700559 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
560 return static_cast<android_dataspace>(
561 HAL_DATASPACE_STANDARD_ADOBE_RGB |
562 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
563 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
564 return HAL_DATASPACE_ADOBE_RGB;
565
566 // Pass through is intended to allow app to provide data that is passed
567 // to the display system without modification.
568 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
569 return HAL_DATASPACE_ARBITRARY;
570
571 default:
572 // This indicates that we don't know about the
573 // dataspace specified and we should indicate that
574 // it's unsupported
575 return HAL_DATASPACE_UNKNOWN;
576 }
577}
578
Jesse Halld7b994a2015-09-07 14:17:37 -0700579} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700580
Jesse Halle1b12782015-11-30 11:27:32 -0800581VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800582VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800583 VkInstance instance,
584 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
585 const VkAllocationCallbacks* allocator,
586 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800587 ATRACE_CALL();
588
Jesse Hall1f91d392015-12-11 16:28:44 -0800589 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800590 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800591 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
592 alignof(Surface),
593 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800594 if (!mem)
595 return VK_ERROR_OUT_OF_HOST_MEMORY;
596 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700597
Chia-I Wue8e689f2016-04-18 08:21:31 +0800598 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700599 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700600 int err = native_window_get_consumer_usage(surface->window.get(),
601 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800602 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700603 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
604 strerror(-err), err);
605 surface->~Surface();
606 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700607 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700608 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700609
Yiwei Zhang6435b322018-05-08 11:12:17 -0700610 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800611 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800612 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800613 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
614 err);
615 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800616 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700617 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800618 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700619
Jesse Hall1356b0d2015-11-23 17:24:58 -0800620 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700621 return VK_SUCCESS;
622}
623
Jesse Halle1b12782015-11-30 11:27:32 -0800624VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800625void DestroySurfaceKHR(VkInstance instance,
626 VkSurfaceKHR surface_handle,
627 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800628 ATRACE_CALL();
629
Jesse Hall1356b0d2015-11-23 17:24:58 -0800630 Surface* surface = SurfaceFromHandle(surface_handle);
631 if (!surface)
632 return;
633 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700634 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700635 "destroyed VkSurfaceKHR 0x%" PRIx64
636 " has active VkSwapchainKHR 0x%" PRIx64,
637 reinterpret_cast<uint64_t>(surface_handle),
638 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800639 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800640 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800641 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800642 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800643}
644
Jesse Halle1b12782015-11-30 11:27:32 -0800645VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800646VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
647 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000648 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800649 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000650 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800651 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800652}
653
Jesse Halle1b12782015-11-30 11:27:32 -0800654VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800655VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600656 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800657 VkSurfaceKHR surface,
658 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800659 ATRACE_CALL();
660
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000661 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
662
663 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
664 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
665 nullptr,
666 surface
667 };
668
669 VkSurfaceCapabilities2KHR caps2 = {
670 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
671 nullptr,
672 {},
673 };
674
675 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
676 *capabilities = caps2.surfaceCapabilities;
677 return result;
678}
679
680// Does the call-twice and VK_INCOMPLETE handling for querying lists
681// of things, where we already have the full set built in a vector.
682template <typename T>
683VkResult CopyWithIncomplete(std::vector<T> const& things,
684 T* callerPtr, uint32_t* callerCount) {
685 VkResult result = VK_SUCCESS;
686 if (callerPtr) {
687 if (things.size() > *callerCount)
688 result = VK_INCOMPLETE;
689 *callerCount = std::min(uint32_t(things.size()), *callerCount);
690 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600691 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000692 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800693 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000694 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700695}
696
Jesse Halle1b12782015-11-30 11:27:32 -0800697VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700698VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
699 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800700 uint32_t* count,
701 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800702 ATRACE_CALL();
703
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700704 const InstanceData& instance_data = GetData(pdev);
705
Ian Elliott1ce053f2022-03-16 09:49:53 -0600706 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000707 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600708 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600709 if (surface_handle == VK_NULL_HANDLE) {
710 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
711 bool surfaceless_enabled =
712 instance_data.hook_extensions.test(surfaceless);
713 if (!surfaceless_enabled) {
714 return VK_ERROR_SURFACE_LOST_KHR;
715 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300716 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600717
718 // TODO(b/203826952): research proper value; temporarily use the
719 // values seen on Pixel
720 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
721 } else {
722 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600723 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700724 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700725
Charlie Lao324191f2019-12-13 11:03:16 -0800726 AHardwareBuffer_Desc desc = {};
727 desc.width = 1;
728 desc.height = 1;
729 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600730 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800731 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
732
733 // We must support R8G8B8A8
734 std::vector<VkSurfaceFormatKHR> all_formats = {
735 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000736 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000737 };
Charlie Lao324191f2019-12-13 11:03:16 -0800738
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000739 if (colorspace_ext) {
740 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800741 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
742 all_formats.emplace_back(VkSurfaceFormatKHR{
743 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
744 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000745 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800746 all_formats.emplace_back(VkSurfaceFormatKHR{
747 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
748 all_formats.emplace_back(VkSurfaceFormatKHR{
749 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
750 }
751
Ian Elliott1ce053f2022-03-16 09:49:53 -0600752 // NOTE: Any new formats that are added must be coordinated across different
753 // Android users. This includes the ANGLE team (a layered implementation of
754 // OpenGL-ES).
755
Charlie Lao324191f2019-12-13 11:03:16 -0800756 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
757 if (AHardwareBuffer_isSupported(&desc)) {
758 all_formats.emplace_back(VkSurfaceFormatKHR{
759 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800760 if (colorspace_ext) {
761 all_formats.emplace_back(
762 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
763 VK_COLOR_SPACE_PASS_THROUGH_EXT});
764 }
Charlie Lao324191f2019-12-13 11:03:16 -0800765 }
766
767 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
768 if (AHardwareBuffer_isSupported(&desc)) {
769 all_formats.emplace_back(VkSurfaceFormatKHR{
770 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800771 if (colorspace_ext) {
772 all_formats.emplace_back(
773 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
774 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800775 all_formats.emplace_back(
776 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
777 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
778 all_formats.emplace_back(
779 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
780 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
781 }
782 }
783
784 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
785 if (AHardwareBuffer_isSupported(&desc)) {
786 all_formats.emplace_back(
787 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
788 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800789 if (colorspace_ext) {
790 all_formats.emplace_back(
791 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
792 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800793 all_formats.emplace_back(
794 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
795 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
796 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700797 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700798
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500799 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
800 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800801 if (colorspace_ext) {
802 all_formats.emplace_back(VkSurfaceFormatKHR{
803 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
804 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500805 }
806
Trevor David Black67e9b102023-03-07 05:28:15 +0000807 bool rgba10x6_formats_ext = false;
808 uint32_t exts_count;
809 const auto& driver = GetData(pdev).driver;
810 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
811 nullptr);
812 std::vector<VkExtensionProperties> props(exts_count);
813 driver.EnumerateDeviceExtensionProperties(pdev, nullptr, &exts_count,
814 props.data());
815 for (uint32_t i = 0; i < exts_count; i++) {
816 VkExtensionProperties prop = props[i];
817 if (strcmp(prop.extensionName,
818 VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME) == 0) {
819 rgba10x6_formats_ext = true;
820 }
821 }
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000822 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
Trevor David Black67e9b102023-03-07 05:28:15 +0000823 if (AHardwareBuffer_isSupported(&desc) && rgba10x6_formats_ext) {
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000824 all_formats.emplace_back(
825 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
826 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
827 if (colorspace_ext) {
828 all_formats.emplace_back(
829 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
830 VK_COLOR_SPACE_PASS_THROUGH_EXT});
831 all_formats.emplace_back(
832 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
833 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
834 }
835 }
836
Ian Elliott6ba85d92022-02-18 16:44:58 -0700837 // NOTE: Any new formats that are added must be coordinated across different
838 // Android users. This includes the ANGLE team (a layered implementation of
839 // OpenGL-ES).
840
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000841 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700842}
843
Jesse Halle1b12782015-11-30 11:27:32 -0800844VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300845VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
846 VkPhysicalDevice physicalDevice,
847 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
848 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800849 ATRACE_CALL();
850
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000851 auto surface = pSurfaceInfo->surface;
852 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300853
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000854 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
855 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
856 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
857 switch (pNext->sType) {
858 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
859 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
860 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300861
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000862 default:
863 break;
864 }
865 }
866
867 int err;
868 int width, height;
869 int transform_hint;
870 int max_buffer_count;
871 if (surface == VK_NULL_HANDLE) {
872 const InstanceData& instance_data = GetData(physicalDevice);
873 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
874 bool surfaceless_enabled =
875 instance_data.hook_extensions.test(surfaceless);
876 if (!surfaceless_enabled) {
877 // It is an error to pass a surface==VK_NULL_HANDLE unless the
878 // VK_GOOGLE_surfaceless_query extension is enabled
879 return VK_ERROR_SURFACE_LOST_KHR;
880 }
881 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
882 // extension for this function is for
883 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
884 // four values cannot be known without a surface. Default values will
885 // be supplied anyway, but cannot be relied upon.
886 width = 0xFFFFFFFF;
887 height = 0xFFFFFFFF;
888 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
889 capabilities->minImageCount = 0xFFFFFFFF;
890 capabilities->maxImageCount = 0xFFFFFFFF;
891 } else {
892 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
893
894 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
895 if (err != android::OK) {
896 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
897 strerror(-err), err);
898 return VK_ERROR_SURFACE_LOST_KHR;
899 }
900 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
901 if (err != android::OK) {
902 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
903 strerror(-err), err);
904 return VK_ERROR_SURFACE_LOST_KHR;
905 }
906
907 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
908 &transform_hint);
909 if (err != android::OK) {
910 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
911 strerror(-err), err);
912 return VK_ERROR_SURFACE_LOST_KHR;
913 }
914
915 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
916 &max_buffer_count);
917 if (err != android::OK) {
918 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
919 strerror(-err), err);
920 return VK_ERROR_SURFACE_LOST_KHR;
921 }
922
923 if (pPresentMode && IsSharedPresentMode(pPresentMode->presentMode)) {
924 capabilities->minImageCount = 1;
925 capabilities->maxImageCount = 1;
926 } else if (pPresentMode && pPresentMode->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
927 // TODO: use undequeued buffer requirement for more precise bound
928 capabilities->minImageCount = std::min(max_buffer_count, 4);
929 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
930 } else {
931 // TODO: if we're able to, provide better bounds on the number of buffers
932 // for other modes as well.
933 capabilities->minImageCount = std::min(max_buffer_count, 3);
934 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
935 }
936 }
937
938 capabilities->currentExtent =
939 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
940
941 // TODO(http://b/134182502): Figure out what the max extent should be.
942 capabilities->minImageExtent = VkExtent2D{1, 1};
943 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
944
945 if (capabilities->maxImageExtent.height <
946 capabilities->currentExtent.height) {
947 capabilities->maxImageExtent.height =
948 capabilities->currentExtent.height;
949 }
950
951 if (capabilities->maxImageExtent.width <
952 capabilities->currentExtent.width) {
953 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
954 }
955
956 capabilities->maxImageArrayLayers = 1;
957
958 capabilities->supportedTransforms = kSupportedTransforms;
959 capabilities->currentTransform =
960 TranslateNativeToVulkanTransform(transform_hint);
961
962 // On Android, window composition is a WindowManager property, not something
963 // associated with the bufferqueue. It can't be changed from here.
964 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
965
966 capabilities->supportedUsageFlags =
967 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
968 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
969 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
970 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
971
972 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
973 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
974
975 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300976 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
977 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000978 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300979 // Claim same set of usage flags are supported for
980 // shared present modes as for other modes.
981 shared_caps->sharedPresentSupportedUsageFlags =
982 pSurfaceCapabilities->surfaceCapabilities
983 .supportedUsageFlags;
984 } break;
985
Ian Elliottbb67b242022-03-16 09:52:28 -0600986 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
987 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000988 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -0600989 protected_caps->supportsProtected = VK_TRUE;
990 } break;
991
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000992 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
993 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
994 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
995 // By default, Android stretches the buffer to fit the window,
996 // without preserving aspect ratio. Other modes are technically possible
997 // but consult with CoGS team before exposing them here!
998 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
999
1000 // Since we always scale, we don't support any gravity.
1001 scaling_caps->supportedPresentGravityX = 0;
1002 scaling_caps->supportedPresentGravityY = 0;
1003
1004 // Scaled image limits are just the basic image limits
1005 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
1006 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
1007 } break;
1008
1009 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
1010 VkSurfacePresentModeCompatibilityEXT* mode_caps =
1011 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
1012
1013 ALOG_ASSERT(pPresentMode,
1014 "querying VkSurfacePresentModeCompatibilityEXT "
1015 "requires VkSurfacePresentModeEXT to be provided");
1016 std::vector<VkPresentModeKHR> compatibleModes;
1017 compatibleModes.push_back(pPresentMode->presentMode);
1018
1019 switch (pPresentMode->presentMode) {
1020 // Shared modes are both compatible with each other.
1021 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1022 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1023 break;
1024 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1025 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1026 break;
1027 default:
1028 // Other modes are only compatible with themselves.
1029 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1030 break;
1031 }
1032
1033 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1034 // a larger query and there would be no way to determine exactly where it came from.
1035 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1036 &mode_caps->presentModeCount);
1037 } break;
1038
Chris Forbes06bc0092017-03-16 16:46:05 +13001039 default:
1040 // Ignore all other extension structs
1041 break;
1042 }
1043 }
1044
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001045 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001046}
1047
1048VKAPI_ATTR
1049VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1050 VkPhysicalDevice physicalDevice,
1051 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1052 uint32_t* pSurfaceFormatCount,
1053 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001054 ATRACE_CALL();
1055
Chris Forbes2452cf72017-03-16 16:30:17 +13001056 if (!pSurfaceFormats) {
1057 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1058 pSurfaceInfo->surface,
1059 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001060 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001061
Trevor David Black929e9cd2022-11-22 04:12:19 +00001062 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1063 // after the call.
1064 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1065 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1066 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1067 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001068
Trevor David Black929e9cd2022-11-22 04:12:19 +00001069 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1070 return result;
1071 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001072
Trevor David Black929e9cd2022-11-22 04:12:19 +00001073 const auto& driver = GetData(physicalDevice).driver;
1074
1075 // marshal results individually due to stride difference.
1076 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1077 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1078 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1079
1080 // Query the compression properties for the surface format
1081 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1082 while (pSurfaceFormat->pNext) {
1083 pSurfaceFormat =
1084 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1085 switch (pSurfaceFormat->sType) {
1086 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001087 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1088 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001089 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001090
1091 if (surfaceCompressionProps &&
1092 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1093 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1094 imageFormatInfo.sType =
1095 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1096 imageFormatInfo.format =
1097 pSurfaceFormats[i].surfaceFormat.format;
1098 imageFormatInfo.pNext = nullptr;
1099
1100 VkImageCompressionControlEXT compressionControl = {};
1101 compressionControl.sType =
1102 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1103 compressionControl.pNext = imageFormatInfo.pNext;
1104
1105 imageFormatInfo.pNext = &compressionControl;
1106
1107 VkImageCompressionPropertiesEXT compressionProps = {};
1108 compressionProps.sType =
1109 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1110 compressionProps.pNext = nullptr;
1111
1112 VkImageFormatProperties2KHR imageFormatProps = {};
1113 imageFormatProps.sType =
1114 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1115 imageFormatProps.pNext = &compressionProps;
1116
1117 VkResult compressionRes =
1118 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1119 physicalDevice, &imageFormatInfo,
1120 &imageFormatProps);
1121 if (compressionRes == VK_SUCCESS) {
1122 surfaceCompressionProps->imageCompressionFlags =
1123 compressionProps.imageCompressionFlags;
1124 surfaceCompressionProps
1125 ->imageCompressionFixedRateFlags =
1126 compressionProps.imageCompressionFixedRateFlags;
1127 } else {
1128 return compressionRes;
1129 }
1130 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001131 } break;
1132
1133 default:
1134 // Ignore all other extension structs
1135 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001136 }
1137 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001138 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001139
1140 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001141}
1142
1143VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001144VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001145 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001146 uint32_t* count,
1147 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001148 ATRACE_CALL();
1149
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001150 int err;
1151 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001152 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001153 if (surface == VK_NULL_HANDLE) {
1154 const InstanceData& instance_data = GetData(pdev);
1155 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1156 bool surfaceless_enabled =
1157 instance_data.hook_extensions.test(surfaceless);
1158 if (!surfaceless_enabled) {
1159 return VK_ERROR_SURFACE_LOST_KHR;
1160 }
1161 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1162 // extension for this function is for
1163 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1164 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1165 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001166 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001167 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1168 } else {
1169 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1170
1171 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1172 &query_value);
1173 if (err != android::OK || query_value < 0) {
1174 ALOGE(
1175 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1176 "value=%d",
1177 strerror(-err), err, query_value);
1178 return VK_ERROR_SURFACE_LOST_KHR;
1179 }
1180 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1181
1182 err =
1183 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1184 if (err != android::OK || query_value < 0) {
1185 ALOGE(
1186 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1187 strerror(-err), err, query_value);
1188 return VK_ERROR_SURFACE_LOST_KHR;
1189 }
1190 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1191
1192 if (min_undequeued_buffers + 1 < max_buffer_count)
1193 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1194 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1195 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001196
1197 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001198 QueryPresentationProperties(pdev, &present_properties);
1199 if (present_properties.sharedImage) {
1200 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1201 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001202 }
1203
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001204 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001205}
1206
Jesse Halle1b12782015-11-30 11:27:32 -08001207VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001208VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001209 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001210 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001211 ATRACE_CALL();
1212
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001213 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1214 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1215 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1216 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1217 pDeviceGroupPresentCapabilities->sType);
1218
1219 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1220 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1221
1222 // assume device group of size 1
1223 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1224 pDeviceGroupPresentCapabilities->modes =
1225 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1226
1227 return VK_SUCCESS;
1228}
1229
1230VKAPI_ATTR
1231VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001232 VkDevice,
1233 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001234 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001235 ATRACE_CALL();
1236
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001237 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1238 return VK_SUCCESS;
1239}
1240
1241VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001242VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001243 VkSurfaceKHR surface,
1244 uint32_t* pRectCount,
1245 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001246 ATRACE_CALL();
1247
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001248 if (!pRects) {
1249 *pRectCount = 1;
1250 } else {
1251 uint32_t count = std::min(*pRectCount, 1u);
1252 bool incomplete = *pRectCount < 1;
1253
1254 *pRectCount = count;
1255
1256 if (incomplete) {
1257 return VK_INCOMPLETE;
1258 }
1259
1260 int err;
1261 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1262
1263 int width = 0, height = 0;
1264 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001265 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001266 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1267 strerror(-err), err);
1268 }
1269 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001270 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001271 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1272 strerror(-err), err);
1273 }
1274
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001275 pRects[0].offset.x = 0;
1276 pRects[0].offset.y = 0;
1277 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1278 static_cast<uint32_t>(height)};
1279 }
1280 return VK_SUCCESS;
1281}
1282
Yiwei Zhang533cea92019-06-03 18:43:24 -07001283static void DestroySwapchainInternal(VkDevice device,
1284 VkSwapchainKHR swapchain_handle,
1285 const VkAllocationCallbacks* allocator) {
1286 ATRACE_CALL();
1287
1288 const auto& dispatch = GetData(device).driver;
1289 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1290 if (!swapchain) {
1291 return;
1292 }
1293
1294 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1295 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1296
1297 if (window && swapchain->frame_timestamps_enabled) {
1298 native_window_enable_frame_timestamps(window, false);
1299 }
1300
1301 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001302 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1303 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001304 }
1305
1306 if (active) {
1307 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1308 }
1309
1310 if (!allocator) {
1311 allocator = &GetData(device).allocator;
1312 }
1313
1314 swapchain->~Swapchain();
1315 allocator->pfnFree(allocator->pUserData, swapchain);
1316}
1317
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001318VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001319VkResult CreateSwapchainKHR(VkDevice device,
1320 const VkSwapchainCreateInfoKHR* create_info,
1321 const VkAllocationCallbacks* allocator,
1322 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001323 ATRACE_CALL();
1324
Jesse Halld7b994a2015-09-07 14:17:37 -07001325 int err;
1326 VkResult result = VK_SUCCESS;
1327
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001328 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1329 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1330 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1331 " oldSwapchain=0x%" PRIx64,
1332 reinterpret_cast<uint64_t>(create_info->surface),
1333 create_info->minImageCount, create_info->imageFormat,
1334 create_info->imageColorSpace, create_info->imageExtent.width,
1335 create_info->imageExtent.height, create_info->imageUsage,
1336 create_info->preTransform, create_info->presentMode,
1337 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1338
Jesse Hall1f91d392015-12-11 16:28:44 -08001339 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001340 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001341
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001342 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001343 GetNativePixelFormat(create_info->imageFormat);
1344 android_dataspace native_dataspace =
1345 GetNativeDataspace(create_info->imageColorSpace);
1346 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1347 ALOGE(
1348 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1349 "failed: Unsupported color space",
1350 create_info->imageColorSpace);
1351 return VK_ERROR_INITIALIZATION_FAILED;
1352 }
1353
Jesse Hall42a9eec2016-06-03 12:39:49 -07001354 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001355 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001356 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001357 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001358 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001359 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001360 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001361 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001362 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1363 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001364 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001365 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001366
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001367 Surface& surface = *SurfaceFromHandle(create_info->surface);
1368
Jesse Halldc225072016-05-30 22:40:14 -07001369 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001370 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001371 " because it already has active swapchain 0x%" PRIx64
1372 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1373 reinterpret_cast<uint64_t>(create_info->surface),
1374 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1375 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1376 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1377 }
1378 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1379 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1380
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001381 // -- Reset the native window --
1382 // The native window might have been used previously, and had its properties
1383 // changed from defaults. That will affect the answer we get for queries
1384 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1385 // attempt such queries.
1386
Jesse Halldc225072016-05-30 22:40:14 -07001387 // The native window only allows dequeueing all buffers before any have
1388 // been queued, since after that point at least one is assumed to be in
1389 // non-FREE state at any given time. Disconnecting and re-connecting
1390 // orphans the previous buffers, getting us back to the state where we can
1391 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001392 //
1393 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001394 ANativeWindow* window = surface.window.get();
1395 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1396 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001397 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001398 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1399 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001400 strerror(-err), err);
1401
Nicolas Capens147b7da2021-04-09 14:53:06 -04001402 err =
1403 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001404 if (err != android::OK) {
1405 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1406 strerror(-err), err);
1407 return VK_ERROR_SURFACE_LOST_KHR;
1408 }
1409
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301410 int swap_interval =
1411 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001412 err = window->setSwapInterval(window, swap_interval);
1413 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001414 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1415 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001416 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001417 }
1418
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001419 err = native_window_set_shared_buffer_mode(window, false);
1420 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001421 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1422 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001423 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001424 }
1425
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001426 err = native_window_set_auto_refresh(window, false);
1427 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001428 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1429 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001430 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001431 }
1432
Jesse Halld7b994a2015-09-07 14:17:37 -07001433 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001434
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001435 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001436
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001437 err = native_window_set_buffers_format(window, native_pixel_format);
1438 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001439 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1440 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001441 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001442 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001443
1444 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1445 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1446 err = native_window_set_buffers_data_space(window, native_dataspace);
1447 if (err != android::OK) {
1448 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1449 native_dataspace, strerror(-err), err);
1450 return VK_ERROR_SURFACE_LOST_KHR;
1451 }
Jesse Hall517274a2016-02-10 00:07:18 -08001452 }
1453
Jesse Hall3dd678a2016-01-08 21:52:01 -08001454 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001455 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001456 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001457 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001458 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1459 create_info->imageExtent.width, create_info->imageExtent.height,
1460 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001461 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001462 }
1463
Jesse Hall178b6962016-02-24 15:39:50 -08001464 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1465 // applied during rendering. native_window_set_transform() expects the
1466 // inverse: the transform the app is requesting that the compositor perform
1467 // during composition. With native windows, pre-transform works by rendering
1468 // with the same transform the compositor is applying (as in Vulkan), but
1469 // then requesting the inverse transform, so that when the compositor does
1470 // it's job the two transforms cancel each other out and the compositor ends
1471 // up applying an identity transform to the app's buffer.
1472 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001473 window, InvertTransformToNative(create_info->preTransform));
1474 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001475 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1476 InvertTransformToNative(create_info->preTransform),
1477 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001478 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001479 }
1480
Jesse Hallf64ca122015-11-03 16:11:10 -08001481 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001482 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1483 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001484 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1485 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001486 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001487 }
1488
Chris Forbes97ef4612017-03-30 19:37:50 +13001489 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001490 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001491 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001492 err = native_window_set_shared_buffer_mode(window, true);
1493 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001494 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1495 return VK_ERROR_SURFACE_LOST_KHR;
1496 }
1497 }
1498
1499 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001500 err = native_window_set_auto_refresh(window, true);
1501 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001502 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1503 return VK_ERROR_SURFACE_LOST_KHR;
1504 }
1505 }
1506
Ian Elliott16c443c2021-11-30 17:10:32 -07001507 int query_value;
1508 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1509 &query_value);
1510 if (err != android::OK || query_value < 0) {
1511 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1512 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001513 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001514 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001515 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1516 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1517 const auto requested_images =
1518 swap_interval ? create_info->minImageCount : mailbox_num_images;
1519 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001520
Ian Elliott5396b702021-12-13 19:32:34 -07001521 // Lower layer insists that we have at least min_undequeued_buffers + 1
1522 // buffers. This is wasteful and we'd like to relax it in the shared case,
1523 // but not all the pieces are in place for that to work yet. Note we only
1524 // lie to the lower layer--we don't want to give the app back a swapchain
1525 // with extra images (which they can't actually use!).
1526 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1527 err = native_window_set_buffer_count(
1528 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001529 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001530 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1531 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001532 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001533 }
1534
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001535 // In shared mode the num_images must be one regardless of how many
1536 // buffers were allocated for the buffer queue.
1537 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1538 num_images = 1;
1539 }
1540
Trevor David Black2cc44682022-03-09 00:31:38 +00001541 void* usage_info_pNext = nullptr;
1542 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001543 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001544 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1545 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1546 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1547 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1548 gralloc_usage_info.format = create_info->imageFormat;
1549 gralloc_usage_info.imageUsage = create_info->imageUsage;
1550
1551 // Look through the pNext chain for an image compression control struct
1552 // if one is found AND the appropriate extensions are enabled,
1553 // append it to be the gralloc usage pNext chain
1554 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1555 while (create_infos->pNext) {
1556 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1557 create_infos->pNext);
1558 switch (create_infos->sType) {
1559 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1560 const VkImageCompressionControlEXT* compression_infos =
1561 reinterpret_cast<const VkImageCompressionControlEXT*>(
1562 create_infos);
1563 image_compression = *compression_infos;
1564 image_compression.pNext = nullptr;
1565 usage_info_pNext = &image_compression;
1566 } break;
1567
1568 default:
1569 // Ignore all other info structs
1570 break;
1571 }
1572 }
1573 gralloc_usage_info.pNext = usage_info_pNext;
1574
1575 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1576 device, &gralloc_usage_info, &native_usage);
1577 ATRACE_END();
1578 if (result != VK_SUCCESS) {
1579 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1580 return VK_ERROR_SURFACE_LOST_KHR;
1581 }
1582 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001583 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001584 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001585 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1586 device, create_info->imageFormat, create_info->imageUsage,
1587 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001588 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001589 if (result != VK_SUCCESS) {
1590 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001591 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001592 }
John Reck97678d42022-08-23 11:24:51 -04001593 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001594 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001595 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001596 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001597 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001598 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001599 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001600 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001601 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001602 if (result != VK_SUCCESS) {
1603 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001604 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001605 }
John Reck97678d42022-08-23 11:24:51 -04001606 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001607 }
John Reck97678d42022-08-23 11:24:51 -04001608 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001609
1610 bool createProtectedSwapchain = false;
1611 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1612 createProtectedSwapchain = true;
1613 native_usage |= BufferUsage::PROTECTED;
1614 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001615 err = native_window_set_usage(window, native_usage);
1616 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001617 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001618 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001619 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001620
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001621 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001622 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1623 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001624 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1625 strerror(-err), err);
1626 return VK_ERROR_SURFACE_LOST_KHR;
1627 }
1628
Jesse Halld7b994a2015-09-07 14:17:37 -07001629 // -- Allocate our Swapchain object --
1630 // After this point, we must deallocate the swapchain on error.
1631
Jesse Hall1f91d392015-12-11 16:28:44 -08001632 void* mem = allocator->pfnAllocation(allocator->pUserData,
1633 sizeof(Swapchain), alignof(Swapchain),
1634 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001635 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001636 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001637 Swapchain* swapchain = new (mem)
1638 Swapchain(surface, num_images, create_info->presentMode,
1639 TranslateVulkanToNativeTransform(create_info->preTransform));
Jesse Halld7b994a2015-09-07 14:17:37 -07001640
Chris Forbesb56287a2017-01-12 14:28:58 +13001641 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1642#pragma clang diagnostic push
1643#pragma clang diagnostic ignored "-Wold-style-cast"
1644 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1645#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001646 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001647 .usage = swapchain_image_usage,
1648 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001649 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001650#pragma clang diagnostic push
1651#pragma clang diagnostic ignored "-Wold-style-cast"
1652 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1653#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001654 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001655 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001656
Jesse Halld7b994a2015-09-07 14:17:37 -07001657 VkImageCreateInfo image_create = {
1658 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001659 .pNext = nullptr,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001660 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001661 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001662 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001663 .extent = {
1664 create_info->imageExtent.width,
1665 create_info->imageExtent.height,
1666 1
1667 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001668 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001669 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001670 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001671 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001672 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001673 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001674 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001675 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1676 };
1677
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001678 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1679 // involved so very little benefit.
1680 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1681 !IsSharedPresentMode(create_info->presentMode)) {
1682 // Don't want to touch the underlying gralloc buffers yet;
1683 // instead just create unbound VkImages which will later be bound to memory inside
1684 // AcquireNextImage.
1685 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1686 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1687 .pNext = nullptr,
1688 .swapchain = HandleFromSwapchain(swapchain),
1689 };
1690 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001691
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001692 for (uint32_t i = 0; i < num_images; i++) {
1693 Swapchain::Image& img = swapchain->images[i];
1694 img.buffer = nullptr;
1695 img.dequeued = false;
1696
1697 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1698 if (result != VK_SUCCESS) {
1699 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1700 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001701 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001702 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001703 } else {
1704 // -- Dequeue all buffers and create a VkImage for each --
1705 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001706
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001707 for (uint32_t i = 0; i < num_images; i++) {
1708 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001709
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001710 ANativeWindowBuffer* buffer;
1711 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1712 if (err != android::OK) {
1713 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1714 switch (-err) {
1715 case ENOMEM:
1716 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1717 break;
1718 default:
1719 result = VK_ERROR_SURFACE_LOST_KHR;
1720 break;
1721 }
1722 break;
1723 }
1724 img.buffer = buffer;
1725 img.dequeued = true;
1726
1727 image_native_buffer.handle = img.buffer->handle;
1728 image_native_buffer.stride = img.buffer->stride;
1729 image_native_buffer.format = img.buffer->format;
1730 image_native_buffer.usage = int(img.buffer->usage);
1731 android_convertGralloc0To1Usage(int(img.buffer->usage),
1732 &image_native_buffer.usage2.producer,
1733 &image_native_buffer.usage2.consumer);
1734 image_native_buffer.usage3 = img.buffer->usage;
1735 image_create.pNext = &image_native_buffer;
1736
1737 ATRACE_BEGIN("CreateImage");
1738 result =
1739 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1740 ATRACE_END();
1741 if (result != VK_SUCCESS) {
1742 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1743 break;
1744 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001745 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001746
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001747 // -- Cancel all buffers, returning them to the queue --
1748 // If an error occurred before, also destroy the VkImage and release the
1749 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1750 for (uint32_t i = 0; i < num_images; i++) {
1751 Swapchain::Image& img = swapchain->images[i];
1752 if (img.dequeued) {
1753 if (!swapchain->shared) {
1754 window->cancelBuffer(window, img.buffer.get(),
1755 img.dequeue_fence);
1756 img.dequeue_fence = -1;
1757 img.dequeued = false;
1758 }
Chris Forbese0ced032017-03-30 19:44:15 +13001759 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001760 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001761 }
1762
1763 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001764 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1765 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001766 return result;
1767 }
1768
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001769 if (transform_hint != swapchain->pre_transform) {
1770 // Log that the app is not doing pre-rotation.
1771 android::GraphicsEnv::getInstance().setTargetStats(
1772 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1773 }
1774
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001775 // Set stats for creating a Vulkan swapchain
1776 android::GraphicsEnv::getInstance().setTargetStats(
1777 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1778
Jesse Halldc225072016-05-30 22:40:14 -07001779 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1780 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001781 return VK_SUCCESS;
1782}
1783
Jesse Halle1b12782015-11-30 11:27:32 -08001784VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001785void DestroySwapchainKHR(VkDevice device,
1786 VkSwapchainKHR swapchain_handle,
1787 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001788 ATRACE_CALL();
1789
Yiwei Zhang533cea92019-06-03 18:43:24 -07001790 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001791}
1792
Jesse Halle1b12782015-11-30 11:27:32 -08001793VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001794VkResult GetSwapchainImagesKHR(VkDevice,
1795 VkSwapchainKHR swapchain_handle,
1796 uint32_t* count,
1797 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001798 ATRACE_CALL();
1799
Jesse Halld7b994a2015-09-07 14:17:37 -07001800 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001801 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1802 "getting images for non-active swapchain 0x%" PRIx64
1803 "; only dequeued image handles are valid",
1804 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001805 VkResult result = VK_SUCCESS;
1806 if (images) {
1807 uint32_t n = swapchain.num_images;
1808 if (*count < swapchain.num_images) {
1809 n = *count;
1810 result = VK_INCOMPLETE;
1811 }
1812 for (uint32_t i = 0; i < n; i++)
1813 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001814 *count = n;
1815 } else {
1816 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001817 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001818 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001819}
1820
Jesse Halle1b12782015-11-30 11:27:32 -08001821VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001822VkResult AcquireNextImageKHR(VkDevice device,
1823 VkSwapchainKHR swapchain_handle,
1824 uint64_t timeout,
1825 VkSemaphore semaphore,
1826 VkFence vk_fence,
1827 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001828 ATRACE_CALL();
1829
Jesse Halld7b994a2015-09-07 14:17:37 -07001830 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001831 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001832 VkResult result;
1833 int err;
1834
Jesse Halldc225072016-05-30 22:40:14 -07001835 if (swapchain.surface.swapchain_handle != swapchain_handle)
1836 return VK_ERROR_OUT_OF_DATE_KHR;
1837
Chris Forbesc88409c2017-03-30 19:47:37 +13001838 if (swapchain.shared) {
1839 // In shared mode, we keep the buffer dequeued all the time, so we don't
1840 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1841 // the semaphore and fence passed to us will be signalled.
1842 *image_index = 0;
1843 result = GetData(device).driver.AcquireImageANDROID(
1844 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1845 return result;
1846 }
1847
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001848 const nsecs_t acquire_next_image_timeout =
1849 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1850 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1851 // Cache the timeout to avoid the duplicate binder cost.
1852 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1853 acquire_next_image_timeout);
1854 if (err != android::OK) {
1855 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1856 strerror(-err), err);
1857 return VK_ERROR_SURFACE_LOST_KHR;
1858 }
1859 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1860 }
1861
Jesse Halld7b994a2015-09-07 14:17:37 -07001862 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001863 int fence_fd;
1864 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001865 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001866 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1867 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1868 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001869 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001870 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001871 }
1872
1873 uint32_t idx;
1874 for (idx = 0; idx < swapchain.num_images; idx++) {
1875 if (swapchain.images[idx].buffer.get() == buffer) {
1876 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001877 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001878 break;
1879 }
1880 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001881
1882 // If this is a deferred alloc swapchain, this may be the first time we've
1883 // seen a particular buffer. If so, there should be an empty slot. Find it,
1884 // and bind the gralloc buffer to the VkImage for that slot. If there is no
1885 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
1886 // will also take this path, but will never have an empty slot since we
1887 // populated them all upfront.
1888 if (idx == swapchain.num_images) {
1889 for (idx = 0; idx < swapchain.num_images; idx++) {
1890 if (!swapchain.images[idx].buffer) {
1891 // Note: this structure is technically required for
1892 // Vulkan correctness, even though the driver is probably going
1893 // to use everything from the VkNativeBufferANDROID below.
1894 // This is kindof silly, but it's how we did the ANB
1895 // side of VK_KHR_swapchain v69, so we're stuck with it unless
1896 // we want to go tinkering with the ANB spec some more.
1897 VkBindImageMemorySwapchainInfoKHR bimsi = {
1898 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
1899 .pNext = nullptr,
1900 .swapchain = swapchain_handle,
1901 .imageIndex = idx,
1902 };
1903 VkNativeBufferANDROID nb = {
1904 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1905 .pNext = &bimsi,
1906 .handle = buffer->handle,
1907 .stride = buffer->stride,
1908 .format = buffer->format,
1909 .usage = int(buffer->usage),
1910 };
1911 VkBindImageMemoryInfo bimi = {
1912 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
1913 .pNext = &nb,
1914 .image = swapchain.images[idx].image,
1915 .memory = VK_NULL_HANDLE,
1916 .memoryOffset = 0,
1917 };
1918 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
1919 if (result != VK_SUCCESS) {
1920 // This shouldn't really happen. If it does, something is probably
1921 // unrecoverably wrong with the swapchain and its images. Cancel
1922 // the buffer and declare the swapchain broken.
1923 ALOGE("failed to do deferred gralloc buffer bind");
1924 window->cancelBuffer(window, buffer, fence_fd);
1925 return VK_ERROR_OUT_OF_DATE_KHR;
1926 }
1927
1928 swapchain.images[idx].dequeued = true;
1929 swapchain.images[idx].dequeue_fence = fence_fd;
1930 swapchain.images[idx].buffer = buffer;
1931 break;
1932 }
1933 }
1934 }
1935
1936 // The buffer doesn't match any slot. This shouldn't normally happen, but is
1937 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
1938 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07001939 if (idx == swapchain.num_images) {
1940 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001941 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001942 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001943 }
1944
1945 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001946 if (fence_fd != -1) {
1947 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001948 if (fence_clone == -1) {
1949 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1950 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001951 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001952 }
1953 }
1954
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001955 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001956 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001957 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001958 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1959 // even if the call fails. We could close it ourselves on failure, but
1960 // that would create a race condition if the driver closes it on a
1961 // failure path: some other thread might create an fd with the same
1962 // number between the time the driver closes it and the time we close
1963 // it. We must assume one of: the driver *always* closes it even on
1964 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001965 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001966 swapchain.images[idx].dequeued = false;
1967 swapchain.images[idx].dequeue_fence = -1;
1968 return result;
1969 }
1970
1971 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001972 return VK_SUCCESS;
1973}
1974
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001975VKAPI_ATTR
1976VkResult AcquireNextImage2KHR(VkDevice device,
1977 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1978 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001979 ATRACE_CALL();
1980
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001981 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1982 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1983 pAcquireInfo->fence, pImageIndex);
1984}
1985
Jesse Halldc225072016-05-30 22:40:14 -07001986static VkResult WorstPresentResult(VkResult a, VkResult b) {
1987 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1988 // (in spec version 1.0.14).
1989 static const VkResult kWorstToBest[] = {
1990 VK_ERROR_DEVICE_LOST,
1991 VK_ERROR_SURFACE_LOST_KHR,
1992 VK_ERROR_OUT_OF_DATE_KHR,
1993 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1994 VK_ERROR_OUT_OF_HOST_MEMORY,
1995 VK_SUBOPTIMAL_KHR,
1996 };
1997 for (auto result : kWorstToBest) {
1998 if (a == result || b == result)
1999 return result;
2000 }
2001 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
2002 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
2003 return a != VK_SUCCESS ? a : b;
2004}
2005
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002006// KHR_incremental_present aspect of QueuePresentKHR
2007static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
2008 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
2009 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
2010 auto const& rect = pRegion->pRectangles[i];
2011 if (rect.layer > 0) {
2012 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2013 rect.layer);
2014 }
2015
2016 rects[i].left = rect.offset.x;
2017 rects[i].bottom = rect.offset.y;
2018 rects[i].right = rect.offset.x + rect.extent.width;
2019 rects[i].top = rect.offset.y + rect.extent.height;
2020 }
2021 native_window_set_surface_damage(window, rects.data(), rects.size());
2022}
2023
2024// GOOGLE_display_timing aspect of QueuePresentKHR
2025static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2026 ANativeWindow *window = swapchain.surface.window.get();
2027
2028 // We don't know whether the app will actually use GOOGLE_display_timing
2029 // with a particular swapchain until QueuePresent; enable it on the BQ
2030 // now if needed
2031 if (!swapchain.frame_timestamps_enabled) {
2032 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2033 native_window_enable_frame_timestamps(window, true);
2034 swapchain.frame_timestamps_enabled = true;
2035 }
2036
2037 // Record the nativeFrameId so it can be later correlated to
2038 // this present.
2039 uint64_t nativeFrameId = 0;
2040 int err = native_window_get_next_frame_id(
2041 window, &nativeFrameId);
2042 if (err != android::OK) {
2043 ALOGE("Failed to get next native frame ID.");
2044 }
2045
2046 // Add a new timing record with the user's presentID and
2047 // the nativeFrameId.
2048 swapchain.timing.emplace_back(pTime, nativeFrameId);
2049 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2050 swapchain.timing.erase(
2051 swapchain.timing.begin(),
2052 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2053 }
2054 if (pTime->desiredPresentTime) {
2055 ALOGV(
2056 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2057 pTime->desiredPresentTime);
2058 native_window_set_buffers_timestamp(
2059 window,
2060 static_cast<int64_t>(pTime->desiredPresentTime));
2061 }
2062}
2063
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002064// EXT_swapchain_maintenance1 present mode change
2065static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2066 // There is no dynamic switching between non-shared present modes.
2067 // All we support is switching between demand and continuous refresh.
2068 if (!IsSharedPresentMode(mode))
2069 return true;
2070
2071 int err = native_window_set_auto_refresh(window,
2072 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2073 if (err != android::OK) {
2074 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2075 strerror(-err), err);
2076 return false;
2077 }
2078
2079 return true;
2080}
2081
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002082static VkResult PresentOneSwapchain(
2083 VkQueue queue,
2084 Swapchain& swapchain,
2085 uint32_t imageIndex,
2086 const VkPresentRegionKHR *pRegion,
2087 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002088 VkFence presentFence,
2089 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002090 uint32_t waitSemaphoreCount,
2091 const VkSemaphore *pWaitSemaphores) {
2092
2093 VkDevice device = GetData(queue).driver_device;
2094 const auto& dispatch = GetData(queue).driver;
2095
2096 Swapchain::Image& img = swapchain.images[imageIndex];
2097 VkResult swapchain_result = VK_SUCCESS;
2098 VkResult result;
2099 int err;
2100
2101 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2102 // wait semaphores, so this doesn't actually work for the multiple swapchain
2103 // case.
2104 int fence = -1;
2105 result = dispatch.QueueSignalReleaseImageANDROID(
2106 queue, waitSemaphoreCount,
2107 pWaitSemaphores, img.image, &fence);
2108 if (result != VK_SUCCESS) {
2109 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2110 swapchain_result = result;
2111 }
2112 if (img.release_fence >= 0)
2113 close(img.release_fence);
2114 img.release_fence = fence < 0 ? -1 : dup(fence);
2115
2116 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2117 ANativeWindow* window = swapchain.surface.window.get();
2118 if (swapchain_result == VK_SUCCESS) {
2119
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002120 if (presentFence != VK_NULL_HANDLE) {
2121 int fence_copy = fence < 0 ? -1 : dup(fence);
2122 VkImportFenceFdInfoKHR iffi = {
2123 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2124 nullptr,
2125 presentFence,
2126 VK_FENCE_IMPORT_TEMPORARY_BIT,
2127 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2128 fence_copy,
2129 };
2130 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2131 // ImportFenceFdKHR takes ownership only if it succeeds
2132 close(fence_copy);
2133 }
2134 }
2135
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002136 if (pRegion) {
2137 SetSwapchainSurfaceDamage(window, pRegion);
2138 }
2139 if (pTime) {
2140 SetSwapchainFrameTimestamp(swapchain, pTime);
2141 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002142 if (pPresentMode) {
2143 if (!SetSwapchainPresentMode(window, *pPresentMode))
2144 swapchain_result = WorstPresentResult(swapchain_result,
2145 VK_ERROR_SURFACE_LOST_KHR);
2146 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002147
2148 err = window->queueBuffer(window, img.buffer.get(), fence);
2149 // queueBuffer always closes fence, even on error
2150 if (err != android::OK) {
2151 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2152 swapchain_result = WorstPresentResult(
2153 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2154 } else {
2155 if (img.dequeue_fence >= 0) {
2156 close(img.dequeue_fence);
2157 img.dequeue_fence = -1;
2158 }
2159 img.dequeued = false;
2160 }
2161
2162 // If the swapchain is in shared mode, immediately dequeue the
2163 // buffer so it can be presented again without an intervening
2164 // call to AcquireNextImageKHR. We expect to get the same buffer
2165 // back from every call to dequeueBuffer in this mode.
2166 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2167 ANativeWindowBuffer* buffer;
2168 int fence_fd;
2169 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2170 if (err != android::OK) {
2171 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2172 swapchain_result = WorstPresentResult(swapchain_result,
2173 VK_ERROR_SURFACE_LOST_KHR);
2174 } else if (img.buffer != buffer) {
2175 ALOGE("got wrong image back for shared swapchain");
2176 swapchain_result = WorstPresentResult(swapchain_result,
2177 VK_ERROR_SURFACE_LOST_KHR);
2178 } else {
2179 img.dequeue_fence = fence_fd;
2180 img.dequeued = true;
2181 }
2182 }
2183 }
2184 if (swapchain_result != VK_SUCCESS) {
2185 OrphanSwapchain(device, &swapchain);
2186 }
2187 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2188 // and only when the window's transform/rotation changes. Extent
2189 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2190 // application issues that were caused when the following transform
2191 // change was added.
2192 int window_transform_hint;
2193 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2194 &window_transform_hint);
2195 if (err != android::OK) {
2196 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2197 strerror(-err), err);
2198 swapchain_result = WorstPresentResult(
2199 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2200 }
2201 if (swapchain.pre_transform != window_transform_hint) {
2202 swapchain_result =
2203 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2204 }
2205 } else {
2206 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2207 img, true);
2208 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2209 }
2210
2211 return swapchain_result;
2212}
2213
Jesse Halle1b12782015-11-30 11:27:32 -08002214VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002215VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002216 ATRACE_CALL();
2217
Jesse Halld7b994a2015-09-07 14:17:37 -07002218 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2219 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2220 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002221
Jesse Halld7b994a2015-09-07 14:17:37 -07002222 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002223
Ian Elliottcb351132016-12-13 10:30:40 -07002224 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002225 const VkPresentRegionsKHR* present_regions = nullptr;
2226 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002227 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2228 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2229
Ian Elliottcb351132016-12-13 10:30:40 -07002230 const VkPresentRegionsKHR* next =
2231 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2232 while (next) {
2233 switch (next->sType) {
2234 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2235 present_regions = next;
2236 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002237 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002238 present_times =
2239 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2240 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002241 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2242 present_fences =
2243 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2244 break;
2245 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2246 present_modes =
2247 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2248 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002249 default:
2250 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2251 next->sType);
2252 break;
2253 }
2254 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2255 }
2256 ALOGV_IF(
2257 present_regions &&
2258 present_regions->swapchainCount != present_info->swapchainCount,
2259 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002260 ALOGV_IF(present_times &&
2261 present_times->swapchainCount != present_info->swapchainCount,
2262 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2263 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002264 ALOGV_IF(present_fences &&
2265 present_fences->swapchainCount != present_info->swapchainCount,
2266 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2267 "VkPresentInfo::swapchainCount");
2268 ALOGV_IF(present_modes &&
2269 present_modes->swapchainCount != present_info->swapchainCount,
2270 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2271 "VkPresentInfo::swapchainCount");
2272
Ian Elliottcb351132016-12-13 10:30:40 -07002273 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002274 (present_regions) ? present_regions->pRegions : nullptr;
2275 const VkPresentTimeGOOGLE* times =
2276 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002277
Jesse Halld7b994a2015-09-07 14:17:37 -07002278 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2279 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002280 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002281
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002282 VkResult swapchain_result = PresentOneSwapchain(
2283 queue,
2284 swapchain,
2285 present_info->pImageIndices[sc],
2286 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2287 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002288 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2289 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002290 present_info->waitSemaphoreCount,
2291 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002292
Jesse Halla9e57032015-11-30 01:03:10 -08002293 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002294 present_info->pResults[sc] = swapchain_result;
2295
2296 if (swapchain_result != final_result)
2297 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002298 }
2299
2300 return final_result;
2301}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002302
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002303VKAPI_ATTR
2304VkResult GetRefreshCycleDurationGOOGLE(
2305 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002306 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002307 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002308 ATRACE_CALL();
2309
Ian Elliott62c48c92017-01-20 13:13:20 -07002310 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002311 VkResult result = VK_SUCCESS;
2312
Ian Elliott3568bfe2019-05-03 15:54:46 -06002313 pDisplayTimingProperties->refreshDuration = swapchain.get_refresh_duration();
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002314
2315 return result;
2316}
2317
2318VKAPI_ATTR
2319VkResult GetPastPresentationTimingGOOGLE(
2320 VkDevice,
2321 VkSwapchainKHR swapchain_handle,
2322 uint32_t* count,
2323 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002324 ATRACE_CALL();
2325
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002326 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002327 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2328 return VK_ERROR_OUT_OF_DATE_KHR;
2329 }
2330
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002331 ANativeWindow* window = swapchain.surface.window.get();
2332 VkResult result = VK_SUCCESS;
2333
2334 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002335 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002336 native_window_enable_frame_timestamps(window, true);
2337 swapchain.frame_timestamps_enabled = true;
2338 }
2339
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002340 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002341 // Get the latest ready timing count before copying, since the copied
2342 // timing info will be erased in copy_ready_timings function.
2343 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002344 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002345 // Check the *count here against the recorded ready timing count, since
2346 // *count can be overwritten per spec describes.
2347 if (*count < n) {
2348 result = VK_INCOMPLETE;
2349 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002350 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002351 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002352 }
2353
2354 return result;
2355}
2356
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002357VKAPI_ATTR
2358VkResult GetSwapchainStatusKHR(
2359 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002360 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002361 ATRACE_CALL();
2362
Chris Forbes4e18ba82017-01-20 12:50:17 +13002363 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002364 VkResult result = VK_SUCCESS;
2365
Chris Forbes4e18ba82017-01-20 12:50:17 +13002366 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2367 return VK_ERROR_OUT_OF_DATE_KHR;
2368 }
2369
Yiwei Zhanga885c062019-10-24 12:07:57 -07002370 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002371
2372 return result;
2373}
2374
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002375VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002376 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002377 uint32_t swapchainCount,
2378 const VkSwapchainKHR* pSwapchains,
2379 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002380 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002381
2382 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2383 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2384 if (!swapchain)
2385 continue;
2386
2387 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2388
2389 ANativeWindow* window = swapchain->surface.window.get();
2390
2391 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2392 const android_smpte2086_metadata smpteMetdata = {
2393 {vulkanMetadata.displayPrimaryRed.x,
2394 vulkanMetadata.displayPrimaryRed.y},
2395 {vulkanMetadata.displayPrimaryGreen.x,
2396 vulkanMetadata.displayPrimaryGreen.y},
2397 {vulkanMetadata.displayPrimaryBlue.x,
2398 vulkanMetadata.displayPrimaryBlue.y},
2399 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2400 vulkanMetadata.maxLuminance,
2401 vulkanMetadata.minLuminance};
2402 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2403
2404 const android_cta861_3_metadata cta8613Metadata = {
2405 vulkanMetadata.maxContentLightLevel,
2406 vulkanMetadata.maxFrameAverageLightLevel};
2407 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2408 }
2409
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002410 return;
2411}
2412
Yiwei Zhang0f475222019-04-11 19:38:00 -07002413static void InterceptBindImageMemory2(
2414 uint32_t bind_info_count,
2415 const VkBindImageMemoryInfo* bind_infos,
2416 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2417 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2418 out_native_buffers->clear();
2419 out_bind_infos->clear();
2420
2421 if (!bind_info_count)
2422 return;
2423
2424 std::unordered_set<uint32_t> intercepted_indexes;
2425
2426 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2427 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2428 bind_infos[idx].pNext);
2429 while (info &&
2430 info->sType !=
2431 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2432 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2433 info->pNext);
2434 }
2435
2436 if (!info)
2437 continue;
2438
2439 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2440 "swapchain handle must not be NULL");
2441 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2442 ALOG_ASSERT(
2443 info->imageIndex < swapchain->num_images,
2444 "imageIndex must be less than the number of images in swapchain");
2445
2446 ANativeWindowBuffer* buffer =
2447 swapchain->images[info->imageIndex].buffer.get();
2448 VkNativeBufferANDROID native_buffer = {
2449#pragma clang diagnostic push
2450#pragma clang diagnostic ignored "-Wold-style-cast"
2451 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2452#pragma clang diagnostic pop
2453 .pNext = bind_infos[idx].pNext,
2454 .handle = buffer->handle,
2455 .stride = buffer->stride,
2456 .format = buffer->format,
2457 .usage = int(buffer->usage),
2458 };
2459 // Reserve enough space to avoid letting re-allocation invalidate the
2460 // addresses of the elements inside.
2461 out_native_buffers->reserve(bind_info_count);
2462 out_native_buffers->emplace_back(native_buffer);
2463
2464 // Reserve the space now since we know how much is needed now.
2465 out_bind_infos->reserve(bind_info_count);
2466 out_bind_infos->emplace_back(bind_infos[idx]);
2467 out_bind_infos->back().pNext = &out_native_buffers->back();
2468
2469 intercepted_indexes.insert(idx);
2470 }
2471
2472 if (intercepted_indexes.empty())
2473 return;
2474
2475 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2476 if (intercepted_indexes.count(idx))
2477 continue;
2478 out_bind_infos->emplace_back(bind_infos[idx]);
2479 }
2480}
2481
Yiwei Zhang23143102019-04-10 18:24:05 -07002482VKAPI_ATTR
2483VkResult BindImageMemory2(VkDevice device,
2484 uint32_t bindInfoCount,
2485 const VkBindImageMemoryInfo* pBindInfos) {
2486 ATRACE_CALL();
2487
Yiwei Zhang0f475222019-04-11 19:38:00 -07002488 // out_native_buffers is for maintaining the lifecycle of the constructed
2489 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2490 std::vector<VkNativeBufferANDROID> out_native_buffers;
2491 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2492 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2493 &out_bind_infos);
2494 return GetData(device).driver.BindImageMemory2(
2495 device, bindInfoCount,
2496 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002497}
2498
2499VKAPI_ATTR
2500VkResult BindImageMemory2KHR(VkDevice device,
2501 uint32_t bindInfoCount,
2502 const VkBindImageMemoryInfo* pBindInfos) {
2503 ATRACE_CALL();
2504
Yiwei Zhang0f475222019-04-11 19:38:00 -07002505 std::vector<VkNativeBufferANDROID> out_native_buffers;
2506 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2507 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2508 &out_bind_infos);
2509 return GetData(device).driver.BindImageMemory2KHR(
2510 device, bindInfoCount,
2511 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002512}
2513
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002514VKAPI_ATTR
2515VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2516 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2517 ATRACE_CALL();
2518
2519 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2520 ANativeWindow* window = swapchain.surface.window.get();
2521
2522 // If in shared present mode, don't actually release the image back to the BQ.
2523 // Both sides share it forever.
2524 if (swapchain.shared)
2525 return VK_SUCCESS;
2526
2527 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2528 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2529 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2530
2531 // cancelBuffer has taken ownership of the dequeue fence
2532 img.dequeue_fence = -1;
2533 // if we're still holding a release fence, get rid of it now
2534 if (img.release_fence >= 0) {
2535 close(img.release_fence);
2536 img.release_fence = -1;
2537 }
2538 img.dequeued = false;
2539 }
2540
2541 return VK_SUCCESS;
2542}
2543
Chia-I Wu62262232016-03-26 07:06:44 +08002544} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002545} // namespace vulkan