blob: 0dac6ad1aa0d887c9a97714da6fdca0b75456945 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Yiwei Zhang0f475222019-04-11 19:38:00 -070019#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070020#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070021#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040022#include <hardware/gralloc.h>
23#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070025#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070026#include <system/window.h>
27#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050028#include <ui/DebugUtils.h>
29#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080030#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080031#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080032#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070033
34#include <algorithm>
35#include <unordered_set>
36#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Chia-I Wu4a6a9162016-03-26 07:17:34 +080038#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Daniel Kochf25f5bb2017-10-05 00:26:58 -040040using android::hardware::graphics::common::V1_0::BufferUsage;
41
Chia-I Wu62262232016-03-26 07:06:44 +080042namespace vulkan {
43namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070044
Jesse Halld7b994a2015-09-07 14:17:37 -070045namespace {
46
John Reck97678d42022-08-23 11:24:51 -040047static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
48 uint64_t consumerUsage) {
49 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
50 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
51 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
52 "bits to match");
53 uint64_t merged = producerUsage | consumerUsage;
54 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
55 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
56 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
57 merged |= BufferUsage::CPU_READ_OFTEN;
58 }
59 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
60 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
61 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
62 merged |= BufferUsage::CPU_WRITE_OFTEN;
63 }
64 return merged;
65}
66
Jesse Hall55bc0972016-02-23 16:43:29 -080067const VkSurfaceTransformFlagsKHR kSupportedTransforms =
68 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
69 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
70 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
71 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
73 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080076 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
77
78VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
79 // Native and Vulkan transforms are isomorphic, but are represented
80 // differently. Vulkan transforms are built up of an optional horizontal
81 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
82 // transforms are built up from a horizontal flip, vertical flip, and
83 // 90-degree rotation, all optional but always in that order.
84
Jesse Hall55bc0972016-02-23 16:43:29 -080085 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070086 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080087 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070088 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
89 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
90 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
91 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
92 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080093 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070094 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080095 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070096 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
97 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
98 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
99 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
100 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800101 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
103 default:
104 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
105 }
106}
107
Yiwei Zhang70a21962019-05-31 17:26:52 -0700108int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
109 switch (transform) {
110 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
111 return NATIVE_WINDOW_TRANSFORM_ROT_90;
112 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
113 return NATIVE_WINDOW_TRANSFORM_ROT_180;
114 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_270;
116 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
118 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
120 NATIVE_WINDOW_TRANSFORM_ROT_90;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
123 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
124 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
125 NATIVE_WINDOW_TRANSFORM_ROT_90;
126 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
127 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
128 default:
129 return 0;
130 }
131}
132
Jesse Hall178b6962016-02-24 15:39:50 -0800133int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
134 switch (transform) {
135 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
136 return NATIVE_WINDOW_TRANSFORM_ROT_270;
137 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
138 return NATIVE_WINDOW_TRANSFORM_ROT_180;
139 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700141 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
143 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
145 NATIVE_WINDOW_TRANSFORM_ROT_90;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
148 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
149 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
150 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800151 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
152 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
153 default:
154 return 0;
155 }
156}
157
Ian Elliott8a977262017-01-19 09:05:58 -0700158class TimingInfo {
159 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800160 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700161 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800162 native_frame_id_(nativeFrameId) {}
163 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700164 return (timestamp_desired_present_time_ !=
165 NATIVE_WINDOW_TIMESTAMP_PENDING &&
166 timestamp_actual_present_time_ !=
167 NATIVE_WINDOW_TIMESTAMP_PENDING &&
168 timestamp_render_complete_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_composition_latch_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700172 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700173 void calculate(int64_t rdur) {
174 bool anyTimestampInvalid =
175 (timestamp_actual_present_time_ ==
176 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
177 (timestamp_render_complete_time_ ==
178 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
179 (timestamp_composition_latch_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID);
181 if (anyTimestampInvalid) {
182 ALOGE("Unexpectedly received invalid timestamp.");
183 vals_.actualPresentTime = 0;
184 vals_.earliestPresentTime = 0;
185 vals_.presentMargin = 0;
186 return;
187 }
188
189 vals_.actualPresentTime =
190 static_cast<uint64_t>(timestamp_actual_present_time_);
191 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700192 timestamp_render_complete_time_);
193 // Calculate vals_.earliestPresentTime, and potentially adjust
194 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
195 // is vals_.actualPresentTime. If we can subtract rdur (the duration
196 // of a refresh cycle) from vals_.earliestPresentTime (and also from
197 // vals_.presentMargin) and still leave a positive margin, then we can
198 // report to the application that it could have presented earlier than
199 // it did (per the extension specification). If for some reason, we
200 // can do this subtraction repeatedly, we do, since
201 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700202 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700203 while ((margin > rdur) &&
204 ((early_time - rdur) > timestamp_composition_latch_time_)) {
205 early_time -= rdur;
206 margin -= rdur;
207 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700208 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
209 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700210 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800211 void get_values(VkPastPresentationTimingGOOGLE* values) const {
212 *values = vals_;
213 }
Ian Elliott8a977262017-01-19 09:05:58 -0700214
215 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800216 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700217
Brian Anderson1049d1d2016-12-16 17:25:57 -0800218 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700219 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
220 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
221 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
222 int64_t timestamp_composition_latch_time_
223 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700224};
225
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800227 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700228 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700229 uint64_t consumer_usage;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230};
231
232VkSurfaceKHR HandleFromSurface(Surface* surface) {
233 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
234}
235
236Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800237 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800238}
239
Ian Elliott8a977262017-01-19 09:05:58 -0700240// Maximum number of TimingInfo structs to keep per swapchain:
241enum { MAX_TIMING_INFOS = 10 };
242// Minimum number of frames to look for in the past (so we don't cause
243// syncronous requests to Surface Flinger):
244enum { MIN_NUM_FRAMES_AGO = 5 };
245
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300246bool IsSharedPresentMode(VkPresentModeKHR mode) {
247 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
248 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
249}
250
Jesse Hall1356b0d2015-11-23 17:24:58 -0800251struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700252 Swapchain(Surface& surface_,
253 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700254 VkPresentModeKHR present_mode,
255 int pre_transform_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700256 : surface(surface_),
257 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700258 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700259 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300260 frame_timestamps_enabled(false),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800261 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300262 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700263 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700264 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700265 window,
Brian Andersondc96fdf2017-03-20 16:54:25 -0700266 &refresh_duration);
Ian Elliott8a977262017-01-19 09:05:58 -0700267 }
Ian Elliott3568bfe2019-05-03 15:54:46 -0600268 uint64_t get_refresh_duration()
269 {
270 ANativeWindow* window = surface.window.get();
271 native_window_get_refresh_cycle_duration(
272 window,
273 &refresh_duration);
274 return static_cast<uint64_t>(refresh_duration);
275
276 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800277
278 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700279 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700280 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700281 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700282 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700283 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800284 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300285 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700286
287 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700288 Image()
289 : image(VK_NULL_HANDLE),
290 dequeue_fence(-1),
291 release_fence(-1),
292 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700293 VkImage image;
Chris Forbes08c7bb12022-12-09 08:10:18 +1300294 // If the image is bound to memory, an sp to the underlying gralloc buffer.
295 // Otherwise, nullptr; the image will be bound to memory as part of
296 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800297 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700298 // The fence is only valid when the buffer is dequeued, and should be
299 // -1 any other time. When valid, we own the fd, and must ensure it is
300 // closed: either by closing it explicitly when queueing the buffer,
301 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
302 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700303 // This fence is a dup of the sync fd returned from the driver via
304 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
305 // ensure it is closed upon re-presenting or releasing the image.
306 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700307 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800308 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700309
Yiwei Zhang5e862202019-06-21 14:59:16 -0700310 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700311};
312
313VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
314 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
315}
316
317Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800318 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700319}
320
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700321static bool IsFencePending(int fd) {
322 if (fd < 0)
323 return false;
324
325 errno = 0;
326 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
327}
328
Jesse Halldc225072016-05-30 22:40:14 -0700329void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000330 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700331 ANativeWindow* window,
332 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700333 Swapchain::Image& image,
334 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700335 ATRACE_CALL();
336
Jesse Halldc225072016-05-30 22:40:14 -0700337 ALOG_ASSERT(release_fence == -1 || image.dequeued,
338 "ReleaseSwapchainImage: can't provide a release fence for "
339 "non-dequeued images");
340
341 if (image.dequeued) {
342 if (release_fence >= 0) {
343 // We get here from vkQueuePresentKHR. The application is
344 // responsible for creating an execution dependency chain from
345 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
346 // (release_fence), so we can drop the dequeue_fence here.
347 if (image.dequeue_fence >= 0)
348 close(image.dequeue_fence);
349 } else {
350 // We get here during swapchain destruction, or various serious
351 // error cases e.g. when we can't create the release_fence during
352 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
353 // have already signalled, since the swapchain images are supposed
354 // to be idle before the swapchain is destroyed. In error cases,
355 // there may be rendering in flight to the image, but since we
356 // weren't able to create a release_fence, waiting for the
357 // dequeue_fence is about the best we can do.
358 release_fence = image.dequeue_fence;
359 }
360 image.dequeue_fence = -1;
361
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000362 // It's invalid to call cancelBuffer on a shared buffer
363 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700364 window->cancelBuffer(window, image.buffer.get(), release_fence);
365 } else {
366 if (release_fence >= 0) {
367 sync_wait(release_fence, -1 /* forever */);
368 close(release_fence);
369 }
370 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700371 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700372 image.dequeued = false;
373 }
374
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700375 if (defer_if_pending && IsFencePending(image.release_fence))
376 return;
377
378 if (image.release_fence >= 0) {
379 close(image.release_fence);
380 image.release_fence = -1;
381 }
382
Jesse Halldc225072016-05-30 22:40:14 -0700383 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700384 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700385 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700386 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700387 image.image = VK_NULL_HANDLE;
388 }
389
390 image.buffer.clear();
391}
392
393void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
394 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
395 return;
Jesse Halldc225072016-05-30 22:40:14 -0700396 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000397 if (!swapchain->images[i].dequeued) {
398 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
399 swapchain->images[i], true);
400 }
Jesse Halldc225072016-05-30 22:40:14 -0700401 }
402 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700403 swapchain->timing.clear();
404}
405
406uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800407 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
408 return 0;
409 }
Ian Elliott8a977262017-01-19 09:05:58 -0700410
Brian Anderson1049d1d2016-12-16 17:25:57 -0800411 uint32_t num_ready = 0;
412 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
413 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700414 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800415 if (ti.ready()) {
416 // This TimingInfo is ready to be reported to the user. Add it
417 // to the num_ready.
418 num_ready++;
419 continue;
420 }
421 // This TimingInfo is not yet ready to be reported to the user,
422 // and so we should look for any available timestamps that
423 // might make it ready.
424 int64_t desired_present_time = 0;
425 int64_t render_complete_time = 0;
426 int64_t composition_latch_time = 0;
427 int64_t actual_present_time = 0;
428 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800429 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800430 swapchain.surface.window.get(), ti.native_frame_id_,
431 &desired_present_time, &render_complete_time,
432 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700433 nullptr, //&first_composition_start_time,
434 nullptr, //&last_composition_start_time,
435 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800436 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700437 nullptr, //&dequeue_ready_time,
438 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800439
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800440 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800441 continue;
442 }
443
444 // Record the timestamp(s) we received, and then see if this TimingInfo
445 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700446 ti.timestamp_desired_present_time_ = desired_present_time;
447 ti.timestamp_actual_present_time_ = actual_present_time;
448 ti.timestamp_render_complete_time_ = render_complete_time;
449 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800450
451 if (ti.ready()) {
452 // The TimingInfo has received enough timestamps, and should now
453 // use those timestamps to calculate the info that should be
454 // reported to the user:
455 ti.calculate(swapchain.refresh_duration);
456 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700457 }
458 }
459 return num_ready;
460}
461
Ian Elliott8a977262017-01-19 09:05:58 -0700462void copy_ready_timings(Swapchain& swapchain,
463 uint32_t* count,
464 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800465 if (swapchain.timing.empty()) {
466 *count = 0;
467 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700468 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800469
470 size_t last_ready = swapchain.timing.size() - 1;
471 while (!swapchain.timing[last_ready].ready()) {
472 if (last_ready == 0) {
473 *count = 0;
474 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700475 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800476 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700477 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800478
479 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700480 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800481 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
482 const TimingInfo& ti = swapchain.timing[i];
483 if (ti.ready()) {
484 ti.get_values(&timings[num_copied]);
485 num_copied++;
486 }
487 num_to_remove++;
488 }
489
490 // Discard old frames that aren't ready if newer frames are ready.
491 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700492 swapchain.timing.erase(swapchain.timing.begin(),
493 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800494
Ian Elliott8a977262017-01-19 09:05:58 -0700495 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700496}
497
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500498android::PixelFormat GetNativePixelFormat(VkFormat format) {
499 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700500 switch (format) {
501 case VK_FORMAT_R8G8B8A8_UNORM:
502 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500503 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700504 break;
505 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500506 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700507 break;
508 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500509 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700510 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800511 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500512 native_format = android::PIXEL_FORMAT_RGBA_1010102;
513 break;
514 case VK_FORMAT_R8_UNORM:
515 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700516 break;
517 default:
518 ALOGV("unsupported swapchain format %d", format);
519 break;
520 }
521 return native_format;
522}
523
524android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
525 switch (colorspace) {
526 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
527 return HAL_DATASPACE_V0_SRGB;
528 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
529 return HAL_DATASPACE_DISPLAY_P3;
530 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
531 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600532 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
533 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700534 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
535 return HAL_DATASPACE_DCI_P3_LINEAR;
536 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
537 return HAL_DATASPACE_DCI_P3;
538 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
539 return HAL_DATASPACE_V0_SRGB_LINEAR;
540 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
541 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600542 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
543 return HAL_DATASPACE_BT2020_LINEAR;
544 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700545 return static_cast<android_dataspace>(
546 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
547 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600548 case VK_COLOR_SPACE_DOLBYVISION_EXT:
549 return static_cast<android_dataspace>(
550 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
551 HAL_DATASPACE_RANGE_FULL);
552 case VK_COLOR_SPACE_HDR10_HLG_EXT:
553 return static_cast<android_dataspace>(
554 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
555 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700556 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
557 return static_cast<android_dataspace>(
558 HAL_DATASPACE_STANDARD_ADOBE_RGB |
559 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
560 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
561 return HAL_DATASPACE_ADOBE_RGB;
562
563 // Pass through is intended to allow app to provide data that is passed
564 // to the display system without modification.
565 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
566 return HAL_DATASPACE_ARBITRARY;
567
568 default:
569 // This indicates that we don't know about the
570 // dataspace specified and we should indicate that
571 // it's unsupported
572 return HAL_DATASPACE_UNKNOWN;
573 }
574}
575
Jesse Halld7b994a2015-09-07 14:17:37 -0700576} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700577
Jesse Halle1b12782015-11-30 11:27:32 -0800578VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800579VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800580 VkInstance instance,
581 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
582 const VkAllocationCallbacks* allocator,
583 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800584 ATRACE_CALL();
585
Jesse Hall1f91d392015-12-11 16:28:44 -0800586 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800587 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800588 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
589 alignof(Surface),
590 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800591 if (!mem)
592 return VK_ERROR_OUT_OF_HOST_MEMORY;
593 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700594
Chia-I Wue8e689f2016-04-18 08:21:31 +0800595 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700596 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700597 int err = native_window_get_consumer_usage(surface->window.get(),
598 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800599 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700600 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
601 strerror(-err), err);
602 surface->~Surface();
603 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700604 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700605 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700606
Yiwei Zhang6435b322018-05-08 11:12:17 -0700607 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800608 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800609 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800610 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
611 err);
612 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800613 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700614 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800615 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700616
Jesse Hall1356b0d2015-11-23 17:24:58 -0800617 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700618 return VK_SUCCESS;
619}
620
Jesse Halle1b12782015-11-30 11:27:32 -0800621VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800622void DestroySurfaceKHR(VkInstance instance,
623 VkSurfaceKHR surface_handle,
624 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800625 ATRACE_CALL();
626
Jesse Hall1356b0d2015-11-23 17:24:58 -0800627 Surface* surface = SurfaceFromHandle(surface_handle);
628 if (!surface)
629 return;
630 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700631 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700632 "destroyed VkSurfaceKHR 0x%" PRIx64
633 " has active VkSwapchainKHR 0x%" PRIx64,
634 reinterpret_cast<uint64_t>(surface_handle),
635 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800636 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800637 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800638 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800639 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800640}
641
Jesse Halle1b12782015-11-30 11:27:32 -0800642VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800643VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
644 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000645 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800646 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000647 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800648 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800649}
650
Jesse Halle1b12782015-11-30 11:27:32 -0800651VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800652VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600653 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800654 VkSurfaceKHR surface,
655 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800656 ATRACE_CALL();
657
Chris Forbes08c7bb12022-12-09 08:10:18 +1300658 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
659
660 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
661 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
662 nullptr,
663 surface
664 };
665
666 VkSurfaceCapabilities2KHR caps2 = {
667 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
668 nullptr,
669 {},
670 };
671
672 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
673 *capabilities = caps2.surfaceCapabilities;
674 return result;
675}
676
677// Does the call-twice and VK_INCOMPLETE handling for querying lists
678// of things, where we already have the full set built in a vector.
679template <typename T>
680VkResult CopyWithIncomplete(std::vector<T> const& things,
681 T* callerPtr, uint32_t* callerCount) {
682 VkResult result = VK_SUCCESS;
683 if (callerPtr) {
684 if (things.size() > *callerCount)
685 result = VK_INCOMPLETE;
686 *callerCount = std::min(uint32_t(things.size()), *callerCount);
687 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600688 } else {
Chris Forbes08c7bb12022-12-09 08:10:18 +1300689 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800690 }
Chris Forbes08c7bb12022-12-09 08:10:18 +1300691 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700692}
693
Jesse Halle1b12782015-11-30 11:27:32 -0800694VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700695VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
696 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800697 uint32_t* count,
698 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800699 ATRACE_CALL();
700
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700701 const InstanceData& instance_data = GetData(pdev);
702
Ian Elliott1ce053f2022-03-16 09:49:53 -0600703 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000704 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600705 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600706 if (surface_handle == VK_NULL_HANDLE) {
707 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
708 bool surfaceless_enabled =
709 instance_data.hook_extensions.test(surfaceless);
710 if (!surfaceless_enabled) {
711 return VK_ERROR_SURFACE_LOST_KHR;
712 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300713 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600714
715 // TODO(b/203826952): research proper value; temporarily use the
716 // values seen on Pixel
717 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
718 } else {
719 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600720 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700721 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700722
Charlie Lao324191f2019-12-13 11:03:16 -0800723 AHardwareBuffer_Desc desc = {};
724 desc.width = 1;
725 desc.height = 1;
726 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600727 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800728 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
729
730 // We must support R8G8B8A8
731 std::vector<VkSurfaceFormatKHR> all_formats = {
732 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000733 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000734 };
Charlie Lao324191f2019-12-13 11:03:16 -0800735
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000736 if (colorspace_ext) {
737 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800738 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
739 all_formats.emplace_back(VkSurfaceFormatKHR{
740 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
741 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000742 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800743 all_formats.emplace_back(VkSurfaceFormatKHR{
744 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
745 all_formats.emplace_back(VkSurfaceFormatKHR{
746 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
747 }
748
Ian Elliott1ce053f2022-03-16 09:49:53 -0600749 // NOTE: Any new formats that are added must be coordinated across different
750 // Android users. This includes the ANGLE team (a layered implementation of
751 // OpenGL-ES).
752
Charlie Lao324191f2019-12-13 11:03:16 -0800753 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
754 if (AHardwareBuffer_isSupported(&desc)) {
755 all_formats.emplace_back(VkSurfaceFormatKHR{
756 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800757 if (colorspace_ext) {
758 all_formats.emplace_back(
759 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
760 VK_COLOR_SPACE_PASS_THROUGH_EXT});
761 }
Charlie Lao324191f2019-12-13 11:03:16 -0800762 }
763
764 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
765 if (AHardwareBuffer_isSupported(&desc)) {
766 all_formats.emplace_back(VkSurfaceFormatKHR{
767 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800768 if (colorspace_ext) {
769 all_formats.emplace_back(
770 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
771 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800772 all_formats.emplace_back(
773 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
774 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
775 all_formats.emplace_back(
776 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
777 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
778 }
779 }
780
781 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
782 if (AHardwareBuffer_isSupported(&desc)) {
783 all_formats.emplace_back(
784 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
785 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800786 if (colorspace_ext) {
787 all_formats.emplace_back(
788 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
789 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800790 all_formats.emplace_back(
791 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
792 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
793 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700794 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700795
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500796 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
797 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800798 if (colorspace_ext) {
799 all_formats.emplace_back(VkSurfaceFormatKHR{
800 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
801 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500802 }
803
Ian Elliott6ba85d92022-02-18 16:44:58 -0700804 // NOTE: Any new formats that are added must be coordinated across different
805 // Android users. This includes the ANGLE team (a layered implementation of
806 // OpenGL-ES).
807
Chris Forbes08c7bb12022-12-09 08:10:18 +1300808 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700809}
810
Jesse Halle1b12782015-11-30 11:27:32 -0800811VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300812VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
813 VkPhysicalDevice physicalDevice,
814 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
815 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800816 ATRACE_CALL();
817
Chris Forbes08c7bb12022-12-09 08:10:18 +1300818 auto surface = pSurfaceInfo->surface;
819 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300820
Chris Forbes08c7bb12022-12-09 08:10:18 +1300821 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
822 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
823 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
824 switch (pNext->sType) {
825 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
826 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
827 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300828
Chris Forbes08c7bb12022-12-09 08:10:18 +1300829 default:
830 break;
831 }
832 }
833
834 int err;
835 int width, height;
836 int transform_hint;
837 int max_buffer_count;
838 if (surface == VK_NULL_HANDLE) {
839 const InstanceData& instance_data = GetData(physicalDevice);
840 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
841 bool surfaceless_enabled =
842 instance_data.hook_extensions.test(surfaceless);
843 if (!surfaceless_enabled) {
844 // It is an error to pass a surface==VK_NULL_HANDLE unless the
845 // VK_GOOGLE_surfaceless_query extension is enabled
846 return VK_ERROR_SURFACE_LOST_KHR;
847 }
848 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
849 // extension for this function is for
850 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
851 // four values cannot be known without a surface. Default values will
852 // be supplied anyway, but cannot be relied upon.
853 width = 0xFFFFFFFF;
854 height = 0xFFFFFFFF;
855 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
856 capabilities->minImageCount = 0xFFFFFFFF;
857 capabilities->maxImageCount = 0xFFFFFFFF;
858 } else {
859 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
860
861 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
862 if (err != android::OK) {
863 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
864 strerror(-err), err);
865 return VK_ERROR_SURFACE_LOST_KHR;
866 }
867 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
868 if (err != android::OK) {
869 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
870 strerror(-err), err);
871 return VK_ERROR_SURFACE_LOST_KHR;
872 }
873
874 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
875 &transform_hint);
876 if (err != android::OK) {
877 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
878 strerror(-err), err);
879 return VK_ERROR_SURFACE_LOST_KHR;
880 }
881
882 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
883 &max_buffer_count);
884 if (err != android::OK) {
885 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
886 strerror(-err), err);
887 return VK_ERROR_SURFACE_LOST_KHR;
888 }
889
890 if (pPresentMode && IsSharedPresentMode(pPresentMode->presentMode)) {
891 capabilities->minImageCount = 1;
892 capabilities->maxImageCount = 1;
893 } else if (pPresentMode && pPresentMode->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
894 // TODO: use undequeued buffer requirement for more precise bound
895 capabilities->minImageCount = std::min(max_buffer_count, 4);
896 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
897 } else {
898 // TODO: if we're able to, provide better bounds on the number of buffers
899 // for other modes as well.
900 capabilities->minImageCount = std::min(max_buffer_count, 3);
901 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
902 }
903 }
904
905 capabilities->currentExtent =
906 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
907
908 // TODO(http://b/134182502): Figure out what the max extent should be.
909 capabilities->minImageExtent = VkExtent2D{1, 1};
910 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
911
912 if (capabilities->maxImageExtent.height <
913 capabilities->currentExtent.height) {
914 capabilities->maxImageExtent.height =
915 capabilities->currentExtent.height;
916 }
917
918 if (capabilities->maxImageExtent.width <
919 capabilities->currentExtent.width) {
920 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
921 }
922
923 capabilities->maxImageArrayLayers = 1;
924
925 capabilities->supportedTransforms = kSupportedTransforms;
926 capabilities->currentTransform =
927 TranslateNativeToVulkanTransform(transform_hint);
928
929 // On Android, window composition is a WindowManager property, not something
930 // associated with the bufferqueue. It can't be changed from here.
931 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
932
933 capabilities->supportedUsageFlags =
934 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
935 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
936 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
937 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
938
939 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
940 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
941
942 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300943 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
944 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes08c7bb12022-12-09 08:10:18 +1300945 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300946 // Claim same set of usage flags are supported for
947 // shared present modes as for other modes.
948 shared_caps->sharedPresentSupportedUsageFlags =
949 pSurfaceCapabilities->surfaceCapabilities
950 .supportedUsageFlags;
951 } break;
952
Ian Elliottbb67b242022-03-16 09:52:28 -0600953 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
954 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes08c7bb12022-12-09 08:10:18 +1300955 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -0600956 protected_caps->supportsProtected = VK_TRUE;
957 } break;
958
Chris Forbes08c7bb12022-12-09 08:10:18 +1300959 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
960 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
961 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
962 // By default, Android stretches the buffer to fit the window,
963 // without preserving aspect ratio. Other modes are technically possible
964 // but consult with CoGS team before exposing them here!
965 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
966
967 // Since we always scale, we don't support any gravity.
968 scaling_caps->supportedPresentGravityX = 0;
969 scaling_caps->supportedPresentGravityY = 0;
970
971 // Scaled image limits are just the basic image limits
972 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
973 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
974 } break;
975
976 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
977 VkSurfacePresentModeCompatibilityEXT* mode_caps =
978 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
979
980 ALOG_ASSERT(pPresentMode,
981 "querying VkSurfacePresentModeCompatibilityEXT "
982 "requires VkSurfacePresentModeEXT to be provided");
983 std::vector<VkPresentModeKHR> compatibleModes;
984 compatibleModes.push_back(pPresentMode->presentMode);
985
986 switch (pPresentMode->presentMode) {
987 // Shared modes are both compatible with each other.
988 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
989 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
990 break;
991 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
992 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
993 break;
994 default:
995 // Other modes are only compatible with themselves.
996 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
997 break;
998 }
999
1000 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1001 // a larger query and there would be no way to determine exactly where it came from.
1002 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1003 &mode_caps->presentModeCount);
1004 } break;
1005
Chris Forbes06bc0092017-03-16 16:46:05 +13001006 default:
1007 // Ignore all other extension structs
1008 break;
1009 }
1010 }
1011
Chris Forbes08c7bb12022-12-09 08:10:18 +13001012 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001013}
1014
1015VKAPI_ATTR
1016VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1017 VkPhysicalDevice physicalDevice,
1018 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1019 uint32_t* pSurfaceFormatCount,
1020 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001021 ATRACE_CALL();
1022
Chris Forbes2452cf72017-03-16 16:30:17 +13001023 if (!pSurfaceFormats) {
1024 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1025 pSurfaceInfo->surface,
1026 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001027 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001028
Trevor David Black929e9cd2022-11-22 04:12:19 +00001029 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1030 // after the call.
1031 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1032 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1033 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1034 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001035
Trevor David Black929e9cd2022-11-22 04:12:19 +00001036 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1037 return result;
1038 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001039
Trevor David Black929e9cd2022-11-22 04:12:19 +00001040 const auto& driver = GetData(physicalDevice).driver;
1041
1042 // marshal results individually due to stride difference.
1043 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1044 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1045 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1046
1047 // Query the compression properties for the surface format
1048 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1049 while (pSurfaceFormat->pNext) {
1050 pSurfaceFormat =
1051 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1052 switch (pSurfaceFormat->sType) {
1053 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001054 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1055 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001056 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001057
1058 if (surfaceCompressionProps &&
1059 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1060 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1061 imageFormatInfo.sType =
1062 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1063 imageFormatInfo.format =
1064 pSurfaceFormats[i].surfaceFormat.format;
1065 imageFormatInfo.pNext = nullptr;
1066
1067 VkImageCompressionControlEXT compressionControl = {};
1068 compressionControl.sType =
1069 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1070 compressionControl.pNext = imageFormatInfo.pNext;
1071
1072 imageFormatInfo.pNext = &compressionControl;
1073
1074 VkImageCompressionPropertiesEXT compressionProps = {};
1075 compressionProps.sType =
1076 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1077 compressionProps.pNext = nullptr;
1078
1079 VkImageFormatProperties2KHR imageFormatProps = {};
1080 imageFormatProps.sType =
1081 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1082 imageFormatProps.pNext = &compressionProps;
1083
1084 VkResult compressionRes =
1085 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1086 physicalDevice, &imageFormatInfo,
1087 &imageFormatProps);
1088 if (compressionRes == VK_SUCCESS) {
1089 surfaceCompressionProps->imageCompressionFlags =
1090 compressionProps.imageCompressionFlags;
1091 surfaceCompressionProps
1092 ->imageCompressionFixedRateFlags =
1093 compressionProps.imageCompressionFixedRateFlags;
1094 } else {
1095 return compressionRes;
1096 }
1097 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001098 } break;
1099
1100 default:
1101 // Ignore all other extension structs
1102 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001103 }
1104 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001105 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001106
1107 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001108}
1109
1110VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001111VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001112 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001113 uint32_t* count,
1114 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001115 ATRACE_CALL();
1116
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001117 int err;
1118 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001119 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001120 if (surface == VK_NULL_HANDLE) {
1121 const InstanceData& instance_data = GetData(pdev);
1122 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1123 bool surfaceless_enabled =
1124 instance_data.hook_extensions.test(surfaceless);
1125 if (!surfaceless_enabled) {
1126 return VK_ERROR_SURFACE_LOST_KHR;
1127 }
1128 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1129 // extension for this function is for
1130 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1131 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1132 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001133 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001134 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1135 } else {
1136 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1137
1138 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1139 &query_value);
1140 if (err != android::OK || query_value < 0) {
1141 ALOGE(
1142 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1143 "value=%d",
1144 strerror(-err), err, query_value);
1145 return VK_ERROR_SURFACE_LOST_KHR;
1146 }
1147 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1148
1149 err =
1150 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1151 if (err != android::OK || query_value < 0) {
1152 ALOGE(
1153 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1154 strerror(-err), err, query_value);
1155 return VK_ERROR_SURFACE_LOST_KHR;
1156 }
1157 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1158
1159 if (min_undequeued_buffers + 1 < max_buffer_count)
1160 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1161 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1162 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001163
1164 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001165 QueryPresentationProperties(pdev, &present_properties);
1166 if (present_properties.sharedImage) {
1167 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1168 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001169 }
1170
Chris Forbes08c7bb12022-12-09 08:10:18 +13001171 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001172}
1173
Jesse Halle1b12782015-11-30 11:27:32 -08001174VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001175VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001176 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001177 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001178 ATRACE_CALL();
1179
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001180 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1181 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1182 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1183 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1184 pDeviceGroupPresentCapabilities->sType);
1185
1186 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1187 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1188
1189 // assume device group of size 1
1190 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1191 pDeviceGroupPresentCapabilities->modes =
1192 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1193
1194 return VK_SUCCESS;
1195}
1196
1197VKAPI_ATTR
1198VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001199 VkDevice,
1200 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001201 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001202 ATRACE_CALL();
1203
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001204 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1205 return VK_SUCCESS;
1206}
1207
1208VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001209VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001210 VkSurfaceKHR surface,
1211 uint32_t* pRectCount,
1212 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001213 ATRACE_CALL();
1214
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001215 if (!pRects) {
1216 *pRectCount = 1;
1217 } else {
1218 uint32_t count = std::min(*pRectCount, 1u);
1219 bool incomplete = *pRectCount < 1;
1220
1221 *pRectCount = count;
1222
1223 if (incomplete) {
1224 return VK_INCOMPLETE;
1225 }
1226
1227 int err;
1228 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1229
1230 int width = 0, height = 0;
1231 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001232 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001233 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1234 strerror(-err), err);
1235 }
1236 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001237 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001238 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1239 strerror(-err), err);
1240 }
1241
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001242 pRects[0].offset.x = 0;
1243 pRects[0].offset.y = 0;
1244 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1245 static_cast<uint32_t>(height)};
1246 }
1247 return VK_SUCCESS;
1248}
1249
Yiwei Zhang533cea92019-06-03 18:43:24 -07001250static void DestroySwapchainInternal(VkDevice device,
1251 VkSwapchainKHR swapchain_handle,
1252 const VkAllocationCallbacks* allocator) {
1253 ATRACE_CALL();
1254
1255 const auto& dispatch = GetData(device).driver;
1256 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1257 if (!swapchain) {
1258 return;
1259 }
1260
1261 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1262 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1263
1264 if (window && swapchain->frame_timestamps_enabled) {
1265 native_window_enable_frame_timestamps(window, false);
1266 }
1267
1268 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001269 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1270 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001271 }
1272
1273 if (active) {
1274 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1275 }
1276
1277 if (!allocator) {
1278 allocator = &GetData(device).allocator;
1279 }
1280
1281 swapchain->~Swapchain();
1282 allocator->pfnFree(allocator->pUserData, swapchain);
1283}
1284
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001285VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001286VkResult CreateSwapchainKHR(VkDevice device,
1287 const VkSwapchainCreateInfoKHR* create_info,
1288 const VkAllocationCallbacks* allocator,
1289 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001290 ATRACE_CALL();
1291
Jesse Halld7b994a2015-09-07 14:17:37 -07001292 int err;
1293 VkResult result = VK_SUCCESS;
1294
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001295 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1296 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1297 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1298 " oldSwapchain=0x%" PRIx64,
1299 reinterpret_cast<uint64_t>(create_info->surface),
1300 create_info->minImageCount, create_info->imageFormat,
1301 create_info->imageColorSpace, create_info->imageExtent.width,
1302 create_info->imageExtent.height, create_info->imageUsage,
1303 create_info->preTransform, create_info->presentMode,
1304 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1305
Jesse Hall1f91d392015-12-11 16:28:44 -08001306 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001307 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001308
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001309 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001310 GetNativePixelFormat(create_info->imageFormat);
1311 android_dataspace native_dataspace =
1312 GetNativeDataspace(create_info->imageColorSpace);
1313 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1314 ALOGE(
1315 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1316 "failed: Unsupported color space",
1317 create_info->imageColorSpace);
1318 return VK_ERROR_INITIALIZATION_FAILED;
1319 }
1320
Jesse Hall42a9eec2016-06-03 12:39:49 -07001321 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001322 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001323 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001324 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001325 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001326 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001327 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001328 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001329 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1330 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001331 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001332 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001333
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001334 Surface& surface = *SurfaceFromHandle(create_info->surface);
1335
Jesse Halldc225072016-05-30 22:40:14 -07001336 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001337 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001338 " because it already has active swapchain 0x%" PRIx64
1339 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1340 reinterpret_cast<uint64_t>(create_info->surface),
1341 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1342 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1343 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1344 }
1345 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1346 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1347
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001348 // -- Reset the native window --
1349 // The native window might have been used previously, and had its properties
1350 // changed from defaults. That will affect the answer we get for queries
1351 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1352 // attempt such queries.
1353
Jesse Halldc225072016-05-30 22:40:14 -07001354 // The native window only allows dequeueing all buffers before any have
1355 // been queued, since after that point at least one is assumed to be in
1356 // non-FREE state at any given time. Disconnecting and re-connecting
1357 // orphans the previous buffers, getting us back to the state where we can
1358 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001359 //
1360 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001361 ANativeWindow* window = surface.window.get();
1362 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1363 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001364 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001365 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1366 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001367 strerror(-err), err);
1368
Nicolas Capens147b7da2021-04-09 14:53:06 -04001369 err =
1370 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001371 if (err != android::OK) {
1372 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1373 strerror(-err), err);
1374 return VK_ERROR_SURFACE_LOST_KHR;
1375 }
1376
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301377 int swap_interval =
1378 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001379 err = window->setSwapInterval(window, swap_interval);
1380 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001381 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1382 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001383 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001384 }
1385
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001386 err = native_window_set_shared_buffer_mode(window, false);
1387 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001388 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1389 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001390 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001391 }
1392
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001393 err = native_window_set_auto_refresh(window, false);
1394 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001395 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1396 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001397 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001398 }
1399
Jesse Halld7b994a2015-09-07 14:17:37 -07001400 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001401
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001402 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001403
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001404 err = native_window_set_buffers_format(window, native_pixel_format);
1405 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001406 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1407 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001408 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001409 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001410
1411 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1412 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1413 err = native_window_set_buffers_data_space(window, native_dataspace);
1414 if (err != android::OK) {
1415 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1416 native_dataspace, strerror(-err), err);
1417 return VK_ERROR_SURFACE_LOST_KHR;
1418 }
Jesse Hall517274a2016-02-10 00:07:18 -08001419 }
1420
Jesse Hall3dd678a2016-01-08 21:52:01 -08001421 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001422 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001423 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001424 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001425 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1426 create_info->imageExtent.width, create_info->imageExtent.height,
1427 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001428 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001429 }
1430
Jesse Hall178b6962016-02-24 15:39:50 -08001431 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1432 // applied during rendering. native_window_set_transform() expects the
1433 // inverse: the transform the app is requesting that the compositor perform
1434 // during composition. With native windows, pre-transform works by rendering
1435 // with the same transform the compositor is applying (as in Vulkan), but
1436 // then requesting the inverse transform, so that when the compositor does
1437 // it's job the two transforms cancel each other out and the compositor ends
1438 // up applying an identity transform to the app's buffer.
1439 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001440 window, InvertTransformToNative(create_info->preTransform));
1441 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001442 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1443 InvertTransformToNative(create_info->preTransform),
1444 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001445 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001446 }
1447
Jesse Hallf64ca122015-11-03 16:11:10 -08001448 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001449 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1450 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001451 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1452 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001453 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001454 }
1455
Chris Forbes97ef4612017-03-30 19:37:50 +13001456 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes08c7bb12022-12-09 08:10:18 +13001457 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001458 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001459 err = native_window_set_shared_buffer_mode(window, true);
1460 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001461 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1462 return VK_ERROR_SURFACE_LOST_KHR;
1463 }
1464 }
1465
1466 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001467 err = native_window_set_auto_refresh(window, true);
1468 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001469 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1470 return VK_ERROR_SURFACE_LOST_KHR;
1471 }
1472 }
1473
Ian Elliott16c443c2021-11-30 17:10:32 -07001474 int query_value;
1475 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1476 &query_value);
1477 if (err != android::OK || query_value < 0) {
1478 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1479 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001480 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001481 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001482 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1483 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1484 const auto requested_images =
1485 swap_interval ? create_info->minImageCount : mailbox_num_images;
1486 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001487
Ian Elliott5396b702021-12-13 19:32:34 -07001488 // Lower layer insists that we have at least min_undequeued_buffers + 1
1489 // buffers. This is wasteful and we'd like to relax it in the shared case,
1490 // but not all the pieces are in place for that to work yet. Note we only
1491 // lie to the lower layer--we don't want to give the app back a swapchain
1492 // with extra images (which they can't actually use!).
1493 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1494 err = native_window_set_buffer_count(
1495 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001496 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001497 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1498 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001499 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001500 }
1501
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001502 // In shared mode the num_images must be one regardless of how many
1503 // buffers were allocated for the buffer queue.
1504 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1505 num_images = 1;
1506 }
1507
Trevor David Black2cc44682022-03-09 00:31:38 +00001508 void* usage_info_pNext = nullptr;
1509 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001510 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001511 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1512 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1513 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1514 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1515 gralloc_usage_info.format = create_info->imageFormat;
1516 gralloc_usage_info.imageUsage = create_info->imageUsage;
1517
1518 // Look through the pNext chain for an image compression control struct
1519 // if one is found AND the appropriate extensions are enabled,
1520 // append it to be the gralloc usage pNext chain
1521 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1522 while (create_infos->pNext) {
1523 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1524 create_infos->pNext);
1525 switch (create_infos->sType) {
1526 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1527 const VkImageCompressionControlEXT* compression_infos =
1528 reinterpret_cast<const VkImageCompressionControlEXT*>(
1529 create_infos);
1530 image_compression = *compression_infos;
1531 image_compression.pNext = nullptr;
1532 usage_info_pNext = &image_compression;
1533 } break;
1534
1535 default:
1536 // Ignore all other info structs
1537 break;
1538 }
1539 }
1540 gralloc_usage_info.pNext = usage_info_pNext;
1541
1542 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1543 device, &gralloc_usage_info, &native_usage);
1544 ATRACE_END();
1545 if (result != VK_SUCCESS) {
1546 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1547 return VK_ERROR_SURFACE_LOST_KHR;
1548 }
1549 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001550 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001551 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001552 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1553 device, create_info->imageFormat, create_info->imageUsage,
1554 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001555 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001556 if (result != VK_SUCCESS) {
1557 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001558 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001559 }
John Reck97678d42022-08-23 11:24:51 -04001560 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001561 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001562 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001563 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001564 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001565 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001566 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001567 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001568 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001569 if (result != VK_SUCCESS) {
1570 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001571 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001572 }
John Reck97678d42022-08-23 11:24:51 -04001573 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001574 }
John Reck97678d42022-08-23 11:24:51 -04001575 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001576
1577 bool createProtectedSwapchain = false;
1578 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1579 createProtectedSwapchain = true;
1580 native_usage |= BufferUsage::PROTECTED;
1581 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001582 err = native_window_set_usage(window, native_usage);
1583 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001584 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001585 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001586 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001587
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001588 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001589 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1590 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001591 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1592 strerror(-err), err);
1593 return VK_ERROR_SURFACE_LOST_KHR;
1594 }
1595
Jesse Halld7b994a2015-09-07 14:17:37 -07001596 // -- Allocate our Swapchain object --
1597 // After this point, we must deallocate the swapchain on error.
1598
Jesse Hall1f91d392015-12-11 16:28:44 -08001599 void* mem = allocator->pfnAllocation(allocator->pUserData,
1600 sizeof(Swapchain), alignof(Swapchain),
1601 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001602 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001603 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001604 Swapchain* swapchain = new (mem)
1605 Swapchain(surface, num_images, create_info->presentMode,
1606 TranslateVulkanToNativeTransform(create_info->preTransform));
Jesse Halld7b994a2015-09-07 14:17:37 -07001607
Chris Forbesb56287a2017-01-12 14:28:58 +13001608 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1609#pragma clang diagnostic push
1610#pragma clang diagnostic ignored "-Wold-style-cast"
1611 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1612#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001613 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001614 .usage = swapchain_image_usage,
1615 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001616 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001617#pragma clang diagnostic push
1618#pragma clang diagnostic ignored "-Wold-style-cast"
1619 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1620#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001621 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001622 };
Chris Forbes08c7bb12022-12-09 08:10:18 +13001623
Jesse Halld7b994a2015-09-07 14:17:37 -07001624 VkImageCreateInfo image_create = {
1625 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes08c7bb12022-12-09 08:10:18 +13001626 .pNext = nullptr,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001627 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001628 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001629 .format = create_info->imageFormat,
Chris Forbes08c7bb12022-12-09 08:10:18 +13001630 .extent = {
1631 create_info->imageExtent.width,
1632 create_info->imageExtent.height,
1633 1
1634 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001635 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001636 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001637 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001638 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001639 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001640 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001641 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001642 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1643 };
1644
Chris Forbes08c7bb12022-12-09 08:10:18 +13001645 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1646 // involved so very little benefit.
1647 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1648 !IsSharedPresentMode(create_info->presentMode)) {
1649 // Don't want to touch the underlying gralloc buffers yet;
1650 // instead just create unbound VkImages which will later be bound to memory inside
1651 // AcquireNextImage.
1652 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1653 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1654 .pNext = nullptr,
1655 .swapchain = HandleFromSwapchain(swapchain),
1656 };
1657 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001658
Chris Forbes08c7bb12022-12-09 08:10:18 +13001659 for (uint32_t i = 0; i < num_images; i++) {
1660 Swapchain::Image& img = swapchain->images[i];
1661 img.buffer = nullptr;
1662 img.dequeued = false;
1663
1664 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1665 if (result != VK_SUCCESS) {
1666 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1667 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001668 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001669 }
Chris Forbes08c7bb12022-12-09 08:10:18 +13001670 } else {
1671 // -- Dequeue all buffers and create a VkImage for each --
1672 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001673
Chris Forbes08c7bb12022-12-09 08:10:18 +13001674 for (uint32_t i = 0; i < num_images; i++) {
1675 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001676
Chris Forbes08c7bb12022-12-09 08:10:18 +13001677 ANativeWindowBuffer* buffer;
1678 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1679 if (err != android::OK) {
1680 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1681 switch (-err) {
1682 case ENOMEM:
1683 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1684 break;
1685 default:
1686 result = VK_ERROR_SURFACE_LOST_KHR;
1687 break;
1688 }
1689 break;
1690 }
1691 img.buffer = buffer;
1692 img.dequeued = true;
1693
1694 image_native_buffer.handle = img.buffer->handle;
1695 image_native_buffer.stride = img.buffer->stride;
1696 image_native_buffer.format = img.buffer->format;
1697 image_native_buffer.usage = int(img.buffer->usage);
1698 android_convertGralloc0To1Usage(int(img.buffer->usage),
1699 &image_native_buffer.usage2.producer,
1700 &image_native_buffer.usage2.consumer);
1701 image_native_buffer.usage3 = img.buffer->usage;
1702 image_create.pNext = &image_native_buffer;
1703
1704 ATRACE_BEGIN("CreateImage");
1705 result =
1706 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1707 ATRACE_END();
1708 if (result != VK_SUCCESS) {
1709 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1710 break;
1711 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001712 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001713
Chris Forbes08c7bb12022-12-09 08:10:18 +13001714 // -- Cancel all buffers, returning them to the queue --
1715 // If an error occurred before, also destroy the VkImage and release the
1716 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1717 for (uint32_t i = 0; i < num_images; i++) {
1718 Swapchain::Image& img = swapchain->images[i];
1719 if (img.dequeued) {
1720 if (!swapchain->shared) {
1721 window->cancelBuffer(window, img.buffer.get(),
1722 img.dequeue_fence);
1723 img.dequeue_fence = -1;
1724 img.dequeued = false;
1725 }
Chris Forbese0ced032017-03-30 19:44:15 +13001726 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001727 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001728 }
1729
1730 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001731 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1732 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001733 return result;
1734 }
1735
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001736 if (transform_hint != swapchain->pre_transform) {
1737 // Log that the app is not doing pre-rotation.
1738 android::GraphicsEnv::getInstance().setTargetStats(
1739 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1740 }
1741
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001742 // Set stats for creating a Vulkan swapchain
1743 android::GraphicsEnv::getInstance().setTargetStats(
1744 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1745
Jesse Halldc225072016-05-30 22:40:14 -07001746 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1747 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001748 return VK_SUCCESS;
1749}
1750
Jesse Halle1b12782015-11-30 11:27:32 -08001751VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001752void DestroySwapchainKHR(VkDevice device,
1753 VkSwapchainKHR swapchain_handle,
1754 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001755 ATRACE_CALL();
1756
Yiwei Zhang533cea92019-06-03 18:43:24 -07001757 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001758}
1759
Jesse Halle1b12782015-11-30 11:27:32 -08001760VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001761VkResult GetSwapchainImagesKHR(VkDevice,
1762 VkSwapchainKHR swapchain_handle,
1763 uint32_t* count,
1764 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001765 ATRACE_CALL();
1766
Jesse Halld7b994a2015-09-07 14:17:37 -07001767 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001768 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1769 "getting images for non-active swapchain 0x%" PRIx64
1770 "; only dequeued image handles are valid",
1771 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001772 VkResult result = VK_SUCCESS;
1773 if (images) {
1774 uint32_t n = swapchain.num_images;
1775 if (*count < swapchain.num_images) {
1776 n = *count;
1777 result = VK_INCOMPLETE;
1778 }
1779 for (uint32_t i = 0; i < n; i++)
1780 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001781 *count = n;
1782 } else {
1783 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001784 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001785 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001786}
1787
Jesse Halle1b12782015-11-30 11:27:32 -08001788VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001789VkResult AcquireNextImageKHR(VkDevice device,
1790 VkSwapchainKHR swapchain_handle,
1791 uint64_t timeout,
1792 VkSemaphore semaphore,
1793 VkFence vk_fence,
1794 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001795 ATRACE_CALL();
1796
Jesse Halld7b994a2015-09-07 14:17:37 -07001797 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001798 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001799 VkResult result;
1800 int err;
1801
Jesse Halldc225072016-05-30 22:40:14 -07001802 if (swapchain.surface.swapchain_handle != swapchain_handle)
1803 return VK_ERROR_OUT_OF_DATE_KHR;
1804
Chris Forbesc88409c2017-03-30 19:47:37 +13001805 if (swapchain.shared) {
1806 // In shared mode, we keep the buffer dequeued all the time, so we don't
1807 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1808 // the semaphore and fence passed to us will be signalled.
1809 *image_index = 0;
1810 result = GetData(device).driver.AcquireImageANDROID(
1811 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1812 return result;
1813 }
1814
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001815 const nsecs_t acquire_next_image_timeout =
1816 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1817 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1818 // Cache the timeout to avoid the duplicate binder cost.
1819 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1820 acquire_next_image_timeout);
1821 if (err != android::OK) {
1822 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1823 strerror(-err), err);
1824 return VK_ERROR_SURFACE_LOST_KHR;
1825 }
1826 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1827 }
1828
Jesse Halld7b994a2015-09-07 14:17:37 -07001829 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001830 int fence_fd;
1831 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001832 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001833 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1834 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1835 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001836 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001837 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001838 }
1839
1840 uint32_t idx;
1841 for (idx = 0; idx < swapchain.num_images; idx++) {
1842 if (swapchain.images[idx].buffer.get() == buffer) {
1843 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001844 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001845 break;
1846 }
1847 }
Chris Forbes08c7bb12022-12-09 08:10:18 +13001848
1849 // If this is a deferred alloc swapchain, this may be the first time we've
1850 // seen a particular buffer. If so, there should be an empty slot. Find it,
1851 // and bind the gralloc buffer to the VkImage for that slot. If there is no
1852 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
1853 // will also take this path, but will never have an empty slot since we
1854 // populated them all upfront.
1855 if (idx == swapchain.num_images) {
1856 for (idx = 0; idx < swapchain.num_images; idx++) {
1857 if (!swapchain.images[idx].buffer) {
1858 // Note: this structure is technically required for
1859 // Vulkan correctness, even though the driver is probably going
1860 // to use everything from the VkNativeBufferANDROID below.
1861 // This is kindof silly, but it's how we did the ANB
1862 // side of VK_KHR_swapchain v69, so we're stuck with it unless
1863 // we want to go tinkering with the ANB spec some more.
1864 VkBindImageMemorySwapchainInfoKHR bimsi = {
1865 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
1866 .pNext = nullptr,
1867 .swapchain = swapchain_handle,
1868 .imageIndex = idx,
1869 };
1870 VkNativeBufferANDROID nb = {
1871 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1872 .pNext = &bimsi,
1873 .handle = buffer->handle,
1874 .stride = buffer->stride,
1875 .format = buffer->format,
1876 .usage = int(buffer->usage),
1877 };
1878 VkBindImageMemoryInfo bimi = {
1879 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
1880 .pNext = &nb,
1881 .image = swapchain.images[idx].image,
1882 .memory = VK_NULL_HANDLE,
1883 .memoryOffset = 0,
1884 };
1885 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
1886 if (result != VK_SUCCESS) {
1887 // This shouldn't really happen. If it does, something is probably
1888 // unrecoverably wrong with the swapchain and its images. Cancel
1889 // the buffer and declare the swapchain broken.
1890 ALOGE("failed to do deferred gralloc buffer bind");
1891 window->cancelBuffer(window, buffer, fence_fd);
1892 return VK_ERROR_OUT_OF_DATE_KHR;
1893 }
1894
1895 swapchain.images[idx].dequeued = true;
1896 swapchain.images[idx].dequeue_fence = fence_fd;
1897 swapchain.images[idx].buffer = buffer;
1898 break;
1899 }
1900 }
1901 }
1902
1903 // The buffer doesn't match any slot. This shouldn't normally happen, but is
1904 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
1905 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07001906 if (idx == swapchain.num_images) {
1907 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001908 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001909 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001910 }
1911
1912 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001913 if (fence_fd != -1) {
1914 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001915 if (fence_clone == -1) {
1916 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1917 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001918 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001919 }
1920 }
1921
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001922 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001923 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001924 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001925 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1926 // even if the call fails. We could close it ourselves on failure, but
1927 // that would create a race condition if the driver closes it on a
1928 // failure path: some other thread might create an fd with the same
1929 // number between the time the driver closes it and the time we close
1930 // it. We must assume one of: the driver *always* closes it even on
1931 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001932 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001933 swapchain.images[idx].dequeued = false;
1934 swapchain.images[idx].dequeue_fence = -1;
1935 return result;
1936 }
1937
1938 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001939 return VK_SUCCESS;
1940}
1941
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001942VKAPI_ATTR
1943VkResult AcquireNextImage2KHR(VkDevice device,
1944 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1945 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001946 ATRACE_CALL();
1947
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001948 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1949 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1950 pAcquireInfo->fence, pImageIndex);
1951}
1952
Jesse Halldc225072016-05-30 22:40:14 -07001953static VkResult WorstPresentResult(VkResult a, VkResult b) {
1954 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1955 // (in spec version 1.0.14).
1956 static const VkResult kWorstToBest[] = {
1957 VK_ERROR_DEVICE_LOST,
1958 VK_ERROR_SURFACE_LOST_KHR,
1959 VK_ERROR_OUT_OF_DATE_KHR,
1960 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1961 VK_ERROR_OUT_OF_HOST_MEMORY,
1962 VK_SUBOPTIMAL_KHR,
1963 };
1964 for (auto result : kWorstToBest) {
1965 if (a == result || b == result)
1966 return result;
1967 }
1968 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1969 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1970 return a != VK_SUCCESS ? a : b;
1971}
1972
Chris Forbes4cd01fb2022-10-19 11:35:16 +13001973// KHR_incremental_present aspect of QueuePresentKHR
1974static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
1975 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
1976 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
1977 auto const& rect = pRegion->pRectangles[i];
1978 if (rect.layer > 0) {
1979 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
1980 rect.layer);
1981 }
1982
1983 rects[i].left = rect.offset.x;
1984 rects[i].bottom = rect.offset.y;
1985 rects[i].right = rect.offset.x + rect.extent.width;
1986 rects[i].top = rect.offset.y + rect.extent.height;
1987 }
1988 native_window_set_surface_damage(window, rects.data(), rects.size());
1989}
1990
1991// GOOGLE_display_timing aspect of QueuePresentKHR
1992static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
1993 ANativeWindow *window = swapchain.surface.window.get();
1994
1995 // We don't know whether the app will actually use GOOGLE_display_timing
1996 // with a particular swapchain until QueuePresent; enable it on the BQ
1997 // now if needed
1998 if (!swapchain.frame_timestamps_enabled) {
1999 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2000 native_window_enable_frame_timestamps(window, true);
2001 swapchain.frame_timestamps_enabled = true;
2002 }
2003
2004 // Record the nativeFrameId so it can be later correlated to
2005 // this present.
2006 uint64_t nativeFrameId = 0;
2007 int err = native_window_get_next_frame_id(
2008 window, &nativeFrameId);
2009 if (err != android::OK) {
2010 ALOGE("Failed to get next native frame ID.");
2011 }
2012
2013 // Add a new timing record with the user's presentID and
2014 // the nativeFrameId.
2015 swapchain.timing.emplace_back(pTime, nativeFrameId);
2016 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2017 swapchain.timing.erase(
2018 swapchain.timing.begin(),
2019 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2020 }
2021 if (pTime->desiredPresentTime) {
2022 ALOGV(
2023 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2024 pTime->desiredPresentTime);
2025 native_window_set_buffers_timestamp(
2026 window,
2027 static_cast<int64_t>(pTime->desiredPresentTime));
2028 }
2029}
2030
Chris Forbes08c7bb12022-12-09 08:10:18 +13002031// EXT_swapchain_maintenance1 present mode change
2032static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2033 // There is no dynamic switching between non-shared present modes.
2034 // All we support is switching between demand and continuous refresh.
2035 if (!IsSharedPresentMode(mode))
2036 return true;
2037
2038 int err = native_window_set_auto_refresh(window,
2039 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2040 if (err != android::OK) {
2041 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2042 strerror(-err), err);
2043 return false;
2044 }
2045
2046 return true;
2047}
2048
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002049static VkResult PresentOneSwapchain(
2050 VkQueue queue,
2051 Swapchain& swapchain,
2052 uint32_t imageIndex,
2053 const VkPresentRegionKHR *pRegion,
2054 const VkPresentTimeGOOGLE *pTime,
Chris Forbes08c7bb12022-12-09 08:10:18 +13002055 VkFence presentFence,
2056 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002057 uint32_t waitSemaphoreCount,
2058 const VkSemaphore *pWaitSemaphores) {
2059
2060 VkDevice device = GetData(queue).driver_device;
2061 const auto& dispatch = GetData(queue).driver;
2062
2063 Swapchain::Image& img = swapchain.images[imageIndex];
2064 VkResult swapchain_result = VK_SUCCESS;
2065 VkResult result;
2066 int err;
2067
2068 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2069 // wait semaphores, so this doesn't actually work for the multiple swapchain
2070 // case.
2071 int fence = -1;
2072 result = dispatch.QueueSignalReleaseImageANDROID(
2073 queue, waitSemaphoreCount,
2074 pWaitSemaphores, img.image, &fence);
2075 if (result != VK_SUCCESS) {
2076 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2077 swapchain_result = result;
2078 }
2079 if (img.release_fence >= 0)
2080 close(img.release_fence);
2081 img.release_fence = fence < 0 ? -1 : dup(fence);
2082
2083 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2084 ANativeWindow* window = swapchain.surface.window.get();
2085 if (swapchain_result == VK_SUCCESS) {
2086
Chris Forbes08c7bb12022-12-09 08:10:18 +13002087 if (presentFence != VK_NULL_HANDLE) {
2088 int fence_copy = fence < 0 ? -1 : dup(fence);
2089 VkImportFenceFdInfoKHR iffi = {
2090 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2091 nullptr,
2092 presentFence,
2093 VK_FENCE_IMPORT_TEMPORARY_BIT,
2094 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2095 fence_copy,
2096 };
2097 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2098 // ImportFenceFdKHR takes ownership only if it succeeds
2099 close(fence_copy);
2100 }
2101 }
2102
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002103 if (pRegion) {
2104 SetSwapchainSurfaceDamage(window, pRegion);
2105 }
2106 if (pTime) {
2107 SetSwapchainFrameTimestamp(swapchain, pTime);
2108 }
Chris Forbes08c7bb12022-12-09 08:10:18 +13002109 if (pPresentMode) {
2110 if (!SetSwapchainPresentMode(window, *pPresentMode))
2111 swapchain_result = WorstPresentResult(swapchain_result,
2112 VK_ERROR_SURFACE_LOST_KHR);
2113 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002114
2115 err = window->queueBuffer(window, img.buffer.get(), fence);
2116 // queueBuffer always closes fence, even on error
2117 if (err != android::OK) {
2118 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2119 swapchain_result = WorstPresentResult(
2120 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2121 } else {
2122 if (img.dequeue_fence >= 0) {
2123 close(img.dequeue_fence);
2124 img.dequeue_fence = -1;
2125 }
2126 img.dequeued = false;
2127 }
2128
2129 // If the swapchain is in shared mode, immediately dequeue the
2130 // buffer so it can be presented again without an intervening
2131 // call to AcquireNextImageKHR. We expect to get the same buffer
2132 // back from every call to dequeueBuffer in this mode.
2133 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2134 ANativeWindowBuffer* buffer;
2135 int fence_fd;
2136 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2137 if (err != android::OK) {
2138 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2139 swapchain_result = WorstPresentResult(swapchain_result,
2140 VK_ERROR_SURFACE_LOST_KHR);
2141 } else if (img.buffer != buffer) {
2142 ALOGE("got wrong image back for shared swapchain");
2143 swapchain_result = WorstPresentResult(swapchain_result,
2144 VK_ERROR_SURFACE_LOST_KHR);
2145 } else {
2146 img.dequeue_fence = fence_fd;
2147 img.dequeued = true;
2148 }
2149 }
2150 }
2151 if (swapchain_result != VK_SUCCESS) {
2152 OrphanSwapchain(device, &swapchain);
2153 }
2154 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2155 // and only when the window's transform/rotation changes. Extent
2156 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2157 // application issues that were caused when the following transform
2158 // change was added.
2159 int window_transform_hint;
2160 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2161 &window_transform_hint);
2162 if (err != android::OK) {
2163 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2164 strerror(-err), err);
2165 swapchain_result = WorstPresentResult(
2166 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2167 }
2168 if (swapchain.pre_transform != window_transform_hint) {
2169 swapchain_result =
2170 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2171 }
2172 } else {
2173 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2174 img, true);
2175 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2176 }
2177
2178 return swapchain_result;
2179}
2180
Jesse Halle1b12782015-11-30 11:27:32 -08002181VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002182VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002183 ATRACE_CALL();
2184
Jesse Halld7b994a2015-09-07 14:17:37 -07002185 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2186 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2187 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002188
Jesse Halld7b994a2015-09-07 14:17:37 -07002189 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002190
Ian Elliottcb351132016-12-13 10:30:40 -07002191 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002192 const VkPresentRegionsKHR* present_regions = nullptr;
2193 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes08c7bb12022-12-09 08:10:18 +13002194 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2195 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2196
Ian Elliottcb351132016-12-13 10:30:40 -07002197 const VkPresentRegionsKHR* next =
2198 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2199 while (next) {
2200 switch (next->sType) {
2201 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2202 present_regions = next;
2203 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002204 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002205 present_times =
2206 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2207 break;
Chris Forbes08c7bb12022-12-09 08:10:18 +13002208 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2209 present_fences =
2210 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2211 break;
2212 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2213 present_modes =
2214 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2215 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002216 default:
2217 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2218 next->sType);
2219 break;
2220 }
2221 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2222 }
2223 ALOGV_IF(
2224 present_regions &&
2225 present_regions->swapchainCount != present_info->swapchainCount,
2226 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002227 ALOGV_IF(present_times &&
2228 present_times->swapchainCount != present_info->swapchainCount,
2229 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2230 "VkPresentInfo::swapchainCount");
Chris Forbes08c7bb12022-12-09 08:10:18 +13002231 ALOGV_IF(present_fences &&
2232 present_fences->swapchainCount != present_info->swapchainCount,
2233 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2234 "VkPresentInfo::swapchainCount");
2235 ALOGV_IF(present_modes &&
2236 present_modes->swapchainCount != present_info->swapchainCount,
2237 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2238 "VkPresentInfo::swapchainCount");
2239
Ian Elliottcb351132016-12-13 10:30:40 -07002240 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002241 (present_regions) ? present_regions->pRegions : nullptr;
2242 const VkPresentTimeGOOGLE* times =
2243 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002244
Jesse Halld7b994a2015-09-07 14:17:37 -07002245 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2246 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002247 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002248
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002249 VkResult swapchain_result = PresentOneSwapchain(
2250 queue,
2251 swapchain,
2252 present_info->pImageIndices[sc],
2253 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2254 times ? &times[sc] : nullptr,
Chris Forbes08c7bb12022-12-09 08:10:18 +13002255 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2256 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002257 present_info->waitSemaphoreCount,
2258 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002259
Jesse Halla9e57032015-11-30 01:03:10 -08002260 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002261 present_info->pResults[sc] = swapchain_result;
2262
2263 if (swapchain_result != final_result)
2264 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002265 }
2266
2267 return final_result;
2268}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002269
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002270VKAPI_ATTR
2271VkResult GetRefreshCycleDurationGOOGLE(
2272 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002273 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002274 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002275 ATRACE_CALL();
2276
Ian Elliott62c48c92017-01-20 13:13:20 -07002277 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002278 VkResult result = VK_SUCCESS;
2279
Ian Elliott3568bfe2019-05-03 15:54:46 -06002280 pDisplayTimingProperties->refreshDuration = swapchain.get_refresh_duration();
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002281
2282 return result;
2283}
2284
2285VKAPI_ATTR
2286VkResult GetPastPresentationTimingGOOGLE(
2287 VkDevice,
2288 VkSwapchainKHR swapchain_handle,
2289 uint32_t* count,
2290 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002291 ATRACE_CALL();
2292
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002293 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002294 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2295 return VK_ERROR_OUT_OF_DATE_KHR;
2296 }
2297
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002298 ANativeWindow* window = swapchain.surface.window.get();
2299 VkResult result = VK_SUCCESS;
2300
2301 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002302 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002303 native_window_enable_frame_timestamps(window, true);
2304 swapchain.frame_timestamps_enabled = true;
2305 }
2306
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002307 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002308 // Get the latest ready timing count before copying, since the copied
2309 // timing info will be erased in copy_ready_timings function.
2310 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002311 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002312 // Check the *count here against the recorded ready timing count, since
2313 // *count can be overwritten per spec describes.
2314 if (*count < n) {
2315 result = VK_INCOMPLETE;
2316 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002317 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002318 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002319 }
2320
2321 return result;
2322}
2323
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002324VKAPI_ATTR
2325VkResult GetSwapchainStatusKHR(
2326 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002327 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002328 ATRACE_CALL();
2329
Chris Forbes4e18ba82017-01-20 12:50:17 +13002330 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002331 VkResult result = VK_SUCCESS;
2332
Chris Forbes4e18ba82017-01-20 12:50:17 +13002333 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2334 return VK_ERROR_OUT_OF_DATE_KHR;
2335 }
2336
Yiwei Zhanga885c062019-10-24 12:07:57 -07002337 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002338
2339 return result;
2340}
2341
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002342VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002343 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002344 uint32_t swapchainCount,
2345 const VkSwapchainKHR* pSwapchains,
2346 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002347 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002348
2349 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2350 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2351 if (!swapchain)
2352 continue;
2353
2354 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2355
2356 ANativeWindow* window = swapchain->surface.window.get();
2357
2358 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2359 const android_smpte2086_metadata smpteMetdata = {
2360 {vulkanMetadata.displayPrimaryRed.x,
2361 vulkanMetadata.displayPrimaryRed.y},
2362 {vulkanMetadata.displayPrimaryGreen.x,
2363 vulkanMetadata.displayPrimaryGreen.y},
2364 {vulkanMetadata.displayPrimaryBlue.x,
2365 vulkanMetadata.displayPrimaryBlue.y},
2366 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2367 vulkanMetadata.maxLuminance,
2368 vulkanMetadata.minLuminance};
2369 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2370
2371 const android_cta861_3_metadata cta8613Metadata = {
2372 vulkanMetadata.maxContentLightLevel,
2373 vulkanMetadata.maxFrameAverageLightLevel};
2374 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2375 }
2376
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002377 return;
2378}
2379
Yiwei Zhang0f475222019-04-11 19:38:00 -07002380static void InterceptBindImageMemory2(
2381 uint32_t bind_info_count,
2382 const VkBindImageMemoryInfo* bind_infos,
2383 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2384 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2385 out_native_buffers->clear();
2386 out_bind_infos->clear();
2387
2388 if (!bind_info_count)
2389 return;
2390
2391 std::unordered_set<uint32_t> intercepted_indexes;
2392
2393 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2394 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2395 bind_infos[idx].pNext);
2396 while (info &&
2397 info->sType !=
2398 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2399 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2400 info->pNext);
2401 }
2402
2403 if (!info)
2404 continue;
2405
2406 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2407 "swapchain handle must not be NULL");
2408 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2409 ALOG_ASSERT(
2410 info->imageIndex < swapchain->num_images,
2411 "imageIndex must be less than the number of images in swapchain");
2412
2413 ANativeWindowBuffer* buffer =
2414 swapchain->images[info->imageIndex].buffer.get();
2415 VkNativeBufferANDROID native_buffer = {
2416#pragma clang diagnostic push
2417#pragma clang diagnostic ignored "-Wold-style-cast"
2418 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2419#pragma clang diagnostic pop
2420 .pNext = bind_infos[idx].pNext,
2421 .handle = buffer->handle,
2422 .stride = buffer->stride,
2423 .format = buffer->format,
2424 .usage = int(buffer->usage),
2425 };
2426 // Reserve enough space to avoid letting re-allocation invalidate the
2427 // addresses of the elements inside.
2428 out_native_buffers->reserve(bind_info_count);
2429 out_native_buffers->emplace_back(native_buffer);
2430
2431 // Reserve the space now since we know how much is needed now.
2432 out_bind_infos->reserve(bind_info_count);
2433 out_bind_infos->emplace_back(bind_infos[idx]);
2434 out_bind_infos->back().pNext = &out_native_buffers->back();
2435
2436 intercepted_indexes.insert(idx);
2437 }
2438
2439 if (intercepted_indexes.empty())
2440 return;
2441
2442 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2443 if (intercepted_indexes.count(idx))
2444 continue;
2445 out_bind_infos->emplace_back(bind_infos[idx]);
2446 }
2447}
2448
Yiwei Zhang23143102019-04-10 18:24:05 -07002449VKAPI_ATTR
2450VkResult BindImageMemory2(VkDevice device,
2451 uint32_t bindInfoCount,
2452 const VkBindImageMemoryInfo* pBindInfos) {
2453 ATRACE_CALL();
2454
Yiwei Zhang0f475222019-04-11 19:38:00 -07002455 // out_native_buffers is for maintaining the lifecycle of the constructed
2456 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2457 std::vector<VkNativeBufferANDROID> out_native_buffers;
2458 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2459 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2460 &out_bind_infos);
2461 return GetData(device).driver.BindImageMemory2(
2462 device, bindInfoCount,
2463 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002464}
2465
2466VKAPI_ATTR
2467VkResult BindImageMemory2KHR(VkDevice device,
2468 uint32_t bindInfoCount,
2469 const VkBindImageMemoryInfo* pBindInfos) {
2470 ATRACE_CALL();
2471
Yiwei Zhang0f475222019-04-11 19:38:00 -07002472 std::vector<VkNativeBufferANDROID> out_native_buffers;
2473 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2474 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2475 &out_bind_infos);
2476 return GetData(device).driver.BindImageMemory2KHR(
2477 device, bindInfoCount,
2478 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002479}
2480
Chris Forbes08c7bb12022-12-09 08:10:18 +13002481VKAPI_ATTR
2482VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2483 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2484 ATRACE_CALL();
2485
2486 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2487 ANativeWindow* window = swapchain.surface.window.get();
2488
2489 // If in shared present mode, don't actually release the image back to the BQ.
2490 // Both sides share it forever.
2491 if (swapchain.shared)
2492 return VK_SUCCESS;
2493
2494 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2495 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2496 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2497
2498 // cancelBuffer has taken ownership of the dequeue fence
2499 img.dequeue_fence = -1;
2500 // if we're still holding a release fence, get rid of it now
2501 if (img.release_fence >= 0) {
2502 close(img.release_fence);
2503 img.release_fence = -1;
2504 }
2505 img.dequeued = false;
2506 }
2507
2508 return VK_SUCCESS;
2509}
2510
Chia-I Wu62262232016-03-26 07:06:44 +08002511} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002512} // namespace vulkan