blob: b03200e4a77790255a09d0412d08f19ac89a17cc [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;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800294 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700295 // The fence is only valid when the buffer is dequeued, and should be
296 // -1 any other time. When valid, we own the fd, and must ensure it is
297 // closed: either by closing it explicitly when queueing the buffer,
298 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
299 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700300 // This fence is a dup of the sync fd returned from the driver via
301 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
302 // ensure it is closed upon re-presenting or releasing the image.
303 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700304 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800305 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700306
Yiwei Zhang5e862202019-06-21 14:59:16 -0700307 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700308};
309
310VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
311 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
312}
313
314Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800315 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700316}
317
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700318static bool IsFencePending(int fd) {
319 if (fd < 0)
320 return false;
321
322 errno = 0;
323 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
324}
325
Jesse Halldc225072016-05-30 22:40:14 -0700326void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000327 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700328 ANativeWindow* window,
329 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700330 Swapchain::Image& image,
331 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700332 ATRACE_CALL();
333
Jesse Halldc225072016-05-30 22:40:14 -0700334 ALOG_ASSERT(release_fence == -1 || image.dequeued,
335 "ReleaseSwapchainImage: can't provide a release fence for "
336 "non-dequeued images");
337
338 if (image.dequeued) {
339 if (release_fence >= 0) {
340 // We get here from vkQueuePresentKHR. The application is
341 // responsible for creating an execution dependency chain from
342 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
343 // (release_fence), so we can drop the dequeue_fence here.
344 if (image.dequeue_fence >= 0)
345 close(image.dequeue_fence);
346 } else {
347 // We get here during swapchain destruction, or various serious
348 // error cases e.g. when we can't create the release_fence during
349 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
350 // have already signalled, since the swapchain images are supposed
351 // to be idle before the swapchain is destroyed. In error cases,
352 // there may be rendering in flight to the image, but since we
353 // weren't able to create a release_fence, waiting for the
354 // dequeue_fence is about the best we can do.
355 release_fence = image.dequeue_fence;
356 }
357 image.dequeue_fence = -1;
358
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000359 // It's invalid to call cancelBuffer on a shared buffer
360 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700361 window->cancelBuffer(window, image.buffer.get(), release_fence);
362 } else {
363 if (release_fence >= 0) {
364 sync_wait(release_fence, -1 /* forever */);
365 close(release_fence);
366 }
367 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700368 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700369 image.dequeued = false;
370 }
371
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700372 if (defer_if_pending && IsFencePending(image.release_fence))
373 return;
374
375 if (image.release_fence >= 0) {
376 close(image.release_fence);
377 image.release_fence = -1;
378 }
379
Jesse Halldc225072016-05-30 22:40:14 -0700380 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700381 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700382 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700383 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700384 image.image = VK_NULL_HANDLE;
385 }
386
387 image.buffer.clear();
388}
389
390void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
391 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
392 return;
Jesse Halldc225072016-05-30 22:40:14 -0700393 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000394 if (!swapchain->images[i].dequeued) {
395 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
396 swapchain->images[i], true);
397 }
Jesse Halldc225072016-05-30 22:40:14 -0700398 }
399 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700400 swapchain->timing.clear();
401}
402
403uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800404 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
405 return 0;
406 }
Ian Elliott8a977262017-01-19 09:05:58 -0700407
Brian Anderson1049d1d2016-12-16 17:25:57 -0800408 uint32_t num_ready = 0;
409 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
410 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700411 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800412 if (ti.ready()) {
413 // This TimingInfo is ready to be reported to the user. Add it
414 // to the num_ready.
415 num_ready++;
416 continue;
417 }
418 // This TimingInfo is not yet ready to be reported to the user,
419 // and so we should look for any available timestamps that
420 // might make it ready.
421 int64_t desired_present_time = 0;
422 int64_t render_complete_time = 0;
423 int64_t composition_latch_time = 0;
424 int64_t actual_present_time = 0;
425 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800426 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800427 swapchain.surface.window.get(), ti.native_frame_id_,
428 &desired_present_time, &render_complete_time,
429 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700430 nullptr, //&first_composition_start_time,
431 nullptr, //&last_composition_start_time,
432 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800433 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700434 nullptr, //&dequeue_ready_time,
435 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800436
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800437 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800438 continue;
439 }
440
441 // Record the timestamp(s) we received, and then see if this TimingInfo
442 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700443 ti.timestamp_desired_present_time_ = desired_present_time;
444 ti.timestamp_actual_present_time_ = actual_present_time;
445 ti.timestamp_render_complete_time_ = render_complete_time;
446 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447
448 if (ti.ready()) {
449 // The TimingInfo has received enough timestamps, and should now
450 // use those timestamps to calculate the info that should be
451 // reported to the user:
452 ti.calculate(swapchain.refresh_duration);
453 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700454 }
455 }
456 return num_ready;
457}
458
Ian Elliott8a977262017-01-19 09:05:58 -0700459void copy_ready_timings(Swapchain& swapchain,
460 uint32_t* count,
461 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800462 if (swapchain.timing.empty()) {
463 *count = 0;
464 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700465 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800466
467 size_t last_ready = swapchain.timing.size() - 1;
468 while (!swapchain.timing[last_ready].ready()) {
469 if (last_ready == 0) {
470 *count = 0;
471 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700472 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800473 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700474 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800475
476 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700477 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800478 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
479 const TimingInfo& ti = swapchain.timing[i];
480 if (ti.ready()) {
481 ti.get_values(&timings[num_copied]);
482 num_copied++;
483 }
484 num_to_remove++;
485 }
486
487 // Discard old frames that aren't ready if newer frames are ready.
488 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700489 swapchain.timing.erase(swapchain.timing.begin(),
490 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800491
Ian Elliott8a977262017-01-19 09:05:58 -0700492 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700493}
494
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500495android::PixelFormat GetNativePixelFormat(VkFormat format) {
496 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700497 switch (format) {
498 case VK_FORMAT_R8G8B8A8_UNORM:
499 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500500 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700501 break;
502 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500503 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700504 break;
505 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500506 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700507 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800508 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500509 native_format = android::PIXEL_FORMAT_RGBA_1010102;
510 break;
511 case VK_FORMAT_R8_UNORM:
512 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700513 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000514 // TODO: Do we need to query for VK_EXT_rgba10x6_formats here?
515 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
516 native_format = android::PIXEL_FORMAT_RGBA_10101010;
517 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700518 default:
519 ALOGV("unsupported swapchain format %d", format);
520 break;
521 }
522 return native_format;
523}
524
525android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
526 switch (colorspace) {
527 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
528 return HAL_DATASPACE_V0_SRGB;
529 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
530 return HAL_DATASPACE_DISPLAY_P3;
531 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
532 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600533 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
534 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700535 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
536 return HAL_DATASPACE_DCI_P3_LINEAR;
537 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
538 return HAL_DATASPACE_DCI_P3;
539 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
540 return HAL_DATASPACE_V0_SRGB_LINEAR;
541 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
542 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600543 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
544 return HAL_DATASPACE_BT2020_LINEAR;
545 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700546 return static_cast<android_dataspace>(
547 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
548 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600549 case VK_COLOR_SPACE_DOLBYVISION_EXT:
550 return static_cast<android_dataspace>(
551 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
552 HAL_DATASPACE_RANGE_FULL);
553 case VK_COLOR_SPACE_HDR10_HLG_EXT:
554 return static_cast<android_dataspace>(
555 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
556 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700557 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
558 return static_cast<android_dataspace>(
559 HAL_DATASPACE_STANDARD_ADOBE_RGB |
560 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
561 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
562 return HAL_DATASPACE_ADOBE_RGB;
563
564 // Pass through is intended to allow app to provide data that is passed
565 // to the display system without modification.
566 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
567 return HAL_DATASPACE_ARBITRARY;
568
569 default:
570 // This indicates that we don't know about the
571 // dataspace specified and we should indicate that
572 // it's unsupported
573 return HAL_DATASPACE_UNKNOWN;
574 }
575}
576
Jesse Halld7b994a2015-09-07 14:17:37 -0700577} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700578
Jesse Halle1b12782015-11-30 11:27:32 -0800579VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800580VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800581 VkInstance instance,
582 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
583 const VkAllocationCallbacks* allocator,
584 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800585 ATRACE_CALL();
586
Jesse Hall1f91d392015-12-11 16:28:44 -0800587 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800588 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800589 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
590 alignof(Surface),
591 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800592 if (!mem)
593 return VK_ERROR_OUT_OF_HOST_MEMORY;
594 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700595
Chia-I Wue8e689f2016-04-18 08:21:31 +0800596 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700597 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700598 int err = native_window_get_consumer_usage(surface->window.get(),
599 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800600 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700601 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
602 strerror(-err), err);
603 surface->~Surface();
604 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700605 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700606 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700607
Yiwei Zhang6435b322018-05-08 11:12:17 -0700608 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800609 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800610 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800611 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
612 err);
613 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800614 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700615 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800616 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700617
Jesse Hall1356b0d2015-11-23 17:24:58 -0800618 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700619 return VK_SUCCESS;
620}
621
Jesse Halle1b12782015-11-30 11:27:32 -0800622VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800623void DestroySurfaceKHR(VkInstance instance,
624 VkSurfaceKHR surface_handle,
625 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800626 ATRACE_CALL();
627
Jesse Hall1356b0d2015-11-23 17:24:58 -0800628 Surface* surface = SurfaceFromHandle(surface_handle);
629 if (!surface)
630 return;
631 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700632 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700633 "destroyed VkSurfaceKHR 0x%" PRIx64
634 " has active VkSwapchainKHR 0x%" PRIx64,
635 reinterpret_cast<uint64_t>(surface_handle),
636 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800637 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800638 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800639 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800640 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800641}
642
Jesse Halle1b12782015-11-30 11:27:32 -0800643VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800644VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
645 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000646 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800647 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000648 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800649 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800650}
651
Jesse Halle1b12782015-11-30 11:27:32 -0800652VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800653VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600654 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800655 VkSurfaceKHR surface,
656 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800657 ATRACE_CALL();
658
Ian Elliottac40c1e2022-12-21 23:16:21 +0000659 int err;
660 int width, height;
661 int transform_hint;
662 int max_buffer_count;
663 if (surface == VK_NULL_HANDLE) {
664 const InstanceData& instance_data = GetData(pdev);
665 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
666 bool surfaceless_enabled =
667 instance_data.hook_extensions.test(surfaceless);
668 if (!surfaceless_enabled) {
669 // It is an error to pass a surface==VK_NULL_HANDLE unless the
670 // VK_GOOGLE_surfaceless_query extension is enabled
671 return VK_ERROR_SURFACE_LOST_KHR;
672 }
673 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
674 // extension for this function is for
675 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
676 // four values cannot be known without a surface. Default values will
677 // be supplied anyway, but cannot be relied upon.
678 width = 0xFFFFFFFF;
679 height = 0xFFFFFFFF;
680 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
681 capabilities->minImageCount = 0xFFFFFFFF;
682 capabilities->maxImageCount = 0xFFFFFFFF;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600683 } else {
Ian Elliottac40c1e2022-12-21 23:16:21 +0000684 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
685
686 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
687 if (err != android::OK) {
688 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
689 strerror(-err), err);
690 return VK_ERROR_SURFACE_LOST_KHR;
691 }
692 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
693 if (err != android::OK) {
694 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
695 strerror(-err), err);
696 return VK_ERROR_SURFACE_LOST_KHR;
697 }
698
699 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
700 &transform_hint);
701 if (err != android::OK) {
702 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
703 strerror(-err), err);
704 return VK_ERROR_SURFACE_LOST_KHR;
705 }
706
707 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
708 &max_buffer_count);
709 if (err != android::OK) {
710 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
711 strerror(-err), err);
712 return VK_ERROR_SURFACE_LOST_KHR;
713 }
714 capabilities->minImageCount = std::min(max_buffer_count, 3);
715 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800716 }
Ian Elliottac40c1e2022-12-21 23:16:21 +0000717
718 capabilities->currentExtent =
719 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
720
721 // TODO(http://b/134182502): Figure out what the max extent should be.
722 capabilities->minImageExtent = VkExtent2D{1, 1};
723 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
724
725 if (capabilities->maxImageExtent.height <
726 capabilities->currentExtent.height) {
727 capabilities->maxImageExtent.height =
728 capabilities->currentExtent.height;
729 }
730
731 if (capabilities->maxImageExtent.width <
732 capabilities->currentExtent.width) {
733 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
734 }
735
736 capabilities->maxImageArrayLayers = 1;
737
738 capabilities->supportedTransforms = kSupportedTransforms;
739 capabilities->currentTransform =
740 TranslateNativeToVulkanTransform(transform_hint);
741
742 // On Android, window composition is a WindowManager property, not something
743 // associated with the bufferqueue. It can't be changed from here.
744 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
745
746 capabilities->supportedUsageFlags =
747 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
748 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
749 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
750 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
751
752 return VK_SUCCESS;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700753}
754
Jesse Halle1b12782015-11-30 11:27:32 -0800755VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700756VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
757 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800758 uint32_t* count,
759 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800760 ATRACE_CALL();
761
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700762 const InstanceData& instance_data = GetData(pdev);
763
Ian Elliott1ce053f2022-03-16 09:49:53 -0600764 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000765 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600766 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600767 if (surface_handle == VK_NULL_HANDLE) {
768 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
769 bool surfaceless_enabled =
770 instance_data.hook_extensions.test(surfaceless);
771 if (!surfaceless_enabled) {
772 return VK_ERROR_SURFACE_LOST_KHR;
773 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300774 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600775
776 // TODO(b/203826952): research proper value; temporarily use the
777 // values seen on Pixel
778 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
779 } else {
780 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600781 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700782 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700783
Charlie Lao324191f2019-12-13 11:03:16 -0800784 AHardwareBuffer_Desc desc = {};
785 desc.width = 1;
786 desc.height = 1;
787 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600788 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800789 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
790
791 // We must support R8G8B8A8
792 std::vector<VkSurfaceFormatKHR> all_formats = {
793 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000794 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000795 };
Charlie Lao324191f2019-12-13 11:03:16 -0800796
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000797 if (colorspace_ext) {
798 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800799 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
800 all_formats.emplace_back(VkSurfaceFormatKHR{
801 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
802 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000803 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800804 all_formats.emplace_back(VkSurfaceFormatKHR{
805 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
806 all_formats.emplace_back(VkSurfaceFormatKHR{
807 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
808 }
809
Ian Elliott1ce053f2022-03-16 09:49:53 -0600810 // NOTE: Any new formats that are added must be coordinated across different
811 // Android users. This includes the ANGLE team (a layered implementation of
812 // OpenGL-ES).
813
Charlie Lao324191f2019-12-13 11:03:16 -0800814 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
815 if (AHardwareBuffer_isSupported(&desc)) {
816 all_formats.emplace_back(VkSurfaceFormatKHR{
817 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800818 if (colorspace_ext) {
819 all_formats.emplace_back(
820 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
821 VK_COLOR_SPACE_PASS_THROUGH_EXT});
822 }
Charlie Lao324191f2019-12-13 11:03:16 -0800823 }
824
825 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
826 if (AHardwareBuffer_isSupported(&desc)) {
827 all_formats.emplace_back(VkSurfaceFormatKHR{
828 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800829 if (colorspace_ext) {
830 all_formats.emplace_back(
831 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
832 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800833 all_formats.emplace_back(
834 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
835 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
836 all_formats.emplace_back(
837 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
838 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
839 }
840 }
841
842 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
843 if (AHardwareBuffer_isSupported(&desc)) {
844 all_formats.emplace_back(
845 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
846 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800847 if (colorspace_ext) {
848 all_formats.emplace_back(
849 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
850 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800851 all_formats.emplace_back(
852 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
853 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
854 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700855 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700856
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500857 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
858 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800859 if (colorspace_ext) {
860 all_formats.emplace_back(VkSurfaceFormatKHR{
861 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
862 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500863 }
864
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000865 // TODO query VK_EXT_rgba10x6_formats support
866 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
867 if (AHardwareBuffer_isSupported(&desc)) {
868 all_formats.emplace_back(
869 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
870 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
871 if (colorspace_ext) {
872 all_formats.emplace_back(
873 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
874 VK_COLOR_SPACE_PASS_THROUGH_EXT});
875 all_formats.emplace_back(
876 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
877 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
878 }
879 }
880
Ian Elliott6ba85d92022-02-18 16:44:58 -0700881 // NOTE: Any new formats that are added must be coordinated across different
882 // Android users. This includes the ANGLE team (a layered implementation of
883 // OpenGL-ES).
884
Ian Elliottac40c1e2022-12-21 23:16:21 +0000885 VkResult result = VK_SUCCESS;
886 if (formats) {
887 uint32_t transfer_count = all_formats.size();
888 if (transfer_count > *count) {
889 transfer_count = *count;
890 result = VK_INCOMPLETE;
891 }
892 std::copy(all_formats.begin(), all_formats.begin() + transfer_count,
893 formats);
894 *count = transfer_count;
895 } else {
896 *count = all_formats.size();
897 }
898
899 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700900}
901
Jesse Halle1b12782015-11-30 11:27:32 -0800902VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300903VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
904 VkPhysicalDevice physicalDevice,
905 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
906 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800907 ATRACE_CALL();
908
Ian Elliottac40c1e2022-12-21 23:16:21 +0000909 VkResult result = GetPhysicalDeviceSurfaceCapabilitiesKHR(
910 physicalDevice, pSurfaceInfo->surface,
911 &pSurfaceCapabilities->surfaceCapabilities);
Chris Forbes2452cf72017-03-16 16:30:17 +1300912
Ian Elliottac40c1e2022-12-21 23:16:21 +0000913 VkSurfaceCapabilities2KHR* caps = pSurfaceCapabilities;
914 while (caps->pNext) {
915 caps = reinterpret_cast<VkSurfaceCapabilities2KHR*>(caps->pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300916
Ian Elliottac40c1e2022-12-21 23:16:21 +0000917 switch (caps->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300918 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
919 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Ian Elliottac40c1e2022-12-21 23:16:21 +0000920 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(
921 caps);
Chris Forbes06bc0092017-03-16 16:46:05 +1300922 // Claim same set of usage flags are supported for
923 // shared present modes as for other modes.
924 shared_caps->sharedPresentSupportedUsageFlags =
925 pSurfaceCapabilities->surfaceCapabilities
926 .supportedUsageFlags;
927 } break;
928
Ian Elliottbb67b242022-03-16 09:52:28 -0600929 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
930 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Ian Elliottac40c1e2022-12-21 23:16:21 +0000931 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(caps);
Ian Elliottbb67b242022-03-16 09:52:28 -0600932 protected_caps->supportsProtected = VK_TRUE;
933 } break;
934
Chris Forbes06bc0092017-03-16 16:46:05 +1300935 default:
936 // Ignore all other extension structs
937 break;
938 }
939 }
940
Ian Elliottac40c1e2022-12-21 23:16:21 +0000941 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +1300942}
943
944VKAPI_ATTR
945VkResult GetPhysicalDeviceSurfaceFormats2KHR(
946 VkPhysicalDevice physicalDevice,
947 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
948 uint32_t* pSurfaceFormatCount,
949 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800950 ATRACE_CALL();
951
Chris Forbes2452cf72017-03-16 16:30:17 +1300952 if (!pSurfaceFormats) {
953 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
954 pSurfaceInfo->surface,
955 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +0000956 }
Chris Forbes2452cf72017-03-16 16:30:17 +1300957
Trevor David Black929e9cd2022-11-22 04:12:19 +0000958 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
959 // after the call.
960 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
961 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
962 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
963 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +0000964
Trevor David Black929e9cd2022-11-22 04:12:19 +0000965 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
966 return result;
967 }
Trevor David Black2cc44682022-03-09 00:31:38 +0000968
Trevor David Black929e9cd2022-11-22 04:12:19 +0000969 const auto& driver = GetData(physicalDevice).driver;
970
971 // marshal results individually due to stride difference.
972 uint32_t formats_to_marshal = *pSurfaceFormatCount;
973 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
974 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
975
976 // Query the compression properties for the surface format
977 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
978 while (pSurfaceFormat->pNext) {
979 pSurfaceFormat =
980 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
981 switch (pSurfaceFormat->sType) {
982 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +0000983 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
984 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +0000985 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +0000986
987 if (surfaceCompressionProps &&
988 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
989 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
990 imageFormatInfo.sType =
991 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
992 imageFormatInfo.format =
993 pSurfaceFormats[i].surfaceFormat.format;
994 imageFormatInfo.pNext = nullptr;
995
996 VkImageCompressionControlEXT compressionControl = {};
997 compressionControl.sType =
998 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
999 compressionControl.pNext = imageFormatInfo.pNext;
1000
1001 imageFormatInfo.pNext = &compressionControl;
1002
1003 VkImageCompressionPropertiesEXT compressionProps = {};
1004 compressionProps.sType =
1005 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1006 compressionProps.pNext = nullptr;
1007
1008 VkImageFormatProperties2KHR imageFormatProps = {};
1009 imageFormatProps.sType =
1010 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1011 imageFormatProps.pNext = &compressionProps;
1012
1013 VkResult compressionRes =
1014 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1015 physicalDevice, &imageFormatInfo,
1016 &imageFormatProps);
1017 if (compressionRes == VK_SUCCESS) {
1018 surfaceCompressionProps->imageCompressionFlags =
1019 compressionProps.imageCompressionFlags;
1020 surfaceCompressionProps
1021 ->imageCompressionFixedRateFlags =
1022 compressionProps.imageCompressionFixedRateFlags;
1023 } else {
1024 return compressionRes;
1025 }
1026 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001027 } break;
1028
1029 default:
1030 // Ignore all other extension structs
1031 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001032 }
1033 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001034 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001035
1036 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001037}
1038
1039VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001040VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001041 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001042 uint32_t* count,
1043 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001044 ATRACE_CALL();
1045
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001046 int err;
1047 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001048 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001049 if (surface == VK_NULL_HANDLE) {
1050 const InstanceData& instance_data = GetData(pdev);
1051 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1052 bool surfaceless_enabled =
1053 instance_data.hook_extensions.test(surfaceless);
1054 if (!surfaceless_enabled) {
1055 return VK_ERROR_SURFACE_LOST_KHR;
1056 }
1057 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1058 // extension for this function is for
1059 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1060 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1061 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001062 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001063 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1064 } else {
1065 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1066
1067 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1068 &query_value);
1069 if (err != android::OK || query_value < 0) {
1070 ALOGE(
1071 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1072 "value=%d",
1073 strerror(-err), err, query_value);
1074 return VK_ERROR_SURFACE_LOST_KHR;
1075 }
1076 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1077
1078 err =
1079 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1080 if (err != android::OK || query_value < 0) {
1081 ALOGE(
1082 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1083 strerror(-err), err, query_value);
1084 return VK_ERROR_SURFACE_LOST_KHR;
1085 }
1086 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1087
1088 if (min_undequeued_buffers + 1 < max_buffer_count)
1089 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1090 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1091 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001092
1093 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001094 QueryPresentationProperties(pdev, &present_properties);
1095 if (present_properties.sharedImage) {
1096 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1097 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001098 }
1099
Ian Elliottac40c1e2022-12-21 23:16:21 +00001100 uint32_t num_modes = uint32_t(present_modes.size());
1101
1102 VkResult result = VK_SUCCESS;
1103 if (modes) {
1104 if (*count < num_modes)
1105 result = VK_INCOMPLETE;
1106 *count = std::min(*count, num_modes);
1107 std::copy_n(present_modes.data(), *count, modes);
1108 } else {
1109 *count = num_modes;
1110 }
1111 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001112}
1113
Jesse Halle1b12782015-11-30 11:27:32 -08001114VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001115VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001116 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001117 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001118 ATRACE_CALL();
1119
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001120 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1121 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1122 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1123 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1124 pDeviceGroupPresentCapabilities->sType);
1125
1126 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1127 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1128
1129 // assume device group of size 1
1130 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1131 pDeviceGroupPresentCapabilities->modes =
1132 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1133
1134 return VK_SUCCESS;
1135}
1136
1137VKAPI_ATTR
1138VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001139 VkDevice,
1140 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001141 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001142 ATRACE_CALL();
1143
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001144 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1145 return VK_SUCCESS;
1146}
1147
1148VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001149VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001150 VkSurfaceKHR surface,
1151 uint32_t* pRectCount,
1152 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001153 ATRACE_CALL();
1154
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001155 if (!pRects) {
1156 *pRectCount = 1;
1157 } else {
1158 uint32_t count = std::min(*pRectCount, 1u);
1159 bool incomplete = *pRectCount < 1;
1160
1161 *pRectCount = count;
1162
1163 if (incomplete) {
1164 return VK_INCOMPLETE;
1165 }
1166
1167 int err;
1168 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1169
1170 int width = 0, height = 0;
1171 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001172 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001173 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1174 strerror(-err), err);
1175 }
1176 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001177 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001178 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1179 strerror(-err), err);
1180 }
1181
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001182 pRects[0].offset.x = 0;
1183 pRects[0].offset.y = 0;
1184 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1185 static_cast<uint32_t>(height)};
1186 }
1187 return VK_SUCCESS;
1188}
1189
Yiwei Zhang533cea92019-06-03 18:43:24 -07001190static void DestroySwapchainInternal(VkDevice device,
1191 VkSwapchainKHR swapchain_handle,
1192 const VkAllocationCallbacks* allocator) {
1193 ATRACE_CALL();
1194
1195 const auto& dispatch = GetData(device).driver;
1196 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1197 if (!swapchain) {
1198 return;
1199 }
1200
1201 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1202 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1203
1204 if (window && swapchain->frame_timestamps_enabled) {
1205 native_window_enable_frame_timestamps(window, false);
1206 }
1207
1208 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001209 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1210 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001211 }
1212
1213 if (active) {
1214 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1215 }
1216
1217 if (!allocator) {
1218 allocator = &GetData(device).allocator;
1219 }
1220
1221 swapchain->~Swapchain();
1222 allocator->pfnFree(allocator->pUserData, swapchain);
1223}
1224
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001225VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001226VkResult CreateSwapchainKHR(VkDevice device,
1227 const VkSwapchainCreateInfoKHR* create_info,
1228 const VkAllocationCallbacks* allocator,
1229 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001230 ATRACE_CALL();
1231
Jesse Halld7b994a2015-09-07 14:17:37 -07001232 int err;
1233 VkResult result = VK_SUCCESS;
1234
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001235 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1236 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1237 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1238 " oldSwapchain=0x%" PRIx64,
1239 reinterpret_cast<uint64_t>(create_info->surface),
1240 create_info->minImageCount, create_info->imageFormat,
1241 create_info->imageColorSpace, create_info->imageExtent.width,
1242 create_info->imageExtent.height, create_info->imageUsage,
1243 create_info->preTransform, create_info->presentMode,
1244 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1245
Jesse Hall1f91d392015-12-11 16:28:44 -08001246 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001247 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001248
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001249 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001250 GetNativePixelFormat(create_info->imageFormat);
1251 android_dataspace native_dataspace =
1252 GetNativeDataspace(create_info->imageColorSpace);
1253 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1254 ALOGE(
1255 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1256 "failed: Unsupported color space",
1257 create_info->imageColorSpace);
1258 return VK_ERROR_INITIALIZATION_FAILED;
1259 }
1260
Jesse Hall42a9eec2016-06-03 12:39:49 -07001261 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001262 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001263 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001264 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001265 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001266 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001267 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001268 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001269 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1270 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001271 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001272 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001273
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001274 Surface& surface = *SurfaceFromHandle(create_info->surface);
1275
Jesse Halldc225072016-05-30 22:40:14 -07001276 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001277 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001278 " because it already has active swapchain 0x%" PRIx64
1279 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1280 reinterpret_cast<uint64_t>(create_info->surface),
1281 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1282 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1283 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1284 }
1285 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1286 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1287
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001288 // -- Reset the native window --
1289 // The native window might have been used previously, and had its properties
1290 // changed from defaults. That will affect the answer we get for queries
1291 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1292 // attempt such queries.
1293
Jesse Halldc225072016-05-30 22:40:14 -07001294 // The native window only allows dequeueing all buffers before any have
1295 // been queued, since after that point at least one is assumed to be in
1296 // non-FREE state at any given time. Disconnecting and re-connecting
1297 // orphans the previous buffers, getting us back to the state where we can
1298 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001299 //
1300 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001301 ANativeWindow* window = surface.window.get();
1302 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1303 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001304 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001305 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1306 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001307 strerror(-err), err);
1308
Nicolas Capens147b7da2021-04-09 14:53:06 -04001309 err =
1310 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001311 if (err != android::OK) {
1312 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1313 strerror(-err), err);
1314 return VK_ERROR_SURFACE_LOST_KHR;
1315 }
1316
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301317 int swap_interval =
1318 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001319 err = window->setSwapInterval(window, swap_interval);
1320 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001321 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1322 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001323 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001324 }
1325
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001326 err = native_window_set_shared_buffer_mode(window, false);
1327 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001328 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1329 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001330 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001331 }
1332
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001333 err = native_window_set_auto_refresh(window, false);
1334 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001335 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1336 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001337 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001338 }
1339
Jesse Halld7b994a2015-09-07 14:17:37 -07001340 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001341
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001342 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001343
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001344 err = native_window_set_buffers_format(window, native_pixel_format);
1345 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001346 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1347 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001348 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001349 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001350
1351 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1352 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1353 err = native_window_set_buffers_data_space(window, native_dataspace);
1354 if (err != android::OK) {
1355 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1356 native_dataspace, strerror(-err), err);
1357 return VK_ERROR_SURFACE_LOST_KHR;
1358 }
Jesse Hall517274a2016-02-10 00:07:18 -08001359 }
1360
Jesse Hall3dd678a2016-01-08 21:52:01 -08001361 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001362 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001363 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001364 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001365 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1366 create_info->imageExtent.width, create_info->imageExtent.height,
1367 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001368 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001369 }
1370
Jesse Hall178b6962016-02-24 15:39:50 -08001371 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1372 // applied during rendering. native_window_set_transform() expects the
1373 // inverse: the transform the app is requesting that the compositor perform
1374 // during composition. With native windows, pre-transform works by rendering
1375 // with the same transform the compositor is applying (as in Vulkan), but
1376 // then requesting the inverse transform, so that when the compositor does
1377 // it's job the two transforms cancel each other out and the compositor ends
1378 // up applying an identity transform to the app's buffer.
1379 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001380 window, InvertTransformToNative(create_info->preTransform));
1381 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001382 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1383 InvertTransformToNative(create_info->preTransform),
1384 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001385 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001386 }
1387
Jesse Hallf64ca122015-11-03 16:11:10 -08001388 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001389 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1390 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001391 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1392 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001393 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001394 }
1395
Chris Forbes97ef4612017-03-30 19:37:50 +13001396 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Ian Elliottac40c1e2022-12-21 23:16:21 +00001397 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1398 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001399 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001400 err = native_window_set_shared_buffer_mode(window, true);
1401 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001402 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1403 return VK_ERROR_SURFACE_LOST_KHR;
1404 }
1405 }
1406
1407 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001408 err = native_window_set_auto_refresh(window, true);
1409 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001410 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1411 return VK_ERROR_SURFACE_LOST_KHR;
1412 }
1413 }
1414
Ian Elliott16c443c2021-11-30 17:10:32 -07001415 int query_value;
1416 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1417 &query_value);
1418 if (err != android::OK || query_value < 0) {
1419 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1420 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001421 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001422 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001423 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1424 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1425 const auto requested_images =
1426 swap_interval ? create_info->minImageCount : mailbox_num_images;
1427 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001428
Ian Elliott5396b702021-12-13 19:32:34 -07001429 // Lower layer insists that we have at least min_undequeued_buffers + 1
1430 // buffers. This is wasteful and we'd like to relax it in the shared case,
1431 // but not all the pieces are in place for that to work yet. Note we only
1432 // lie to the lower layer--we don't want to give the app back a swapchain
1433 // with extra images (which they can't actually use!).
1434 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1435 err = native_window_set_buffer_count(
1436 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001437 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001438 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1439 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001440 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001441 }
1442
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001443 // In shared mode the num_images must be one regardless of how many
1444 // buffers were allocated for the buffer queue.
1445 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1446 num_images = 1;
1447 }
1448
Trevor David Black2cc44682022-03-09 00:31:38 +00001449 void* usage_info_pNext = nullptr;
1450 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001451 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001452 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1453 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1454 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1455 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1456 gralloc_usage_info.format = create_info->imageFormat;
1457 gralloc_usage_info.imageUsage = create_info->imageUsage;
1458
1459 // Look through the pNext chain for an image compression control struct
1460 // if one is found AND the appropriate extensions are enabled,
1461 // append it to be the gralloc usage pNext chain
1462 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1463 while (create_infos->pNext) {
1464 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1465 create_infos->pNext);
1466 switch (create_infos->sType) {
1467 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1468 const VkImageCompressionControlEXT* compression_infos =
1469 reinterpret_cast<const VkImageCompressionControlEXT*>(
1470 create_infos);
1471 image_compression = *compression_infos;
1472 image_compression.pNext = nullptr;
1473 usage_info_pNext = &image_compression;
1474 } break;
1475
1476 default:
1477 // Ignore all other info structs
1478 break;
1479 }
1480 }
1481 gralloc_usage_info.pNext = usage_info_pNext;
1482
1483 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1484 device, &gralloc_usage_info, &native_usage);
1485 ATRACE_END();
1486 if (result != VK_SUCCESS) {
1487 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1488 return VK_ERROR_SURFACE_LOST_KHR;
1489 }
1490 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001491 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001492 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001493 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1494 device, create_info->imageFormat, create_info->imageUsage,
1495 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001496 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001497 if (result != VK_SUCCESS) {
1498 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001499 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001500 }
John Reck97678d42022-08-23 11:24:51 -04001501 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001502 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001503 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001504 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001505 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001506 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001507 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001508 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001509 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001510 if (result != VK_SUCCESS) {
1511 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001512 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001513 }
John Reck97678d42022-08-23 11:24:51 -04001514 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001515 }
John Reck97678d42022-08-23 11:24:51 -04001516 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001517
1518 bool createProtectedSwapchain = false;
1519 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1520 createProtectedSwapchain = true;
1521 native_usage |= BufferUsage::PROTECTED;
1522 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001523 err = native_window_set_usage(window, native_usage);
1524 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001525 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001526 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001527 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001528
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001529 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001530 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1531 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001532 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1533 strerror(-err), err);
1534 return VK_ERROR_SURFACE_LOST_KHR;
1535 }
1536
Jesse Halld7b994a2015-09-07 14:17:37 -07001537 // -- Allocate our Swapchain object --
1538 // After this point, we must deallocate the swapchain on error.
1539
Jesse Hall1f91d392015-12-11 16:28:44 -08001540 void* mem = allocator->pfnAllocation(allocator->pUserData,
1541 sizeof(Swapchain), alignof(Swapchain),
1542 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001543 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001544 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001545 Swapchain* swapchain = new (mem)
1546 Swapchain(surface, num_images, create_info->presentMode,
1547 TranslateVulkanToNativeTransform(create_info->preTransform));
Ian Elliottac40c1e2022-12-21 23:16:21 +00001548 // -- Dequeue all buffers and create a VkImage for each --
1549 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001550
Chris Forbesb56287a2017-01-12 14:28:58 +13001551 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1552#pragma clang diagnostic push
1553#pragma clang diagnostic ignored "-Wold-style-cast"
1554 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1555#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001556 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001557 .usage = swapchain_image_usage,
1558 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001559 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001560#pragma clang diagnostic push
1561#pragma clang diagnostic ignored "-Wold-style-cast"
1562 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1563#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001564 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001565 };
1566 VkImageCreateInfo image_create = {
1567 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Ian Elliottac40c1e2022-12-21 23:16:21 +00001568 .pNext = &image_native_buffer,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001569 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001570 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001571 .format = create_info->imageFormat,
Ian Elliottac40c1e2022-12-21 23:16:21 +00001572 .extent = {0, 0, 1},
Jesse Halld7b994a2015-09-07 14:17:37 -07001573 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001574 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001575 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001576 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001577 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001578 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001579 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001580 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1581 };
1582
Ian Elliottac40c1e2022-12-21 23:16:21 +00001583 for (uint32_t i = 0; i < num_images; i++) {
1584 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001585
Ian Elliottac40c1e2022-12-21 23:16:21 +00001586 ANativeWindowBuffer* buffer;
1587 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1588 if (err != android::OK) {
1589 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1590 switch (-err) {
1591 case ENOMEM:
1592 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1593 break;
1594 default:
1595 result = VK_ERROR_SURFACE_LOST_KHR;
1596 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001597 }
Ian Elliottac40c1e2022-12-21 23:16:21 +00001598 break;
Jesse Halld7b994a2015-09-07 14:17:37 -07001599 }
Ian Elliottac40c1e2022-12-21 23:16:21 +00001600 img.buffer = buffer;
1601 img.dequeued = true;
Jesse Halld7b994a2015-09-07 14:17:37 -07001602
Ian Elliottac40c1e2022-12-21 23:16:21 +00001603 image_create.extent =
1604 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
1605 static_cast<uint32_t>(img.buffer->height),
1606 1};
1607 image_native_buffer.handle = img.buffer->handle;
1608 image_native_buffer.stride = img.buffer->stride;
1609 image_native_buffer.format = img.buffer->format;
1610 image_native_buffer.usage = int(img.buffer->usage);
1611 android_convertGralloc0To1Usage(int(img.buffer->usage),
1612 &image_native_buffer.usage2.producer,
1613 &image_native_buffer.usage2.consumer);
1614 image_native_buffer.usage3 = img.buffer->usage;
Jesse Halld7b994a2015-09-07 14:17:37 -07001615
Ian Elliottac40c1e2022-12-21 23:16:21 +00001616 ATRACE_BEGIN("CreateImage");
1617 result =
1618 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1619 ATRACE_END();
1620 if (result != VK_SUCCESS) {
1621 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1622 break;
Jesse Halld7b994a2015-09-07 14:17:37 -07001623 }
Ian Elliottac40c1e2022-12-21 23:16:21 +00001624 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001625
Ian Elliottac40c1e2022-12-21 23:16:21 +00001626 // -- Cancel all buffers, returning them to the queue --
1627 // If an error occurred before, also destroy the VkImage and release the
1628 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1629 for (uint32_t i = 0; i < num_images; i++) {
1630 Swapchain::Image& img = swapchain->images[i];
1631 if (img.dequeued) {
1632 if (!swapchain->shared) {
1633 window->cancelBuffer(window, img.buffer.get(),
1634 img.dequeue_fence);
1635 img.dequeue_fence = -1;
1636 img.dequeued = false;
Chris Forbese0ced032017-03-30 19:44:15 +13001637 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001638 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001639 }
1640
1641 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001642 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1643 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001644 return result;
1645 }
1646
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001647 if (transform_hint != swapchain->pre_transform) {
1648 // Log that the app is not doing pre-rotation.
1649 android::GraphicsEnv::getInstance().setTargetStats(
1650 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1651 }
1652
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001653 // Set stats for creating a Vulkan swapchain
1654 android::GraphicsEnv::getInstance().setTargetStats(
1655 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1656
Jesse Halldc225072016-05-30 22:40:14 -07001657 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1658 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001659 return VK_SUCCESS;
1660}
1661
Jesse Halle1b12782015-11-30 11:27:32 -08001662VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001663void DestroySwapchainKHR(VkDevice device,
1664 VkSwapchainKHR swapchain_handle,
1665 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001666 ATRACE_CALL();
1667
Yiwei Zhang533cea92019-06-03 18:43:24 -07001668 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001669}
1670
Jesse Halle1b12782015-11-30 11:27:32 -08001671VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001672VkResult GetSwapchainImagesKHR(VkDevice,
1673 VkSwapchainKHR swapchain_handle,
1674 uint32_t* count,
1675 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001676 ATRACE_CALL();
1677
Jesse Halld7b994a2015-09-07 14:17:37 -07001678 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001679 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1680 "getting images for non-active swapchain 0x%" PRIx64
1681 "; only dequeued image handles are valid",
1682 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001683 VkResult result = VK_SUCCESS;
1684 if (images) {
1685 uint32_t n = swapchain.num_images;
1686 if (*count < swapchain.num_images) {
1687 n = *count;
1688 result = VK_INCOMPLETE;
1689 }
1690 for (uint32_t i = 0; i < n; i++)
1691 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001692 *count = n;
1693 } else {
1694 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001695 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001696 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001697}
1698
Jesse Halle1b12782015-11-30 11:27:32 -08001699VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001700VkResult AcquireNextImageKHR(VkDevice device,
1701 VkSwapchainKHR swapchain_handle,
1702 uint64_t timeout,
1703 VkSemaphore semaphore,
1704 VkFence vk_fence,
1705 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001706 ATRACE_CALL();
1707
Jesse Halld7b994a2015-09-07 14:17:37 -07001708 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001709 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001710 VkResult result;
1711 int err;
1712
Jesse Halldc225072016-05-30 22:40:14 -07001713 if (swapchain.surface.swapchain_handle != swapchain_handle)
1714 return VK_ERROR_OUT_OF_DATE_KHR;
1715
Chris Forbesc88409c2017-03-30 19:47:37 +13001716 if (swapchain.shared) {
1717 // In shared mode, we keep the buffer dequeued all the time, so we don't
1718 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1719 // the semaphore and fence passed to us will be signalled.
1720 *image_index = 0;
1721 result = GetData(device).driver.AcquireImageANDROID(
1722 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1723 return result;
1724 }
1725
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001726 const nsecs_t acquire_next_image_timeout =
1727 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1728 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1729 // Cache the timeout to avoid the duplicate binder cost.
1730 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1731 acquire_next_image_timeout);
1732 if (err != android::OK) {
1733 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1734 strerror(-err), err);
1735 return VK_ERROR_SURFACE_LOST_KHR;
1736 }
1737 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1738 }
1739
Jesse Halld7b994a2015-09-07 14:17:37 -07001740 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001741 int fence_fd;
1742 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001743 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001744 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1745 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1746 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001747 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001748 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001749 }
1750
1751 uint32_t idx;
1752 for (idx = 0; idx < swapchain.num_images; idx++) {
1753 if (swapchain.images[idx].buffer.get() == buffer) {
1754 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001755 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001756 break;
1757 }
1758 }
1759 if (idx == swapchain.num_images) {
1760 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001761 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001762 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001763 }
1764
1765 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001766 if (fence_fd != -1) {
1767 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001768 if (fence_clone == -1) {
1769 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1770 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001771 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001772 }
1773 }
1774
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001775 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001776 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001777 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001778 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1779 // even if the call fails. We could close it ourselves on failure, but
1780 // that would create a race condition if the driver closes it on a
1781 // failure path: some other thread might create an fd with the same
1782 // number between the time the driver closes it and the time we close
1783 // it. We must assume one of: the driver *always* closes it even on
1784 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001785 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001786 swapchain.images[idx].dequeued = false;
1787 swapchain.images[idx].dequeue_fence = -1;
1788 return result;
1789 }
1790
1791 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001792 return VK_SUCCESS;
1793}
1794
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001795VKAPI_ATTR
1796VkResult AcquireNextImage2KHR(VkDevice device,
1797 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1798 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001799 ATRACE_CALL();
1800
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001801 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1802 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1803 pAcquireInfo->fence, pImageIndex);
1804}
1805
Jesse Halldc225072016-05-30 22:40:14 -07001806static VkResult WorstPresentResult(VkResult a, VkResult b) {
1807 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1808 // (in spec version 1.0.14).
1809 static const VkResult kWorstToBest[] = {
1810 VK_ERROR_DEVICE_LOST,
1811 VK_ERROR_SURFACE_LOST_KHR,
1812 VK_ERROR_OUT_OF_DATE_KHR,
1813 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1814 VK_ERROR_OUT_OF_HOST_MEMORY,
1815 VK_SUBOPTIMAL_KHR,
1816 };
1817 for (auto result : kWorstToBest) {
1818 if (a == result || b == result)
1819 return result;
1820 }
1821 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1822 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1823 return a != VK_SUCCESS ? a : b;
1824}
1825
Chris Forbes4cd01fb2022-10-19 11:35:16 +13001826// KHR_incremental_present aspect of QueuePresentKHR
1827static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
1828 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
1829 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
1830 auto const& rect = pRegion->pRectangles[i];
1831 if (rect.layer > 0) {
1832 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
1833 rect.layer);
1834 }
1835
1836 rects[i].left = rect.offset.x;
1837 rects[i].bottom = rect.offset.y;
1838 rects[i].right = rect.offset.x + rect.extent.width;
1839 rects[i].top = rect.offset.y + rect.extent.height;
1840 }
1841 native_window_set_surface_damage(window, rects.data(), rects.size());
1842}
1843
1844// GOOGLE_display_timing aspect of QueuePresentKHR
1845static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
1846 ANativeWindow *window = swapchain.surface.window.get();
1847
1848 // We don't know whether the app will actually use GOOGLE_display_timing
1849 // with a particular swapchain until QueuePresent; enable it on the BQ
1850 // now if needed
1851 if (!swapchain.frame_timestamps_enabled) {
1852 ALOGV("Calling native_window_enable_frame_timestamps(true)");
1853 native_window_enable_frame_timestamps(window, true);
1854 swapchain.frame_timestamps_enabled = true;
1855 }
1856
1857 // Record the nativeFrameId so it can be later correlated to
1858 // this present.
1859 uint64_t nativeFrameId = 0;
1860 int err = native_window_get_next_frame_id(
1861 window, &nativeFrameId);
1862 if (err != android::OK) {
1863 ALOGE("Failed to get next native frame ID.");
1864 }
1865
1866 // Add a new timing record with the user's presentID and
1867 // the nativeFrameId.
1868 swapchain.timing.emplace_back(pTime, nativeFrameId);
1869 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
1870 swapchain.timing.erase(
1871 swapchain.timing.begin(),
1872 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
1873 }
1874 if (pTime->desiredPresentTime) {
1875 ALOGV(
1876 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
1877 pTime->desiredPresentTime);
1878 native_window_set_buffers_timestamp(
1879 window,
1880 static_cast<int64_t>(pTime->desiredPresentTime));
1881 }
1882}
1883
1884static VkResult PresentOneSwapchain(
1885 VkQueue queue,
1886 Swapchain& swapchain,
1887 uint32_t imageIndex,
1888 const VkPresentRegionKHR *pRegion,
1889 const VkPresentTimeGOOGLE *pTime,
1890 uint32_t waitSemaphoreCount,
1891 const VkSemaphore *pWaitSemaphores) {
1892
1893 VkDevice device = GetData(queue).driver_device;
1894 const auto& dispatch = GetData(queue).driver;
1895
1896 Swapchain::Image& img = swapchain.images[imageIndex];
1897 VkResult swapchain_result = VK_SUCCESS;
1898 VkResult result;
1899 int err;
1900
1901 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
1902 // wait semaphores, so this doesn't actually work for the multiple swapchain
1903 // case.
1904 int fence = -1;
1905 result = dispatch.QueueSignalReleaseImageANDROID(
1906 queue, waitSemaphoreCount,
1907 pWaitSemaphores, img.image, &fence);
1908 if (result != VK_SUCCESS) {
1909 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
1910 swapchain_result = result;
1911 }
1912 if (img.release_fence >= 0)
1913 close(img.release_fence);
1914 img.release_fence = fence < 0 ? -1 : dup(fence);
1915
1916 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
1917 ANativeWindow* window = swapchain.surface.window.get();
1918 if (swapchain_result == VK_SUCCESS) {
1919
1920 if (pRegion) {
1921 SetSwapchainSurfaceDamage(window, pRegion);
1922 }
1923 if (pTime) {
1924 SetSwapchainFrameTimestamp(swapchain, pTime);
1925 }
1926
1927 err = window->queueBuffer(window, img.buffer.get(), fence);
1928 // queueBuffer always closes fence, even on error
1929 if (err != android::OK) {
1930 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1931 swapchain_result = WorstPresentResult(
1932 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
1933 } else {
1934 if (img.dequeue_fence >= 0) {
1935 close(img.dequeue_fence);
1936 img.dequeue_fence = -1;
1937 }
1938 img.dequeued = false;
1939 }
1940
1941 // If the swapchain is in shared mode, immediately dequeue the
1942 // buffer so it can be presented again without an intervening
1943 // call to AcquireNextImageKHR. We expect to get the same buffer
1944 // back from every call to dequeueBuffer in this mode.
1945 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
1946 ANativeWindowBuffer* buffer;
1947 int fence_fd;
1948 err = window->dequeueBuffer(window, &buffer, &fence_fd);
1949 if (err != android::OK) {
1950 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1951 swapchain_result = WorstPresentResult(swapchain_result,
1952 VK_ERROR_SURFACE_LOST_KHR);
1953 } else if (img.buffer != buffer) {
1954 ALOGE("got wrong image back for shared swapchain");
1955 swapchain_result = WorstPresentResult(swapchain_result,
1956 VK_ERROR_SURFACE_LOST_KHR);
1957 } else {
1958 img.dequeue_fence = fence_fd;
1959 img.dequeued = true;
1960 }
1961 }
1962 }
1963 if (swapchain_result != VK_SUCCESS) {
1964 OrphanSwapchain(device, &swapchain);
1965 }
1966 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
1967 // and only when the window's transform/rotation changes. Extent
1968 // changes will not cause VK_SUBOPTIMAL_KHR because of the
1969 // application issues that were caused when the following transform
1970 // change was added.
1971 int window_transform_hint;
1972 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
1973 &window_transform_hint);
1974 if (err != android::OK) {
1975 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1976 strerror(-err), err);
1977 swapchain_result = WorstPresentResult(
1978 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
1979 }
1980 if (swapchain.pre_transform != window_transform_hint) {
1981 swapchain_result =
1982 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
1983 }
1984 } else {
1985 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
1986 img, true);
1987 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
1988 }
1989
1990 return swapchain_result;
1991}
1992
Jesse Halle1b12782015-11-30 11:27:32 -08001993VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001994VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001995 ATRACE_CALL();
1996
Jesse Halld7b994a2015-09-07 14:17:37 -07001997 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1998 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1999 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002000
Jesse Halld7b994a2015-09-07 14:17:37 -07002001 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002002
Ian Elliottcb351132016-12-13 10:30:40 -07002003 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002004 const VkPresentRegionsKHR* present_regions = nullptr;
2005 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002006 const VkPresentRegionsKHR* next =
2007 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2008 while (next) {
2009 switch (next->sType) {
2010 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2011 present_regions = next;
2012 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002013 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002014 present_times =
2015 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2016 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002017 default:
2018 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2019 next->sType);
2020 break;
2021 }
2022 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2023 }
2024 ALOGV_IF(
2025 present_regions &&
2026 present_regions->swapchainCount != present_info->swapchainCount,
2027 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002028 ALOGV_IF(present_times &&
2029 present_times->swapchainCount != present_info->swapchainCount,
2030 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2031 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -07002032 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002033 (present_regions) ? present_regions->pRegions : nullptr;
2034 const VkPresentTimeGOOGLE* times =
2035 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002036
Jesse Halld7b994a2015-09-07 14:17:37 -07002037 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2038 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002039 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002040
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002041 VkResult swapchain_result = PresentOneSwapchain(
2042 queue,
2043 swapchain,
2044 present_info->pImageIndices[sc],
2045 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2046 times ? &times[sc] : nullptr,
2047 present_info->waitSemaphoreCount,
2048 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002049
Jesse Halla9e57032015-11-30 01:03:10 -08002050 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002051 present_info->pResults[sc] = swapchain_result;
2052
2053 if (swapchain_result != final_result)
2054 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002055 }
2056
2057 return final_result;
2058}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002059
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002060VKAPI_ATTR
2061VkResult GetRefreshCycleDurationGOOGLE(
2062 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002063 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002064 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002065 ATRACE_CALL();
2066
Ian Elliott62c48c92017-01-20 13:13:20 -07002067 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002068 VkResult result = VK_SUCCESS;
2069
Ian Elliott3568bfe2019-05-03 15:54:46 -06002070 pDisplayTimingProperties->refreshDuration = swapchain.get_refresh_duration();
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002071
2072 return result;
2073}
2074
2075VKAPI_ATTR
2076VkResult GetPastPresentationTimingGOOGLE(
2077 VkDevice,
2078 VkSwapchainKHR swapchain_handle,
2079 uint32_t* count,
2080 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002081 ATRACE_CALL();
2082
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002083 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002084 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2085 return VK_ERROR_OUT_OF_DATE_KHR;
2086 }
2087
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002088 ANativeWindow* window = swapchain.surface.window.get();
2089 VkResult result = VK_SUCCESS;
2090
2091 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002092 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002093 native_window_enable_frame_timestamps(window, true);
2094 swapchain.frame_timestamps_enabled = true;
2095 }
2096
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002097 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002098 // Get the latest ready timing count before copying, since the copied
2099 // timing info will be erased in copy_ready_timings function.
2100 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002101 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002102 // Check the *count here against the recorded ready timing count, since
2103 // *count can be overwritten per spec describes.
2104 if (*count < n) {
2105 result = VK_INCOMPLETE;
2106 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002107 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002108 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002109 }
2110
2111 return result;
2112}
2113
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002114VKAPI_ATTR
2115VkResult GetSwapchainStatusKHR(
2116 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002117 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002118 ATRACE_CALL();
2119
Chris Forbes4e18ba82017-01-20 12:50:17 +13002120 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002121 VkResult result = VK_SUCCESS;
2122
Chris Forbes4e18ba82017-01-20 12:50:17 +13002123 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2124 return VK_ERROR_OUT_OF_DATE_KHR;
2125 }
2126
Yiwei Zhanga885c062019-10-24 12:07:57 -07002127 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002128
2129 return result;
2130}
2131
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002132VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002133 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002134 uint32_t swapchainCount,
2135 const VkSwapchainKHR* pSwapchains,
2136 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002137 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002138
2139 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2140 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2141 if (!swapchain)
2142 continue;
2143
2144 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2145
2146 ANativeWindow* window = swapchain->surface.window.get();
2147
2148 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2149 const android_smpte2086_metadata smpteMetdata = {
2150 {vulkanMetadata.displayPrimaryRed.x,
2151 vulkanMetadata.displayPrimaryRed.y},
2152 {vulkanMetadata.displayPrimaryGreen.x,
2153 vulkanMetadata.displayPrimaryGreen.y},
2154 {vulkanMetadata.displayPrimaryBlue.x,
2155 vulkanMetadata.displayPrimaryBlue.y},
2156 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2157 vulkanMetadata.maxLuminance,
2158 vulkanMetadata.minLuminance};
2159 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2160
2161 const android_cta861_3_metadata cta8613Metadata = {
2162 vulkanMetadata.maxContentLightLevel,
2163 vulkanMetadata.maxFrameAverageLightLevel};
2164 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2165 }
2166
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002167 return;
2168}
2169
Yiwei Zhang0f475222019-04-11 19:38:00 -07002170static void InterceptBindImageMemory2(
2171 uint32_t bind_info_count,
2172 const VkBindImageMemoryInfo* bind_infos,
2173 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2174 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2175 out_native_buffers->clear();
2176 out_bind_infos->clear();
2177
2178 if (!bind_info_count)
2179 return;
2180
2181 std::unordered_set<uint32_t> intercepted_indexes;
2182
2183 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2184 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2185 bind_infos[idx].pNext);
2186 while (info &&
2187 info->sType !=
2188 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2189 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2190 info->pNext);
2191 }
2192
2193 if (!info)
2194 continue;
2195
2196 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2197 "swapchain handle must not be NULL");
2198 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2199 ALOG_ASSERT(
2200 info->imageIndex < swapchain->num_images,
2201 "imageIndex must be less than the number of images in swapchain");
2202
2203 ANativeWindowBuffer* buffer =
2204 swapchain->images[info->imageIndex].buffer.get();
2205 VkNativeBufferANDROID native_buffer = {
2206#pragma clang diagnostic push
2207#pragma clang diagnostic ignored "-Wold-style-cast"
2208 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2209#pragma clang diagnostic pop
2210 .pNext = bind_infos[idx].pNext,
2211 .handle = buffer->handle,
2212 .stride = buffer->stride,
2213 .format = buffer->format,
2214 .usage = int(buffer->usage),
2215 };
2216 // Reserve enough space to avoid letting re-allocation invalidate the
2217 // addresses of the elements inside.
2218 out_native_buffers->reserve(bind_info_count);
2219 out_native_buffers->emplace_back(native_buffer);
2220
2221 // Reserve the space now since we know how much is needed now.
2222 out_bind_infos->reserve(bind_info_count);
2223 out_bind_infos->emplace_back(bind_infos[idx]);
2224 out_bind_infos->back().pNext = &out_native_buffers->back();
2225
2226 intercepted_indexes.insert(idx);
2227 }
2228
2229 if (intercepted_indexes.empty())
2230 return;
2231
2232 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2233 if (intercepted_indexes.count(idx))
2234 continue;
2235 out_bind_infos->emplace_back(bind_infos[idx]);
2236 }
2237}
2238
Yiwei Zhang23143102019-04-10 18:24:05 -07002239VKAPI_ATTR
2240VkResult BindImageMemory2(VkDevice device,
2241 uint32_t bindInfoCount,
2242 const VkBindImageMemoryInfo* pBindInfos) {
2243 ATRACE_CALL();
2244
Yiwei Zhang0f475222019-04-11 19:38:00 -07002245 // out_native_buffers is for maintaining the lifecycle of the constructed
2246 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2247 std::vector<VkNativeBufferANDROID> out_native_buffers;
2248 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2249 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2250 &out_bind_infos);
2251 return GetData(device).driver.BindImageMemory2(
2252 device, bindInfoCount,
2253 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002254}
2255
2256VKAPI_ATTR
2257VkResult BindImageMemory2KHR(VkDevice device,
2258 uint32_t bindInfoCount,
2259 const VkBindImageMemoryInfo* pBindInfos) {
2260 ATRACE_CALL();
2261
Yiwei Zhang0f475222019-04-11 19:38:00 -07002262 std::vector<VkNativeBufferANDROID> out_native_buffers;
2263 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2264 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2265 &out_bind_infos);
2266 return GetData(device).driver.BindImageMemory2KHR(
2267 device, bindInfoCount,
2268 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002269}
2270
Chia-I Wu62262232016-03-26 07:06:44 +08002271} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002272} // namespace vulkan