blob: 1bff50dd7f8801a8d86b929c73002a981080e7c8 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Yiwei Zhang0f475222019-04-11 19:38:00 -070019#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070020#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070021#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040022#include <hardware/gralloc.h>
23#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070025#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070026#include <system/window.h>
27#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050028#include <ui/DebugUtils.h>
29#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080030#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080031#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080032#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070033
34#include <algorithm>
35#include <unordered_set>
36#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Chia-I Wu4a6a9162016-03-26 07:17:34 +080038#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Daniel Kochf25f5bb2017-10-05 00:26:58 -040040using android::hardware::graphics::common::V1_0::BufferUsage;
41
Chia-I Wu62262232016-03-26 07:06:44 +080042namespace vulkan {
43namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070044
Jesse Halld7b994a2015-09-07 14:17:37 -070045namespace {
46
John Reck97678d42022-08-23 11:24:51 -040047static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
48 uint64_t consumerUsage) {
49 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
50 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
51 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
52 "bits to match");
53 uint64_t merged = producerUsage | consumerUsage;
54 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
55 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
56 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
57 merged |= BufferUsage::CPU_READ_OFTEN;
58 }
59 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
60 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
61 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
62 merged |= BufferUsage::CPU_WRITE_OFTEN;
63 }
64 return merged;
65}
66
Jesse Hall55bc0972016-02-23 16:43:29 -080067const VkSurfaceTransformFlagsKHR kSupportedTransforms =
68 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
69 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
70 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
71 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
73 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080076 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
77
78VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
79 // Native and Vulkan transforms are isomorphic, but are represented
80 // differently. Vulkan transforms are built up of an optional horizontal
81 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
82 // transforms are built up from a horizontal flip, vertical flip, and
83 // 90-degree rotation, all optional but always in that order.
84
Jesse Hall55bc0972016-02-23 16:43:29 -080085 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070086 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080087 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070088 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
89 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
90 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
91 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
92 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080093 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070094 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080095 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070096 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
97 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
98 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
99 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
100 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800101 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
103 default:
104 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
105 }
106}
107
Yiwei Zhang70a21962019-05-31 17:26:52 -0700108int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
109 switch (transform) {
110 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
111 return NATIVE_WINDOW_TRANSFORM_ROT_90;
112 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
113 return NATIVE_WINDOW_TRANSFORM_ROT_180;
114 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_270;
116 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
118 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
120 NATIVE_WINDOW_TRANSFORM_ROT_90;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
123 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
124 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
125 NATIVE_WINDOW_TRANSFORM_ROT_90;
126 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
127 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
128 default:
129 return 0;
130 }
131}
132
Jesse Hall178b6962016-02-24 15:39:50 -0800133int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
134 switch (transform) {
135 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
136 return NATIVE_WINDOW_TRANSFORM_ROT_270;
137 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
138 return NATIVE_WINDOW_TRANSFORM_ROT_180;
139 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700141 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
143 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
145 NATIVE_WINDOW_TRANSFORM_ROT_90;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
148 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
149 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
150 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800151 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
152 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
153 default:
154 return 0;
155 }
156}
157
Ian Elliott8a977262017-01-19 09:05:58 -0700158class TimingInfo {
159 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800160 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700161 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800162 native_frame_id_(nativeFrameId) {}
163 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700164 return (timestamp_desired_present_time_ !=
165 NATIVE_WINDOW_TIMESTAMP_PENDING &&
166 timestamp_actual_present_time_ !=
167 NATIVE_WINDOW_TIMESTAMP_PENDING &&
168 timestamp_render_complete_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_composition_latch_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700172 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700173 void calculate(int64_t rdur) {
174 bool anyTimestampInvalid =
175 (timestamp_actual_present_time_ ==
176 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
177 (timestamp_render_complete_time_ ==
178 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
179 (timestamp_composition_latch_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID);
181 if (anyTimestampInvalid) {
182 ALOGE("Unexpectedly received invalid timestamp.");
183 vals_.actualPresentTime = 0;
184 vals_.earliestPresentTime = 0;
185 vals_.presentMargin = 0;
186 return;
187 }
188
189 vals_.actualPresentTime =
190 static_cast<uint64_t>(timestamp_actual_present_time_);
191 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700192 timestamp_render_complete_time_);
193 // Calculate vals_.earliestPresentTime, and potentially adjust
194 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
195 // is vals_.actualPresentTime. If we can subtract rdur (the duration
196 // of a refresh cycle) from vals_.earliestPresentTime (and also from
197 // vals_.presentMargin) and still leave a positive margin, then we can
198 // report to the application that it could have presented earlier than
199 // it did (per the extension specification). If for some reason, we
200 // can do this subtraction repeatedly, we do, since
201 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700202 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700203 while ((margin > rdur) &&
204 ((early_time - rdur) > timestamp_composition_latch_time_)) {
205 early_time -= rdur;
206 margin -= rdur;
207 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700208 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
209 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700210 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800211 void get_values(VkPastPresentationTimingGOOGLE* values) const {
212 *values = vals_;
213 }
Ian Elliott8a977262017-01-19 09:05:58 -0700214
215 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800216 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700217
Brian Anderson1049d1d2016-12-16 17:25:57 -0800218 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700219 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
220 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
221 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
222 int64_t timestamp_composition_latch_time_
223 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700224};
225
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800227 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700228 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700229 uint64_t consumer_usage;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230};
231
232VkSurfaceKHR HandleFromSurface(Surface* surface) {
233 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
234}
235
236Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800237 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800238}
239
Ian Elliott8a977262017-01-19 09:05:58 -0700240// Maximum number of TimingInfo structs to keep per swapchain:
241enum { MAX_TIMING_INFOS = 10 };
242// Minimum number of frames to look for in the past (so we don't cause
243// syncronous requests to Surface Flinger):
244enum { MIN_NUM_FRAMES_AGO = 5 };
245
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300246bool IsSharedPresentMode(VkPresentModeKHR mode) {
247 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
248 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
249}
250
Jesse Hall1356b0d2015-11-23 17:24:58 -0800251struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700252 Swapchain(Surface& surface_,
253 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700254 VkPresentModeKHR present_mode,
255 int pre_transform_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700256 : surface(surface_),
257 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700258 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700259 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300260 frame_timestamps_enabled(false),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800261 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300262 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700263 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700264 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700265 window,
Brian Andersondc96fdf2017-03-20 16:54:25 -0700266 &refresh_duration);
Ian Elliott8a977262017-01-19 09:05:58 -0700267 }
Ian Elliott3568bfe2019-05-03 15:54:46 -0600268 uint64_t get_refresh_duration()
269 {
270 ANativeWindow* window = surface.window.get();
271 native_window_get_refresh_cycle_duration(
272 window,
273 &refresh_duration);
274 return static_cast<uint64_t>(refresh_duration);
275
276 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800277
278 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700279 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700280 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700281 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700282 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700283 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800284 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300285 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700286
287 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700288 Image()
289 : image(VK_NULL_HANDLE),
290 dequeue_fence(-1),
291 release_fence(-1),
292 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700293 VkImage image;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000294 // If the image is bound to memory, an sp to the underlying gralloc buffer.
295 // Otherwise, nullptr; the image will be bound to memory as part of
296 // AcquireNextImage.
Chia-I Wue8e689f2016-04-18 08:21:31 +0800297 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700298 // The fence is only valid when the buffer is dequeued, and should be
299 // -1 any other time. When valid, we own the fd, and must ensure it is
300 // closed: either by closing it explicitly when queueing the buffer,
301 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
302 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700303 // This fence is a dup of the sync fd returned from the driver via
304 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
305 // ensure it is closed upon re-presenting or releasing the image.
306 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700307 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800308 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700309
Yiwei Zhang5e862202019-06-21 14:59:16 -0700310 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700311};
312
313VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
314 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
315}
316
317Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800318 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700319}
320
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700321static bool IsFencePending(int fd) {
322 if (fd < 0)
323 return false;
324
325 errno = 0;
326 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
327}
328
Jesse Halldc225072016-05-30 22:40:14 -0700329void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000330 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700331 ANativeWindow* window,
332 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700333 Swapchain::Image& image,
334 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700335 ATRACE_CALL();
336
Jesse Halldc225072016-05-30 22:40:14 -0700337 ALOG_ASSERT(release_fence == -1 || image.dequeued,
338 "ReleaseSwapchainImage: can't provide a release fence for "
339 "non-dequeued images");
340
341 if (image.dequeued) {
342 if (release_fence >= 0) {
343 // We get here from vkQueuePresentKHR. The application is
344 // responsible for creating an execution dependency chain from
345 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
346 // (release_fence), so we can drop the dequeue_fence here.
347 if (image.dequeue_fence >= 0)
348 close(image.dequeue_fence);
349 } else {
350 // We get here during swapchain destruction, or various serious
351 // error cases e.g. when we can't create the release_fence during
352 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
353 // have already signalled, since the swapchain images are supposed
354 // to be idle before the swapchain is destroyed. In error cases,
355 // there may be rendering in flight to the image, but since we
356 // weren't able to create a release_fence, waiting for the
357 // dequeue_fence is about the best we can do.
358 release_fence = image.dequeue_fence;
359 }
360 image.dequeue_fence = -1;
361
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000362 // It's invalid to call cancelBuffer on a shared buffer
363 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700364 window->cancelBuffer(window, image.buffer.get(), release_fence);
365 } else {
366 if (release_fence >= 0) {
367 sync_wait(release_fence, -1 /* forever */);
368 close(release_fence);
369 }
370 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700371 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700372 image.dequeued = false;
373 }
374
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700375 if (defer_if_pending && IsFencePending(image.release_fence))
376 return;
377
378 if (image.release_fence >= 0) {
379 close(image.release_fence);
380 image.release_fence = -1;
381 }
382
Jesse Halldc225072016-05-30 22:40:14 -0700383 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700384 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700385 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700386 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700387 image.image = VK_NULL_HANDLE;
388 }
389
390 image.buffer.clear();
391}
392
393void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
394 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
395 return;
Jesse Halldc225072016-05-30 22:40:14 -0700396 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000397 if (!swapchain->images[i].dequeued) {
398 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
399 swapchain->images[i], true);
400 }
Jesse Halldc225072016-05-30 22:40:14 -0700401 }
402 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700403 swapchain->timing.clear();
404}
405
406uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800407 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
408 return 0;
409 }
Ian Elliott8a977262017-01-19 09:05:58 -0700410
Brian Anderson1049d1d2016-12-16 17:25:57 -0800411 uint32_t num_ready = 0;
412 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
413 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700414 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800415 if (ti.ready()) {
416 // This TimingInfo is ready to be reported to the user. Add it
417 // to the num_ready.
418 num_ready++;
419 continue;
420 }
421 // This TimingInfo is not yet ready to be reported to the user,
422 // and so we should look for any available timestamps that
423 // might make it ready.
424 int64_t desired_present_time = 0;
425 int64_t render_complete_time = 0;
426 int64_t composition_latch_time = 0;
427 int64_t actual_present_time = 0;
428 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800429 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800430 swapchain.surface.window.get(), ti.native_frame_id_,
431 &desired_present_time, &render_complete_time,
432 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700433 nullptr, //&first_composition_start_time,
434 nullptr, //&last_composition_start_time,
435 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800436 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700437 nullptr, //&dequeue_ready_time,
438 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800439
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800440 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800441 continue;
442 }
443
444 // Record the timestamp(s) we received, and then see if this TimingInfo
445 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700446 ti.timestamp_desired_present_time_ = desired_present_time;
447 ti.timestamp_actual_present_time_ = actual_present_time;
448 ti.timestamp_render_complete_time_ = render_complete_time;
449 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800450
451 if (ti.ready()) {
452 // The TimingInfo has received enough timestamps, and should now
453 // use those timestamps to calculate the info that should be
454 // reported to the user:
455 ti.calculate(swapchain.refresh_duration);
456 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700457 }
458 }
459 return num_ready;
460}
461
Ian Elliott8a977262017-01-19 09:05:58 -0700462void copy_ready_timings(Swapchain& swapchain,
463 uint32_t* count,
464 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800465 if (swapchain.timing.empty()) {
466 *count = 0;
467 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700468 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800469
470 size_t last_ready = swapchain.timing.size() - 1;
471 while (!swapchain.timing[last_ready].ready()) {
472 if (last_ready == 0) {
473 *count = 0;
474 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700475 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800476 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700477 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800478
479 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700480 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800481 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
482 const TimingInfo& ti = swapchain.timing[i];
483 if (ti.ready()) {
484 ti.get_values(&timings[num_copied]);
485 num_copied++;
486 }
487 num_to_remove++;
488 }
489
490 // Discard old frames that aren't ready if newer frames are ready.
491 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700492 swapchain.timing.erase(swapchain.timing.begin(),
493 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800494
Ian Elliott8a977262017-01-19 09:05:58 -0700495 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700496}
497
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500498android::PixelFormat GetNativePixelFormat(VkFormat format) {
499 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700500 switch (format) {
501 case VK_FORMAT_R8G8B8A8_UNORM:
502 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500503 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700504 break;
505 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500506 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700507 break;
508 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500509 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700510 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800511 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500512 native_format = android::PIXEL_FORMAT_RGBA_1010102;
513 break;
514 case VK_FORMAT_R8_UNORM:
515 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700516 break;
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000517 // TODO: Do we need to query for VK_EXT_rgba10x6_formats here?
518 case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
519 native_format = android::PIXEL_FORMAT_RGBA_10101010;
520 break;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700521 default:
522 ALOGV("unsupported swapchain format %d", format);
523 break;
524 }
525 return native_format;
526}
527
528android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
529 switch (colorspace) {
530 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
531 return HAL_DATASPACE_V0_SRGB;
532 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
533 return HAL_DATASPACE_DISPLAY_P3;
534 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
535 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600536 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
537 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700538 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
539 return HAL_DATASPACE_DCI_P3_LINEAR;
540 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
541 return HAL_DATASPACE_DCI_P3;
542 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
543 return HAL_DATASPACE_V0_SRGB_LINEAR;
544 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
545 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600546 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
547 return HAL_DATASPACE_BT2020_LINEAR;
548 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700549 return static_cast<android_dataspace>(
550 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
551 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600552 case VK_COLOR_SPACE_DOLBYVISION_EXT:
553 return static_cast<android_dataspace>(
554 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
555 HAL_DATASPACE_RANGE_FULL);
556 case VK_COLOR_SPACE_HDR10_HLG_EXT:
557 return static_cast<android_dataspace>(
558 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
559 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700560 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
561 return static_cast<android_dataspace>(
562 HAL_DATASPACE_STANDARD_ADOBE_RGB |
563 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
564 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
565 return HAL_DATASPACE_ADOBE_RGB;
566
567 // Pass through is intended to allow app to provide data that is passed
568 // to the display system without modification.
569 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
570 return HAL_DATASPACE_ARBITRARY;
571
572 default:
573 // This indicates that we don't know about the
574 // dataspace specified and we should indicate that
575 // it's unsupported
576 return HAL_DATASPACE_UNKNOWN;
577 }
578}
579
Jesse Halld7b994a2015-09-07 14:17:37 -0700580} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700581
Jesse Halle1b12782015-11-30 11:27:32 -0800582VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800583VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800584 VkInstance instance,
585 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
586 const VkAllocationCallbacks* allocator,
587 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800588 ATRACE_CALL();
589
Jesse Hall1f91d392015-12-11 16:28:44 -0800590 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800591 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800592 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
593 alignof(Surface),
594 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800595 if (!mem)
596 return VK_ERROR_OUT_OF_HOST_MEMORY;
597 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700598
Chia-I Wue8e689f2016-04-18 08:21:31 +0800599 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700600 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700601 int err = native_window_get_consumer_usage(surface->window.get(),
602 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800603 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700604 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
605 strerror(-err), err);
606 surface->~Surface();
607 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700608 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700609 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700610
Yiwei Zhang6435b322018-05-08 11:12:17 -0700611 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800612 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800613 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800614 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
615 err);
616 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800617 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700618 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800619 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700620
Jesse Hall1356b0d2015-11-23 17:24:58 -0800621 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700622 return VK_SUCCESS;
623}
624
Jesse Halle1b12782015-11-30 11:27:32 -0800625VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800626void DestroySurfaceKHR(VkInstance instance,
627 VkSurfaceKHR surface_handle,
628 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800629 ATRACE_CALL();
630
Jesse Hall1356b0d2015-11-23 17:24:58 -0800631 Surface* surface = SurfaceFromHandle(surface_handle);
632 if (!surface)
633 return;
634 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700635 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700636 "destroyed VkSurfaceKHR 0x%" PRIx64
637 " has active VkSwapchainKHR 0x%" PRIx64,
638 reinterpret_cast<uint64_t>(surface_handle),
639 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800640 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800641 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800642 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800643 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800644}
645
Jesse Halle1b12782015-11-30 11:27:32 -0800646VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800647VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
648 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000649 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800650 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000651 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800652 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800653}
654
Jesse Halle1b12782015-11-30 11:27:32 -0800655VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800656VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600657 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800658 VkSurfaceKHR surface,
659 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800660 ATRACE_CALL();
661
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000662 // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
663
664 VkPhysicalDeviceSurfaceInfo2KHR info2 = {
665 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
666 nullptr,
667 surface
668 };
669
670 VkSurfaceCapabilities2KHR caps2 = {
671 VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
672 nullptr,
673 {},
674 };
675
676 VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
677 *capabilities = caps2.surfaceCapabilities;
678 return result;
679}
680
681// Does the call-twice and VK_INCOMPLETE handling for querying lists
682// of things, where we already have the full set built in a vector.
683template <typename T>
684VkResult CopyWithIncomplete(std::vector<T> const& things,
685 T* callerPtr, uint32_t* callerCount) {
686 VkResult result = VK_SUCCESS;
687 if (callerPtr) {
688 if (things.size() > *callerCount)
689 result = VK_INCOMPLETE;
690 *callerCount = std::min(uint32_t(things.size()), *callerCount);
691 std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600692 } else {
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000693 *callerCount = things.size();
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800694 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000695 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700696}
697
Jesse Halle1b12782015-11-30 11:27:32 -0800698VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700699VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
700 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800701 uint32_t* count,
702 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800703 ATRACE_CALL();
704
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700705 const InstanceData& instance_data = GetData(pdev);
706
Ian Elliott1ce053f2022-03-16 09:49:53 -0600707 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000708 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600709 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600710 if (surface_handle == VK_NULL_HANDLE) {
711 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
712 bool surfaceless_enabled =
713 instance_data.hook_extensions.test(surfaceless);
714 if (!surfaceless_enabled) {
715 return VK_ERROR_SURFACE_LOST_KHR;
716 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300717 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600718
719 // TODO(b/203826952): research proper value; temporarily use the
720 // values seen on Pixel
721 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
722 } else {
723 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600724 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700725 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700726
Charlie Lao324191f2019-12-13 11:03:16 -0800727 AHardwareBuffer_Desc desc = {};
728 desc.width = 1;
729 desc.height = 1;
730 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600731 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800732 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
733
734 // We must support R8G8B8A8
735 std::vector<VkSurfaceFormatKHR> all_formats = {
736 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000737 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000738 };
Charlie Lao324191f2019-12-13 11:03:16 -0800739
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000740 if (colorspace_ext) {
741 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800742 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
743 all_formats.emplace_back(VkSurfaceFormatKHR{
744 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
745 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000746 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800747 all_formats.emplace_back(VkSurfaceFormatKHR{
748 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
749 all_formats.emplace_back(VkSurfaceFormatKHR{
750 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
751 }
752
Ian Elliott1ce053f2022-03-16 09:49:53 -0600753 // NOTE: Any new formats that are added must be coordinated across different
754 // Android users. This includes the ANGLE team (a layered implementation of
755 // OpenGL-ES).
756
Charlie Lao324191f2019-12-13 11:03:16 -0800757 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
758 if (AHardwareBuffer_isSupported(&desc)) {
759 all_formats.emplace_back(VkSurfaceFormatKHR{
760 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800761 if (colorspace_ext) {
762 all_formats.emplace_back(
763 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
764 VK_COLOR_SPACE_PASS_THROUGH_EXT});
765 }
Charlie Lao324191f2019-12-13 11:03:16 -0800766 }
767
768 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
769 if (AHardwareBuffer_isSupported(&desc)) {
770 all_formats.emplace_back(VkSurfaceFormatKHR{
771 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800772 if (colorspace_ext) {
773 all_formats.emplace_back(
774 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
775 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800776 all_formats.emplace_back(
777 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
778 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
779 all_formats.emplace_back(
780 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
781 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
782 }
783 }
784
785 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
786 if (AHardwareBuffer_isSupported(&desc)) {
787 all_formats.emplace_back(
788 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
789 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800790 if (colorspace_ext) {
791 all_formats.emplace_back(
792 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
793 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800794 all_formats.emplace_back(
795 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
796 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
797 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700798 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700799
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500800 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
801 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800802 if (colorspace_ext) {
803 all_formats.emplace_back(VkSurfaceFormatKHR{
804 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
805 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500806 }
807
Trevor David Black9cfe1ed2022-12-05 20:04:57 +0000808 // TODO query VK_EXT_rgba10x6_formats support
809 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
810 if (AHardwareBuffer_isSupported(&desc)) {
811 all_formats.emplace_back(
812 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
813 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
814 if (colorspace_ext) {
815 all_formats.emplace_back(
816 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
817 VK_COLOR_SPACE_PASS_THROUGH_EXT});
818 all_formats.emplace_back(
819 VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
820 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
821 }
822 }
823
Ian Elliott6ba85d92022-02-18 16:44:58 -0700824 // NOTE: Any new formats that are added must be coordinated across different
825 // Android users. This includes the ANGLE team (a layered implementation of
826 // OpenGL-ES).
827
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000828 return CopyWithIncomplete(all_formats, formats, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700829}
830
Jesse Halle1b12782015-11-30 11:27:32 -0800831VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300832VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
833 VkPhysicalDevice physicalDevice,
834 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
835 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800836 ATRACE_CALL();
837
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000838 auto surface = pSurfaceInfo->surface;
839 auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
Chris Forbes2452cf72017-03-16 16:30:17 +1300840
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000841 VkSurfacePresentModeEXT const *pPresentMode = nullptr;
842 for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
843 pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
844 switch (pNext->sType) {
845 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
846 pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
847 break;
Chris Forbes06bc0092017-03-16 16:46:05 +1300848
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000849 default:
850 break;
851 }
852 }
853
854 int err;
855 int width, height;
856 int transform_hint;
857 int max_buffer_count;
858 if (surface == VK_NULL_HANDLE) {
859 const InstanceData& instance_data = GetData(physicalDevice);
860 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
861 bool surfaceless_enabled =
862 instance_data.hook_extensions.test(surfaceless);
863 if (!surfaceless_enabled) {
864 // It is an error to pass a surface==VK_NULL_HANDLE unless the
865 // VK_GOOGLE_surfaceless_query extension is enabled
866 return VK_ERROR_SURFACE_LOST_KHR;
867 }
868 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
869 // extension for this function is for
870 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
871 // four values cannot be known without a surface. Default values will
872 // be supplied anyway, but cannot be relied upon.
873 width = 0xFFFFFFFF;
874 height = 0xFFFFFFFF;
875 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
876 capabilities->minImageCount = 0xFFFFFFFF;
877 capabilities->maxImageCount = 0xFFFFFFFF;
878 } else {
879 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
880
881 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
882 if (err != android::OK) {
883 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
884 strerror(-err), err);
885 return VK_ERROR_SURFACE_LOST_KHR;
886 }
887 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
888 if (err != android::OK) {
889 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
890 strerror(-err), err);
891 return VK_ERROR_SURFACE_LOST_KHR;
892 }
893
894 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
895 &transform_hint);
896 if (err != android::OK) {
897 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
898 strerror(-err), err);
899 return VK_ERROR_SURFACE_LOST_KHR;
900 }
901
902 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
903 &max_buffer_count);
904 if (err != android::OK) {
905 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
906 strerror(-err), err);
907 return VK_ERROR_SURFACE_LOST_KHR;
908 }
909
910 if (pPresentMode && IsSharedPresentMode(pPresentMode->presentMode)) {
911 capabilities->minImageCount = 1;
912 capabilities->maxImageCount = 1;
913 } else if (pPresentMode && pPresentMode->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
914 // TODO: use undequeued buffer requirement for more precise bound
915 capabilities->minImageCount = std::min(max_buffer_count, 4);
916 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
917 } else {
918 // TODO: if we're able to, provide better bounds on the number of buffers
919 // for other modes as well.
920 capabilities->minImageCount = std::min(max_buffer_count, 3);
921 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
922 }
923 }
924
925 capabilities->currentExtent =
926 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
927
928 // TODO(http://b/134182502): Figure out what the max extent should be.
929 capabilities->minImageExtent = VkExtent2D{1, 1};
930 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
931
932 if (capabilities->maxImageExtent.height <
933 capabilities->currentExtent.height) {
934 capabilities->maxImageExtent.height =
935 capabilities->currentExtent.height;
936 }
937
938 if (capabilities->maxImageExtent.width <
939 capabilities->currentExtent.width) {
940 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
941 }
942
943 capabilities->maxImageArrayLayers = 1;
944
945 capabilities->supportedTransforms = kSupportedTransforms;
946 capabilities->currentTransform =
947 TranslateNativeToVulkanTransform(transform_hint);
948
949 // On Android, window composition is a WindowManager property, not something
950 // associated with the bufferqueue. It can't be changed from here.
951 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
952
953 capabilities->supportedUsageFlags =
954 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
955 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
956 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
957 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
958
959 for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
960 pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
961
962 switch (pNext->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300963 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
964 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000965 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300966 // Claim same set of usage flags are supported for
967 // shared present modes as for other modes.
968 shared_caps->sharedPresentSupportedUsageFlags =
969 pSurfaceCapabilities->surfaceCapabilities
970 .supportedUsageFlags;
971 } break;
972
Ian Elliottbb67b242022-03-16 09:52:28 -0600973 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
974 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000975 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
Ian Elliottbb67b242022-03-16 09:52:28 -0600976 protected_caps->supportsProtected = VK_TRUE;
977 } break;
978
Chris Forbes9d0d9ff2022-12-28 01:58:31 +0000979 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
980 VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
981 reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
982 // By default, Android stretches the buffer to fit the window,
983 // without preserving aspect ratio. Other modes are technically possible
984 // but consult with CoGS team before exposing them here!
985 scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
986
987 // Since we always scale, we don't support any gravity.
988 scaling_caps->supportedPresentGravityX = 0;
989 scaling_caps->supportedPresentGravityY = 0;
990
991 // Scaled image limits are just the basic image limits
992 scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
993 scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
994 } break;
995
996 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
997 VkSurfacePresentModeCompatibilityEXT* mode_caps =
998 reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
999
1000 ALOG_ASSERT(pPresentMode,
1001 "querying VkSurfacePresentModeCompatibilityEXT "
1002 "requires VkSurfacePresentModeEXT to be provided");
1003 std::vector<VkPresentModeKHR> compatibleModes;
1004 compatibleModes.push_back(pPresentMode->presentMode);
1005
1006 switch (pPresentMode->presentMode) {
1007 // Shared modes are both compatible with each other.
1008 case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
1009 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
1010 break;
1011 case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
1012 compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1013 break;
1014 default:
1015 // Other modes are only compatible with themselves.
1016 // TODO: consider whether switching between FIFO and MAILBOX is reasonable
1017 break;
1018 }
1019
1020 // Note: this does not generate VK_INCOMPLETE since we're nested inside
1021 // a larger query and there would be no way to determine exactly where it came from.
1022 CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
1023 &mode_caps->presentModeCount);
1024 } break;
1025
Chris Forbes06bc0092017-03-16 16:46:05 +13001026 default:
1027 // Ignore all other extension structs
1028 break;
1029 }
1030 }
1031
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001032 return VK_SUCCESS;
Chris Forbes2452cf72017-03-16 16:30:17 +13001033}
1034
1035VKAPI_ATTR
1036VkResult GetPhysicalDeviceSurfaceFormats2KHR(
1037 VkPhysicalDevice physicalDevice,
1038 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
1039 uint32_t* pSurfaceFormatCount,
1040 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001041 ATRACE_CALL();
1042
Chris Forbes2452cf72017-03-16 16:30:17 +13001043 if (!pSurfaceFormats) {
1044 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
1045 pSurfaceInfo->surface,
1046 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +00001047 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001048
Trevor David Black929e9cd2022-11-22 04:12:19 +00001049 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
1050 // after the call.
1051 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
1052 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
1053 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
1054 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +00001055
Trevor David Black929e9cd2022-11-22 04:12:19 +00001056 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
1057 return result;
1058 }
Trevor David Black2cc44682022-03-09 00:31:38 +00001059
Trevor David Black929e9cd2022-11-22 04:12:19 +00001060 const auto& driver = GetData(physicalDevice).driver;
1061
1062 // marshal results individually due to stride difference.
1063 uint32_t formats_to_marshal = *pSurfaceFormatCount;
1064 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
1065 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
1066
1067 // Query the compression properties for the surface format
1068 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
1069 while (pSurfaceFormat->pNext) {
1070 pSurfaceFormat =
1071 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
1072 switch (pSurfaceFormat->sType) {
1073 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +00001074 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
1075 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +00001076 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +00001077
1078 if (surfaceCompressionProps &&
1079 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
1080 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
1081 imageFormatInfo.sType =
1082 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
1083 imageFormatInfo.format =
1084 pSurfaceFormats[i].surfaceFormat.format;
1085 imageFormatInfo.pNext = nullptr;
1086
1087 VkImageCompressionControlEXT compressionControl = {};
1088 compressionControl.sType =
1089 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
1090 compressionControl.pNext = imageFormatInfo.pNext;
1091
1092 imageFormatInfo.pNext = &compressionControl;
1093
1094 VkImageCompressionPropertiesEXT compressionProps = {};
1095 compressionProps.sType =
1096 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
1097 compressionProps.pNext = nullptr;
1098
1099 VkImageFormatProperties2KHR imageFormatProps = {};
1100 imageFormatProps.sType =
1101 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
1102 imageFormatProps.pNext = &compressionProps;
1103
1104 VkResult compressionRes =
1105 driver.GetPhysicalDeviceImageFormatProperties2KHR(
1106 physicalDevice, &imageFormatInfo,
1107 &imageFormatProps);
1108 if (compressionRes == VK_SUCCESS) {
1109 surfaceCompressionProps->imageCompressionFlags =
1110 compressionProps.imageCompressionFlags;
1111 surfaceCompressionProps
1112 ->imageCompressionFixedRateFlags =
1113 compressionProps.imageCompressionFixedRateFlags;
1114 } else {
1115 return compressionRes;
1116 }
1117 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001118 } break;
1119
1120 default:
1121 // Ignore all other extension structs
1122 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001123 }
1124 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001125 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001126
1127 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001128}
1129
1130VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001131VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001132 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001133 uint32_t* count,
1134 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001135 ATRACE_CALL();
1136
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001137 int err;
1138 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001139 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001140 if (surface == VK_NULL_HANDLE) {
1141 const InstanceData& instance_data = GetData(pdev);
1142 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1143 bool surfaceless_enabled =
1144 instance_data.hook_extensions.test(surfaceless);
1145 if (!surfaceless_enabled) {
1146 return VK_ERROR_SURFACE_LOST_KHR;
1147 }
1148 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1149 // extension for this function is for
1150 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1151 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1152 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001153 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001154 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1155 } else {
1156 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1157
1158 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1159 &query_value);
1160 if (err != android::OK || query_value < 0) {
1161 ALOGE(
1162 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1163 "value=%d",
1164 strerror(-err), err, query_value);
1165 return VK_ERROR_SURFACE_LOST_KHR;
1166 }
1167 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1168
1169 err =
1170 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1171 if (err != android::OK || query_value < 0) {
1172 ALOGE(
1173 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1174 strerror(-err), err, query_value);
1175 return VK_ERROR_SURFACE_LOST_KHR;
1176 }
1177 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1178
1179 if (min_undequeued_buffers + 1 < max_buffer_count)
1180 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1181 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1182 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001183
1184 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001185 QueryPresentationProperties(pdev, &present_properties);
1186 if (present_properties.sharedImage) {
1187 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1188 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001189 }
1190
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001191 return CopyWithIncomplete(present_modes, modes, count);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001192}
1193
Jesse Halle1b12782015-11-30 11:27:32 -08001194VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001195VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001196 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001197 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001198 ATRACE_CALL();
1199
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001200 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1201 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1202 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1203 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1204 pDeviceGroupPresentCapabilities->sType);
1205
1206 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1207 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1208
1209 // assume device group of size 1
1210 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1211 pDeviceGroupPresentCapabilities->modes =
1212 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1213
1214 return VK_SUCCESS;
1215}
1216
1217VKAPI_ATTR
1218VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001219 VkDevice,
1220 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001221 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001222 ATRACE_CALL();
1223
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001224 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1225 return VK_SUCCESS;
1226}
1227
1228VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001229VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001230 VkSurfaceKHR surface,
1231 uint32_t* pRectCount,
1232 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001233 ATRACE_CALL();
1234
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001235 if (!pRects) {
1236 *pRectCount = 1;
1237 } else {
1238 uint32_t count = std::min(*pRectCount, 1u);
1239 bool incomplete = *pRectCount < 1;
1240
1241 *pRectCount = count;
1242
1243 if (incomplete) {
1244 return VK_INCOMPLETE;
1245 }
1246
1247 int err;
1248 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1249
1250 int width = 0, height = 0;
1251 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001252 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001253 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1254 strerror(-err), err);
1255 }
1256 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001257 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001258 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1259 strerror(-err), err);
1260 }
1261
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001262 pRects[0].offset.x = 0;
1263 pRects[0].offset.y = 0;
1264 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1265 static_cast<uint32_t>(height)};
1266 }
1267 return VK_SUCCESS;
1268}
1269
Yiwei Zhang533cea92019-06-03 18:43:24 -07001270static void DestroySwapchainInternal(VkDevice device,
1271 VkSwapchainKHR swapchain_handle,
1272 const VkAllocationCallbacks* allocator) {
1273 ATRACE_CALL();
1274
1275 const auto& dispatch = GetData(device).driver;
1276 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1277 if (!swapchain) {
1278 return;
1279 }
1280
1281 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1282 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1283
1284 if (window && swapchain->frame_timestamps_enabled) {
1285 native_window_enable_frame_timestamps(window, false);
1286 }
1287
1288 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001289 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1290 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001291 }
1292
1293 if (active) {
1294 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1295 }
1296
1297 if (!allocator) {
1298 allocator = &GetData(device).allocator;
1299 }
1300
1301 swapchain->~Swapchain();
1302 allocator->pfnFree(allocator->pUserData, swapchain);
1303}
1304
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001305VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001306VkResult CreateSwapchainKHR(VkDevice device,
1307 const VkSwapchainCreateInfoKHR* create_info,
1308 const VkAllocationCallbacks* allocator,
1309 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001310 ATRACE_CALL();
1311
Jesse Halld7b994a2015-09-07 14:17:37 -07001312 int err;
1313 VkResult result = VK_SUCCESS;
1314
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001315 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1316 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1317 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1318 " oldSwapchain=0x%" PRIx64,
1319 reinterpret_cast<uint64_t>(create_info->surface),
1320 create_info->minImageCount, create_info->imageFormat,
1321 create_info->imageColorSpace, create_info->imageExtent.width,
1322 create_info->imageExtent.height, create_info->imageUsage,
1323 create_info->preTransform, create_info->presentMode,
1324 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1325
Jesse Hall1f91d392015-12-11 16:28:44 -08001326 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001327 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001328
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001329 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001330 GetNativePixelFormat(create_info->imageFormat);
1331 android_dataspace native_dataspace =
1332 GetNativeDataspace(create_info->imageColorSpace);
1333 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1334 ALOGE(
1335 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1336 "failed: Unsupported color space",
1337 create_info->imageColorSpace);
1338 return VK_ERROR_INITIALIZATION_FAILED;
1339 }
1340
Jesse Hall42a9eec2016-06-03 12:39:49 -07001341 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001342 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001343 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001344 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001345 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001346 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001347 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001348 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001349 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1350 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001351 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001352 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001353
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001354 Surface& surface = *SurfaceFromHandle(create_info->surface);
1355
Jesse Halldc225072016-05-30 22:40:14 -07001356 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001357 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001358 " because it already has active swapchain 0x%" PRIx64
1359 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1360 reinterpret_cast<uint64_t>(create_info->surface),
1361 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1362 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1363 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1364 }
1365 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1366 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1367
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001368 // -- Reset the native window --
1369 // The native window might have been used previously, and had its properties
1370 // changed from defaults. That will affect the answer we get for queries
1371 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1372 // attempt such queries.
1373
Jesse Halldc225072016-05-30 22:40:14 -07001374 // The native window only allows dequeueing all buffers before any have
1375 // been queued, since after that point at least one is assumed to be in
1376 // non-FREE state at any given time. Disconnecting and re-connecting
1377 // orphans the previous buffers, getting us back to the state where we can
1378 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001379 //
1380 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001381 ANativeWindow* window = surface.window.get();
1382 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1383 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001384 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001385 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1386 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001387 strerror(-err), err);
1388
Nicolas Capens147b7da2021-04-09 14:53:06 -04001389 err =
1390 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001391 if (err != android::OK) {
1392 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1393 strerror(-err), err);
1394 return VK_ERROR_SURFACE_LOST_KHR;
1395 }
1396
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301397 int swap_interval =
1398 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001399 err = window->setSwapInterval(window, swap_interval);
1400 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001401 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1402 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001403 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001404 }
1405
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001406 err = native_window_set_shared_buffer_mode(window, false);
1407 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001408 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1409 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001410 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001411 }
1412
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001413 err = native_window_set_auto_refresh(window, false);
1414 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001415 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1416 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001417 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001418 }
1419
Jesse Halld7b994a2015-09-07 14:17:37 -07001420 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001421
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001422 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001423
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001424 err = native_window_set_buffers_format(window, native_pixel_format);
1425 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001426 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1427 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001428 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001429 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001430
1431 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1432 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1433 err = native_window_set_buffers_data_space(window, native_dataspace);
1434 if (err != android::OK) {
1435 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1436 native_dataspace, strerror(-err), err);
1437 return VK_ERROR_SURFACE_LOST_KHR;
1438 }
Jesse Hall517274a2016-02-10 00:07:18 -08001439 }
1440
Jesse Hall3dd678a2016-01-08 21:52:01 -08001441 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001442 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001443 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001444 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001445 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1446 create_info->imageExtent.width, create_info->imageExtent.height,
1447 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001448 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001449 }
1450
Jesse Hall178b6962016-02-24 15:39:50 -08001451 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1452 // applied during rendering. native_window_set_transform() expects the
1453 // inverse: the transform the app is requesting that the compositor perform
1454 // during composition. With native windows, pre-transform works by rendering
1455 // with the same transform the compositor is applying (as in Vulkan), but
1456 // then requesting the inverse transform, so that when the compositor does
1457 // it's job the two transforms cancel each other out and the compositor ends
1458 // up applying an identity transform to the app's buffer.
1459 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001460 window, InvertTransformToNative(create_info->preTransform));
1461 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001462 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1463 InvertTransformToNative(create_info->preTransform),
1464 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001465 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001466 }
1467
Jesse Hallf64ca122015-11-03 16:11:10 -08001468 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001469 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1470 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001471 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1472 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001473 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001474 }
1475
Chris Forbes97ef4612017-03-30 19:37:50 +13001476 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001477 if (IsSharedPresentMode(create_info->presentMode)) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001478 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001479 err = native_window_set_shared_buffer_mode(window, true);
1480 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001481 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1482 return VK_ERROR_SURFACE_LOST_KHR;
1483 }
1484 }
1485
1486 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001487 err = native_window_set_auto_refresh(window, true);
1488 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001489 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1490 return VK_ERROR_SURFACE_LOST_KHR;
1491 }
1492 }
1493
Ian Elliott16c443c2021-11-30 17:10:32 -07001494 int query_value;
1495 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1496 &query_value);
1497 if (err != android::OK || query_value < 0) {
1498 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1499 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001500 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001501 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001502 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1503 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1504 const auto requested_images =
1505 swap_interval ? create_info->minImageCount : mailbox_num_images;
1506 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001507
Ian Elliott5396b702021-12-13 19:32:34 -07001508 // Lower layer insists that we have at least min_undequeued_buffers + 1
1509 // buffers. This is wasteful and we'd like to relax it in the shared case,
1510 // but not all the pieces are in place for that to work yet. Note we only
1511 // lie to the lower layer--we don't want to give the app back a swapchain
1512 // with extra images (which they can't actually use!).
1513 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1514 err = native_window_set_buffer_count(
1515 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001516 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001517 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1518 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001519 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001520 }
1521
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001522 // In shared mode the num_images must be one regardless of how many
1523 // buffers were allocated for the buffer queue.
1524 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1525 num_images = 1;
1526 }
1527
Trevor David Black2cc44682022-03-09 00:31:38 +00001528 void* usage_info_pNext = nullptr;
1529 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001530 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001531 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1532 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1533 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1534 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1535 gralloc_usage_info.format = create_info->imageFormat;
1536 gralloc_usage_info.imageUsage = create_info->imageUsage;
1537
1538 // Look through the pNext chain for an image compression control struct
1539 // if one is found AND the appropriate extensions are enabled,
1540 // append it to be the gralloc usage pNext chain
1541 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1542 while (create_infos->pNext) {
1543 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1544 create_infos->pNext);
1545 switch (create_infos->sType) {
1546 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1547 const VkImageCompressionControlEXT* compression_infos =
1548 reinterpret_cast<const VkImageCompressionControlEXT*>(
1549 create_infos);
1550 image_compression = *compression_infos;
1551 image_compression.pNext = nullptr;
1552 usage_info_pNext = &image_compression;
1553 } break;
1554
1555 default:
1556 // Ignore all other info structs
1557 break;
1558 }
1559 }
1560 gralloc_usage_info.pNext = usage_info_pNext;
1561
1562 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1563 device, &gralloc_usage_info, &native_usage);
1564 ATRACE_END();
1565 if (result != VK_SUCCESS) {
1566 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1567 return VK_ERROR_SURFACE_LOST_KHR;
1568 }
1569 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001570 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001571 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001572 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1573 device, create_info->imageFormat, create_info->imageUsage,
1574 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001575 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001576 if (result != VK_SUCCESS) {
1577 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001578 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001579 }
John Reck97678d42022-08-23 11:24:51 -04001580 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001581 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001582 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001583 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001584 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001585 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001586 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001587 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001588 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001589 if (result != VK_SUCCESS) {
1590 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001591 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001592 }
John Reck97678d42022-08-23 11:24:51 -04001593 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001594 }
John Reck97678d42022-08-23 11:24:51 -04001595 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001596
1597 bool createProtectedSwapchain = false;
1598 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1599 createProtectedSwapchain = true;
1600 native_usage |= BufferUsage::PROTECTED;
1601 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001602 err = native_window_set_usage(window, native_usage);
1603 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001604 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001605 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001606 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001607
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001608 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001609 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1610 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001611 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1612 strerror(-err), err);
1613 return VK_ERROR_SURFACE_LOST_KHR;
1614 }
1615
Jesse Halld7b994a2015-09-07 14:17:37 -07001616 // -- Allocate our Swapchain object --
1617 // After this point, we must deallocate the swapchain on error.
1618
Jesse Hall1f91d392015-12-11 16:28:44 -08001619 void* mem = allocator->pfnAllocation(allocator->pUserData,
1620 sizeof(Swapchain), alignof(Swapchain),
1621 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001622 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001623 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001624 Swapchain* swapchain = new (mem)
1625 Swapchain(surface, num_images, create_info->presentMode,
1626 TranslateVulkanToNativeTransform(create_info->preTransform));
Jesse Halld7b994a2015-09-07 14:17:37 -07001627
Chris Forbesb56287a2017-01-12 14:28:58 +13001628 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1629#pragma clang diagnostic push
1630#pragma clang diagnostic ignored "-Wold-style-cast"
1631 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1632#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001633 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001634 .usage = swapchain_image_usage,
1635 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001636 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001637#pragma clang diagnostic push
1638#pragma clang diagnostic ignored "-Wold-style-cast"
1639 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1640#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001641 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001642 };
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001643
Jesse Halld7b994a2015-09-07 14:17:37 -07001644 VkImageCreateInfo image_create = {
1645 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001646 .pNext = nullptr,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001647 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001648 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001649 .format = create_info->imageFormat,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001650 .extent = {
1651 create_info->imageExtent.width,
1652 create_info->imageExtent.height,
1653 1
1654 },
Jesse Halld7b994a2015-09-07 14:17:37 -07001655 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001656 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001657 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001658 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001659 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001660 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001661 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001662 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1663 };
1664
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001665 // Note: don't do deferred allocation for shared present modes. There's only one buffer
1666 // involved so very little benefit.
1667 if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
1668 !IsSharedPresentMode(create_info->presentMode)) {
1669 // Don't want to touch the underlying gralloc buffers yet;
1670 // instead just create unbound VkImages which will later be bound to memory inside
1671 // AcquireNextImage.
1672 VkImageSwapchainCreateInfoKHR image_swapchain_create = {
1673 .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
1674 .pNext = nullptr,
1675 .swapchain = HandleFromSwapchain(swapchain),
1676 };
1677 image_create.pNext = &image_swapchain_create;
Jesse Halld7b994a2015-09-07 14:17:37 -07001678
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001679 for (uint32_t i = 0; i < num_images; i++) {
1680 Swapchain::Image& img = swapchain->images[i];
1681 img.buffer = nullptr;
1682 img.dequeued = false;
1683
1684 result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1685 if (result != VK_SUCCESS) {
1686 ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
1687 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001688 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001689 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001690 } else {
1691 // -- Dequeue all buffers and create a VkImage for each --
1692 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001693
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001694 for (uint32_t i = 0; i < num_images; i++) {
1695 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001696
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001697 ANativeWindowBuffer* buffer;
1698 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1699 if (err != android::OK) {
1700 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1701 switch (-err) {
1702 case ENOMEM:
1703 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1704 break;
1705 default:
1706 result = VK_ERROR_SURFACE_LOST_KHR;
1707 break;
1708 }
1709 break;
1710 }
1711 img.buffer = buffer;
1712 img.dequeued = true;
1713
1714 image_native_buffer.handle = img.buffer->handle;
1715 image_native_buffer.stride = img.buffer->stride;
1716 image_native_buffer.format = img.buffer->format;
1717 image_native_buffer.usage = int(img.buffer->usage);
1718 android_convertGralloc0To1Usage(int(img.buffer->usage),
1719 &image_native_buffer.usage2.producer,
1720 &image_native_buffer.usage2.consumer);
1721 image_native_buffer.usage3 = img.buffer->usage;
1722 image_create.pNext = &image_native_buffer;
1723
1724 ATRACE_BEGIN("CreateImage");
1725 result =
1726 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1727 ATRACE_END();
1728 if (result != VK_SUCCESS) {
1729 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1730 break;
1731 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001732 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001733
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001734 // -- Cancel all buffers, returning them to the queue --
1735 // If an error occurred before, also destroy the VkImage and release the
1736 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1737 for (uint32_t i = 0; i < num_images; i++) {
1738 Swapchain::Image& img = swapchain->images[i];
1739 if (img.dequeued) {
1740 if (!swapchain->shared) {
1741 window->cancelBuffer(window, img.buffer.get(),
1742 img.dequeue_fence);
1743 img.dequeue_fence = -1;
1744 img.dequeued = false;
1745 }
Chris Forbese0ced032017-03-30 19:44:15 +13001746 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001747 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001748 }
1749
1750 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001751 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1752 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001753 return result;
1754 }
1755
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001756 if (transform_hint != swapchain->pre_transform) {
1757 // Log that the app is not doing pre-rotation.
1758 android::GraphicsEnv::getInstance().setTargetStats(
1759 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1760 }
1761
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001762 // Set stats for creating a Vulkan swapchain
1763 android::GraphicsEnv::getInstance().setTargetStats(
1764 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1765
Jesse Halldc225072016-05-30 22:40:14 -07001766 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1767 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001768 return VK_SUCCESS;
1769}
1770
Jesse Halle1b12782015-11-30 11:27:32 -08001771VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001772void DestroySwapchainKHR(VkDevice device,
1773 VkSwapchainKHR swapchain_handle,
1774 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001775 ATRACE_CALL();
1776
Yiwei Zhang533cea92019-06-03 18:43:24 -07001777 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001778}
1779
Jesse Halle1b12782015-11-30 11:27:32 -08001780VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001781VkResult GetSwapchainImagesKHR(VkDevice,
1782 VkSwapchainKHR swapchain_handle,
1783 uint32_t* count,
1784 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001785 ATRACE_CALL();
1786
Jesse Halld7b994a2015-09-07 14:17:37 -07001787 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001788 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1789 "getting images for non-active swapchain 0x%" PRIx64
1790 "; only dequeued image handles are valid",
1791 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001792 VkResult result = VK_SUCCESS;
1793 if (images) {
1794 uint32_t n = swapchain.num_images;
1795 if (*count < swapchain.num_images) {
1796 n = *count;
1797 result = VK_INCOMPLETE;
1798 }
1799 for (uint32_t i = 0; i < n; i++)
1800 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001801 *count = n;
1802 } else {
1803 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001804 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001805 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001806}
1807
Jesse Halle1b12782015-11-30 11:27:32 -08001808VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001809VkResult AcquireNextImageKHR(VkDevice device,
1810 VkSwapchainKHR swapchain_handle,
1811 uint64_t timeout,
1812 VkSemaphore semaphore,
1813 VkFence vk_fence,
1814 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001815 ATRACE_CALL();
1816
Jesse Halld7b994a2015-09-07 14:17:37 -07001817 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001818 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001819 VkResult result;
1820 int err;
1821
Jesse Halldc225072016-05-30 22:40:14 -07001822 if (swapchain.surface.swapchain_handle != swapchain_handle)
1823 return VK_ERROR_OUT_OF_DATE_KHR;
1824
Chris Forbesc88409c2017-03-30 19:47:37 +13001825 if (swapchain.shared) {
1826 // In shared mode, we keep the buffer dequeued all the time, so we don't
1827 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1828 // the semaphore and fence passed to us will be signalled.
1829 *image_index = 0;
1830 result = GetData(device).driver.AcquireImageANDROID(
1831 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1832 return result;
1833 }
1834
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001835 const nsecs_t acquire_next_image_timeout =
1836 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1837 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1838 // Cache the timeout to avoid the duplicate binder cost.
1839 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1840 acquire_next_image_timeout);
1841 if (err != android::OK) {
1842 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1843 strerror(-err), err);
1844 return VK_ERROR_SURFACE_LOST_KHR;
1845 }
1846 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1847 }
1848
Jesse Halld7b994a2015-09-07 14:17:37 -07001849 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001850 int fence_fd;
1851 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001852 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001853 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1854 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1855 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001856 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001857 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001858 }
1859
1860 uint32_t idx;
1861 for (idx = 0; idx < swapchain.num_images; idx++) {
1862 if (swapchain.images[idx].buffer.get() == buffer) {
1863 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001864 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001865 break;
1866 }
1867 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00001868
1869 // If this is a deferred alloc swapchain, this may be the first time we've
1870 // seen a particular buffer. If so, there should be an empty slot. Find it,
1871 // and bind the gralloc buffer to the VkImage for that slot. If there is no
1872 // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
1873 // will also take this path, but will never have an empty slot since we
1874 // populated them all upfront.
1875 if (idx == swapchain.num_images) {
1876 for (idx = 0; idx < swapchain.num_images; idx++) {
1877 if (!swapchain.images[idx].buffer) {
1878 // Note: this structure is technically required for
1879 // Vulkan correctness, even though the driver is probably going
1880 // to use everything from the VkNativeBufferANDROID below.
1881 // This is kindof silly, but it's how we did the ANB
1882 // side of VK_KHR_swapchain v69, so we're stuck with it unless
1883 // we want to go tinkering with the ANB spec some more.
1884 VkBindImageMemorySwapchainInfoKHR bimsi = {
1885 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
1886 .pNext = nullptr,
1887 .swapchain = swapchain_handle,
1888 .imageIndex = idx,
1889 };
1890 VkNativeBufferANDROID nb = {
1891 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1892 .pNext = &bimsi,
1893 .handle = buffer->handle,
1894 .stride = buffer->stride,
1895 .format = buffer->format,
1896 .usage = int(buffer->usage),
1897 };
1898 VkBindImageMemoryInfo bimi = {
1899 .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
1900 .pNext = &nb,
1901 .image = swapchain.images[idx].image,
1902 .memory = VK_NULL_HANDLE,
1903 .memoryOffset = 0,
1904 };
1905 result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
1906 if (result != VK_SUCCESS) {
1907 // This shouldn't really happen. If it does, something is probably
1908 // unrecoverably wrong with the swapchain and its images. Cancel
1909 // the buffer and declare the swapchain broken.
1910 ALOGE("failed to do deferred gralloc buffer bind");
1911 window->cancelBuffer(window, buffer, fence_fd);
1912 return VK_ERROR_OUT_OF_DATE_KHR;
1913 }
1914
1915 swapchain.images[idx].dequeued = true;
1916 swapchain.images[idx].dequeue_fence = fence_fd;
1917 swapchain.images[idx].buffer = buffer;
1918 break;
1919 }
1920 }
1921 }
1922
1923 // The buffer doesn't match any slot. This shouldn't normally happen, but is
1924 // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
1925 // happens, just declare the swapchain to be broken and the app will recreate it.
Jesse Halld7b994a2015-09-07 14:17:37 -07001926 if (idx == swapchain.num_images) {
1927 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001928 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001929 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001930 }
1931
1932 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001933 if (fence_fd != -1) {
1934 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001935 if (fence_clone == -1) {
1936 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1937 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001938 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001939 }
1940 }
1941
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001942 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001943 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001944 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001945 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1946 // even if the call fails. We could close it ourselves on failure, but
1947 // that would create a race condition if the driver closes it on a
1948 // failure path: some other thread might create an fd with the same
1949 // number between the time the driver closes it and the time we close
1950 // it. We must assume one of: the driver *always* closes it even on
1951 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001952 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001953 swapchain.images[idx].dequeued = false;
1954 swapchain.images[idx].dequeue_fence = -1;
1955 return result;
1956 }
1957
1958 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001959 return VK_SUCCESS;
1960}
1961
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001962VKAPI_ATTR
1963VkResult AcquireNextImage2KHR(VkDevice device,
1964 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1965 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001966 ATRACE_CALL();
1967
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001968 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1969 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1970 pAcquireInfo->fence, pImageIndex);
1971}
1972
Jesse Halldc225072016-05-30 22:40:14 -07001973static VkResult WorstPresentResult(VkResult a, VkResult b) {
1974 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1975 // (in spec version 1.0.14).
1976 static const VkResult kWorstToBest[] = {
1977 VK_ERROR_DEVICE_LOST,
1978 VK_ERROR_SURFACE_LOST_KHR,
1979 VK_ERROR_OUT_OF_DATE_KHR,
1980 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1981 VK_ERROR_OUT_OF_HOST_MEMORY,
1982 VK_SUBOPTIMAL_KHR,
1983 };
1984 for (auto result : kWorstToBest) {
1985 if (a == result || b == result)
1986 return result;
1987 }
1988 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1989 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1990 return a != VK_SUCCESS ? a : b;
1991}
1992
Chris Forbes4cd01fb2022-10-19 11:35:16 +13001993// KHR_incremental_present aspect of QueuePresentKHR
1994static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
1995 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
1996 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
1997 auto const& rect = pRegion->pRectangles[i];
1998 if (rect.layer > 0) {
1999 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
2000 rect.layer);
2001 }
2002
2003 rects[i].left = rect.offset.x;
2004 rects[i].bottom = rect.offset.y;
2005 rects[i].right = rect.offset.x + rect.extent.width;
2006 rects[i].top = rect.offset.y + rect.extent.height;
2007 }
2008 native_window_set_surface_damage(window, rects.data(), rects.size());
2009}
2010
2011// GOOGLE_display_timing aspect of QueuePresentKHR
2012static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
2013 ANativeWindow *window = swapchain.surface.window.get();
2014
2015 // We don't know whether the app will actually use GOOGLE_display_timing
2016 // with a particular swapchain until QueuePresent; enable it on the BQ
2017 // now if needed
2018 if (!swapchain.frame_timestamps_enabled) {
2019 ALOGV("Calling native_window_enable_frame_timestamps(true)");
2020 native_window_enable_frame_timestamps(window, true);
2021 swapchain.frame_timestamps_enabled = true;
2022 }
2023
2024 // Record the nativeFrameId so it can be later correlated to
2025 // this present.
2026 uint64_t nativeFrameId = 0;
2027 int err = native_window_get_next_frame_id(
2028 window, &nativeFrameId);
2029 if (err != android::OK) {
2030 ALOGE("Failed to get next native frame ID.");
2031 }
2032
2033 // Add a new timing record with the user's presentID and
2034 // the nativeFrameId.
2035 swapchain.timing.emplace_back(pTime, nativeFrameId);
2036 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
2037 swapchain.timing.erase(
2038 swapchain.timing.begin(),
2039 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
2040 }
2041 if (pTime->desiredPresentTime) {
2042 ALOGV(
2043 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
2044 pTime->desiredPresentTime);
2045 native_window_set_buffers_timestamp(
2046 window,
2047 static_cast<int64_t>(pTime->desiredPresentTime));
2048 }
2049}
2050
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002051// EXT_swapchain_maintenance1 present mode change
2052static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
2053 // There is no dynamic switching between non-shared present modes.
2054 // All we support is switching between demand and continuous refresh.
2055 if (!IsSharedPresentMode(mode))
2056 return true;
2057
2058 int err = native_window_set_auto_refresh(window,
2059 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
2060 if (err != android::OK) {
2061 ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
2062 strerror(-err), err);
2063 return false;
2064 }
2065
2066 return true;
2067}
2068
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002069static VkResult PresentOneSwapchain(
2070 VkQueue queue,
2071 Swapchain& swapchain,
2072 uint32_t imageIndex,
2073 const VkPresentRegionKHR *pRegion,
2074 const VkPresentTimeGOOGLE *pTime,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002075 VkFence presentFence,
2076 const VkPresentModeKHR *pPresentMode,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002077 uint32_t waitSemaphoreCount,
2078 const VkSemaphore *pWaitSemaphores) {
2079
2080 VkDevice device = GetData(queue).driver_device;
2081 const auto& dispatch = GetData(queue).driver;
2082
2083 Swapchain::Image& img = swapchain.images[imageIndex];
2084 VkResult swapchain_result = VK_SUCCESS;
2085 VkResult result;
2086 int err;
2087
2088 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
2089 // wait semaphores, so this doesn't actually work for the multiple swapchain
2090 // case.
2091 int fence = -1;
2092 result = dispatch.QueueSignalReleaseImageANDROID(
2093 queue, waitSemaphoreCount,
2094 pWaitSemaphores, img.image, &fence);
2095 if (result != VK_SUCCESS) {
2096 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
2097 swapchain_result = result;
2098 }
2099 if (img.release_fence >= 0)
2100 close(img.release_fence);
2101 img.release_fence = fence < 0 ? -1 : dup(fence);
2102
2103 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
2104 ANativeWindow* window = swapchain.surface.window.get();
2105 if (swapchain_result == VK_SUCCESS) {
2106
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002107 if (presentFence != VK_NULL_HANDLE) {
2108 int fence_copy = fence < 0 ? -1 : dup(fence);
2109 VkImportFenceFdInfoKHR iffi = {
2110 VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
2111 nullptr,
2112 presentFence,
2113 VK_FENCE_IMPORT_TEMPORARY_BIT,
2114 VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
2115 fence_copy,
2116 };
2117 if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
2118 // ImportFenceFdKHR takes ownership only if it succeeds
2119 close(fence_copy);
2120 }
2121 }
2122
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002123 if (pRegion) {
2124 SetSwapchainSurfaceDamage(window, pRegion);
2125 }
2126 if (pTime) {
2127 SetSwapchainFrameTimestamp(swapchain, pTime);
2128 }
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002129 if (pPresentMode) {
2130 if (!SetSwapchainPresentMode(window, *pPresentMode))
2131 swapchain_result = WorstPresentResult(swapchain_result,
2132 VK_ERROR_SURFACE_LOST_KHR);
2133 }
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002134
2135 err = window->queueBuffer(window, img.buffer.get(), fence);
2136 // queueBuffer always closes fence, even on error
2137 if (err != android::OK) {
2138 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
2139 swapchain_result = WorstPresentResult(
2140 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2141 } else {
2142 if (img.dequeue_fence >= 0) {
2143 close(img.dequeue_fence);
2144 img.dequeue_fence = -1;
2145 }
2146 img.dequeued = false;
2147 }
2148
2149 // If the swapchain is in shared mode, immediately dequeue the
2150 // buffer so it can be presented again without an intervening
2151 // call to AcquireNextImageKHR. We expect to get the same buffer
2152 // back from every call to dequeueBuffer in this mode.
2153 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
2154 ANativeWindowBuffer* buffer;
2155 int fence_fd;
2156 err = window->dequeueBuffer(window, &buffer, &fence_fd);
2157 if (err != android::OK) {
2158 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
2159 swapchain_result = WorstPresentResult(swapchain_result,
2160 VK_ERROR_SURFACE_LOST_KHR);
2161 } else if (img.buffer != buffer) {
2162 ALOGE("got wrong image back for shared swapchain");
2163 swapchain_result = WorstPresentResult(swapchain_result,
2164 VK_ERROR_SURFACE_LOST_KHR);
2165 } else {
2166 img.dequeue_fence = fence_fd;
2167 img.dequeued = true;
2168 }
2169 }
2170 }
2171 if (swapchain_result != VK_SUCCESS) {
2172 OrphanSwapchain(device, &swapchain);
2173 }
2174 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
2175 // and only when the window's transform/rotation changes. Extent
2176 // changes will not cause VK_SUBOPTIMAL_KHR because of the
2177 // application issues that were caused when the following transform
2178 // change was added.
2179 int window_transform_hint;
2180 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
2181 &window_transform_hint);
2182 if (err != android::OK) {
2183 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
2184 strerror(-err), err);
2185 swapchain_result = WorstPresentResult(
2186 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
2187 }
2188 if (swapchain.pre_transform != window_transform_hint) {
2189 swapchain_result =
2190 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
2191 }
2192 } else {
2193 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
2194 img, true);
2195 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
2196 }
2197
2198 return swapchain_result;
2199}
2200
Jesse Halle1b12782015-11-30 11:27:32 -08002201VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08002202VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002203 ATRACE_CALL();
2204
Jesse Halld7b994a2015-09-07 14:17:37 -07002205 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
2206 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
2207 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07002208
Jesse Halld7b994a2015-09-07 14:17:37 -07002209 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07002210
Ian Elliottcb351132016-12-13 10:30:40 -07002211 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002212 const VkPresentRegionsKHR* present_regions = nullptr;
2213 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002214 const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
2215 const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
2216
Ian Elliottcb351132016-12-13 10:30:40 -07002217 const VkPresentRegionsKHR* next =
2218 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
2219 while (next) {
2220 switch (next->sType) {
2221 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
2222 present_regions = next;
2223 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07002224 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002225 present_times =
2226 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
2227 break;
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002228 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
2229 present_fences =
2230 reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
2231 break;
2232 case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
2233 present_modes =
2234 reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
2235 break;
Ian Elliottcb351132016-12-13 10:30:40 -07002236 default:
2237 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
2238 next->sType);
2239 break;
2240 }
2241 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2242 }
2243 ALOGV_IF(
2244 present_regions &&
2245 present_regions->swapchainCount != present_info->swapchainCount,
2246 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002247 ALOGV_IF(present_times &&
2248 present_times->swapchainCount != present_info->swapchainCount,
2249 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2250 "VkPresentInfo::swapchainCount");
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002251 ALOGV_IF(present_fences &&
2252 present_fences->swapchainCount != present_info->swapchainCount,
2253 "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
2254 "VkPresentInfo::swapchainCount");
2255 ALOGV_IF(present_modes &&
2256 present_modes->swapchainCount != present_info->swapchainCount,
2257 "VkSwapchainPresentModeInfoEXT::swapchainCount != "
2258 "VkPresentInfo::swapchainCount");
2259
Ian Elliottcb351132016-12-13 10:30:40 -07002260 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002261 (present_regions) ? present_regions->pRegions : nullptr;
2262 const VkPresentTimeGOOGLE* times =
2263 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002264
Jesse Halld7b994a2015-09-07 14:17:37 -07002265 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2266 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002267 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002268
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002269 VkResult swapchain_result = PresentOneSwapchain(
2270 queue,
2271 swapchain,
2272 present_info->pImageIndices[sc],
2273 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2274 times ? &times[sc] : nullptr,
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002275 present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
2276 present_modes ? &present_modes->pPresentModes[sc] : nullptr,
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002277 present_info->waitSemaphoreCount,
2278 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002279
Jesse Halla9e57032015-11-30 01:03:10 -08002280 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002281 present_info->pResults[sc] = swapchain_result;
2282
2283 if (swapchain_result != final_result)
2284 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002285 }
2286
2287 return final_result;
2288}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002289
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002290VKAPI_ATTR
2291VkResult GetRefreshCycleDurationGOOGLE(
2292 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002293 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002294 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002295 ATRACE_CALL();
2296
Ian Elliott62c48c92017-01-20 13:13:20 -07002297 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002298 VkResult result = VK_SUCCESS;
2299
Ian Elliott3568bfe2019-05-03 15:54:46 -06002300 pDisplayTimingProperties->refreshDuration = swapchain.get_refresh_duration();
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002301
2302 return result;
2303}
2304
2305VKAPI_ATTR
2306VkResult GetPastPresentationTimingGOOGLE(
2307 VkDevice,
2308 VkSwapchainKHR swapchain_handle,
2309 uint32_t* count,
2310 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002311 ATRACE_CALL();
2312
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002313 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002314 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2315 return VK_ERROR_OUT_OF_DATE_KHR;
2316 }
2317
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002318 ANativeWindow* window = swapchain.surface.window.get();
2319 VkResult result = VK_SUCCESS;
2320
2321 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002322 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002323 native_window_enable_frame_timestamps(window, true);
2324 swapchain.frame_timestamps_enabled = true;
2325 }
2326
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002327 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002328 // Get the latest ready timing count before copying, since the copied
2329 // timing info will be erased in copy_ready_timings function.
2330 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002331 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002332 // Check the *count here against the recorded ready timing count, since
2333 // *count can be overwritten per spec describes.
2334 if (*count < n) {
2335 result = VK_INCOMPLETE;
2336 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002337 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002338 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002339 }
2340
2341 return result;
2342}
2343
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002344VKAPI_ATTR
2345VkResult GetSwapchainStatusKHR(
2346 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002347 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002348 ATRACE_CALL();
2349
Chris Forbes4e18ba82017-01-20 12:50:17 +13002350 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002351 VkResult result = VK_SUCCESS;
2352
Chris Forbes4e18ba82017-01-20 12:50:17 +13002353 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2354 return VK_ERROR_OUT_OF_DATE_KHR;
2355 }
2356
Yiwei Zhanga885c062019-10-24 12:07:57 -07002357 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002358
2359 return result;
2360}
2361
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002362VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002363 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002364 uint32_t swapchainCount,
2365 const VkSwapchainKHR* pSwapchains,
2366 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002367 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002368
2369 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2370 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2371 if (!swapchain)
2372 continue;
2373
2374 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2375
2376 ANativeWindow* window = swapchain->surface.window.get();
2377
2378 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2379 const android_smpte2086_metadata smpteMetdata = {
2380 {vulkanMetadata.displayPrimaryRed.x,
2381 vulkanMetadata.displayPrimaryRed.y},
2382 {vulkanMetadata.displayPrimaryGreen.x,
2383 vulkanMetadata.displayPrimaryGreen.y},
2384 {vulkanMetadata.displayPrimaryBlue.x,
2385 vulkanMetadata.displayPrimaryBlue.y},
2386 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2387 vulkanMetadata.maxLuminance,
2388 vulkanMetadata.minLuminance};
2389 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2390
2391 const android_cta861_3_metadata cta8613Metadata = {
2392 vulkanMetadata.maxContentLightLevel,
2393 vulkanMetadata.maxFrameAverageLightLevel};
2394 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2395 }
2396
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002397 return;
2398}
2399
Yiwei Zhang0f475222019-04-11 19:38:00 -07002400static void InterceptBindImageMemory2(
2401 uint32_t bind_info_count,
2402 const VkBindImageMemoryInfo* bind_infos,
2403 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2404 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2405 out_native_buffers->clear();
2406 out_bind_infos->clear();
2407
2408 if (!bind_info_count)
2409 return;
2410
2411 std::unordered_set<uint32_t> intercepted_indexes;
2412
2413 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2414 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2415 bind_infos[idx].pNext);
2416 while (info &&
2417 info->sType !=
2418 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2419 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2420 info->pNext);
2421 }
2422
2423 if (!info)
2424 continue;
2425
2426 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2427 "swapchain handle must not be NULL");
2428 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2429 ALOG_ASSERT(
2430 info->imageIndex < swapchain->num_images,
2431 "imageIndex must be less than the number of images in swapchain");
2432
2433 ANativeWindowBuffer* buffer =
2434 swapchain->images[info->imageIndex].buffer.get();
2435 VkNativeBufferANDROID native_buffer = {
2436#pragma clang diagnostic push
2437#pragma clang diagnostic ignored "-Wold-style-cast"
2438 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2439#pragma clang diagnostic pop
2440 .pNext = bind_infos[idx].pNext,
2441 .handle = buffer->handle,
2442 .stride = buffer->stride,
2443 .format = buffer->format,
2444 .usage = int(buffer->usage),
2445 };
2446 // Reserve enough space to avoid letting re-allocation invalidate the
2447 // addresses of the elements inside.
2448 out_native_buffers->reserve(bind_info_count);
2449 out_native_buffers->emplace_back(native_buffer);
2450
2451 // Reserve the space now since we know how much is needed now.
2452 out_bind_infos->reserve(bind_info_count);
2453 out_bind_infos->emplace_back(bind_infos[idx]);
2454 out_bind_infos->back().pNext = &out_native_buffers->back();
2455
2456 intercepted_indexes.insert(idx);
2457 }
2458
2459 if (intercepted_indexes.empty())
2460 return;
2461
2462 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2463 if (intercepted_indexes.count(idx))
2464 continue;
2465 out_bind_infos->emplace_back(bind_infos[idx]);
2466 }
2467}
2468
Yiwei Zhang23143102019-04-10 18:24:05 -07002469VKAPI_ATTR
2470VkResult BindImageMemory2(VkDevice device,
2471 uint32_t bindInfoCount,
2472 const VkBindImageMemoryInfo* pBindInfos) {
2473 ATRACE_CALL();
2474
Yiwei Zhang0f475222019-04-11 19:38:00 -07002475 // out_native_buffers is for maintaining the lifecycle of the constructed
2476 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2477 std::vector<VkNativeBufferANDROID> out_native_buffers;
2478 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2479 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2480 &out_bind_infos);
2481 return GetData(device).driver.BindImageMemory2(
2482 device, bindInfoCount,
2483 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002484}
2485
2486VKAPI_ATTR
2487VkResult BindImageMemory2KHR(VkDevice device,
2488 uint32_t bindInfoCount,
2489 const VkBindImageMemoryInfo* pBindInfos) {
2490 ATRACE_CALL();
2491
Yiwei Zhang0f475222019-04-11 19:38:00 -07002492 std::vector<VkNativeBufferANDROID> out_native_buffers;
2493 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2494 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2495 &out_bind_infos);
2496 return GetData(device).driver.BindImageMemory2KHR(
2497 device, bindInfoCount,
2498 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002499}
2500
Chris Forbes9d0d9ff2022-12-28 01:58:31 +00002501VKAPI_ATTR
2502VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
2503 const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
2504 ATRACE_CALL();
2505
2506 Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
2507 ANativeWindow* window = swapchain.surface.window.get();
2508
2509 // If in shared present mode, don't actually release the image back to the BQ.
2510 // Both sides share it forever.
2511 if (swapchain.shared)
2512 return VK_SUCCESS;
2513
2514 for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
2515 Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
2516 window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
2517
2518 // cancelBuffer has taken ownership of the dequeue fence
2519 img.dequeue_fence = -1;
2520 // if we're still holding a release fence, get rid of it now
2521 if (img.release_fence >= 0) {
2522 close(img.release_fence);
2523 img.release_fence = -1;
2524 }
2525 img.dequeued = false;
2526 }
2527
2528 return VK_SUCCESS;
2529}
2530
Chia-I Wu62262232016-03-26 07:06:44 +08002531} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002532} // namespace vulkan