blob: 1bf7abb758bc7266b3485d854b0c618e1b3d5da0 [file] [log] [blame]
Jesse Hallb1352bc2015-09-04 16:12:33 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Yiwei Zhang0f475222019-04-11 19:38:00 -070019#include <android/hardware/graphics/common/1.0/types.h>
Jesse Hall79927812017-03-23 11:03:23 -070020#include <grallocusage/GrallocUsageConversion.h>
Yiwei Zhang69395cd2019-07-03 16:55:39 -070021#include <graphicsenv/GraphicsEnv.h>
John Reck97678d42022-08-23 11:24:51 -040022#include <hardware/gralloc.h>
23#include <hardware/gralloc1.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070024#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070025#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070026#include <system/window.h>
27#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050028#include <ui/DebugUtils.h>
29#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080030#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080031#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080032#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070033
34#include <algorithm>
35#include <unordered_set>
36#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Chia-I Wu4a6a9162016-03-26 07:17:34 +080038#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070039
Daniel Kochf25f5bb2017-10-05 00:26:58 -040040using android::hardware::graphics::common::V1_0::BufferUsage;
41
Chia-I Wu62262232016-03-26 07:06:44 +080042namespace vulkan {
43namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070044
Jesse Halld7b994a2015-09-07 14:17:37 -070045namespace {
46
John Reck97678d42022-08-23 11:24:51 -040047static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
48 uint64_t consumerUsage) {
49 static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
50 uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
51 "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
52 "bits to match");
53 uint64_t merged = producerUsage | consumerUsage;
54 if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
55 GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
56 merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
57 merged |= BufferUsage::CPU_READ_OFTEN;
58 }
59 if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
60 GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
61 merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
62 merged |= BufferUsage::CPU_WRITE_OFTEN;
63 }
64 return merged;
65}
66
Jesse Hall55bc0972016-02-23 16:43:29 -080067const VkSurfaceTransformFlagsKHR kSupportedTransforms =
68 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
69 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
70 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
71 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
73 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
74 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
75 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080076 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
77
78VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
79 // Native and Vulkan transforms are isomorphic, but are represented
80 // differently. Vulkan transforms are built up of an optional horizontal
81 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
82 // transforms are built up from a horizontal flip, vertical flip, and
83 // 90-degree rotation, all optional but always in that order.
84
Jesse Hall55bc0972016-02-23 16:43:29 -080085 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070086 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080087 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070088 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
89 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
90 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
91 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
92 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080093 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070094 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080095 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070096 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
97 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
98 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
99 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
100 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -0800101 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
102 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
103 default:
104 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
105 }
106}
107
Yiwei Zhang70a21962019-05-31 17:26:52 -0700108int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
109 switch (transform) {
110 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
111 return NATIVE_WINDOW_TRANSFORM_ROT_90;
112 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
113 return NATIVE_WINDOW_TRANSFORM_ROT_180;
114 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
115 return NATIVE_WINDOW_TRANSFORM_ROT_270;
116 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
117 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
118 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
119 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
120 NATIVE_WINDOW_TRANSFORM_ROT_90;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
123 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
124 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
125 NATIVE_WINDOW_TRANSFORM_ROT_90;
126 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
127 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
128 default:
129 return 0;
130 }
131}
132
Jesse Hall178b6962016-02-24 15:39:50 -0800133int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
134 switch (transform) {
135 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
136 return NATIVE_WINDOW_TRANSFORM_ROT_270;
137 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
138 return NATIVE_WINDOW_TRANSFORM_ROT_180;
139 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
140 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700141 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
142 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
143 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
144 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
145 NATIVE_WINDOW_TRANSFORM_ROT_90;
146 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
147 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
148 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
149 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
150 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800151 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
152 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
153 default:
154 return 0;
155 }
156}
157
Ian Elliott8a977262017-01-19 09:05:58 -0700158class TimingInfo {
159 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800160 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700161 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800162 native_frame_id_(nativeFrameId) {}
163 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700164 return (timestamp_desired_present_time_ !=
165 NATIVE_WINDOW_TIMESTAMP_PENDING &&
166 timestamp_actual_present_time_ !=
167 NATIVE_WINDOW_TIMESTAMP_PENDING &&
168 timestamp_render_complete_time_ !=
169 NATIVE_WINDOW_TIMESTAMP_PENDING &&
170 timestamp_composition_latch_time_ !=
171 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700172 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700173 void calculate(int64_t rdur) {
174 bool anyTimestampInvalid =
175 (timestamp_actual_present_time_ ==
176 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
177 (timestamp_render_complete_time_ ==
178 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
179 (timestamp_composition_latch_time_ ==
180 NATIVE_WINDOW_TIMESTAMP_INVALID);
181 if (anyTimestampInvalid) {
182 ALOGE("Unexpectedly received invalid timestamp.");
183 vals_.actualPresentTime = 0;
184 vals_.earliestPresentTime = 0;
185 vals_.presentMargin = 0;
186 return;
187 }
188
189 vals_.actualPresentTime =
190 static_cast<uint64_t>(timestamp_actual_present_time_);
191 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700192 timestamp_render_complete_time_);
193 // Calculate vals_.earliestPresentTime, and potentially adjust
194 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
195 // is vals_.actualPresentTime. If we can subtract rdur (the duration
196 // of a refresh cycle) from vals_.earliestPresentTime (and also from
197 // vals_.presentMargin) and still leave a positive margin, then we can
198 // report to the application that it could have presented earlier than
199 // it did (per the extension specification). If for some reason, we
200 // can do this subtraction repeatedly, we do, since
201 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700202 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700203 while ((margin > rdur) &&
204 ((early_time - rdur) > timestamp_composition_latch_time_)) {
205 early_time -= rdur;
206 margin -= rdur;
207 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700208 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
209 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700210 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800211 void get_values(VkPastPresentationTimingGOOGLE* values) const {
212 *values = vals_;
213 }
Ian Elliott8a977262017-01-19 09:05:58 -0700214
215 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800216 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700217
Brian Anderson1049d1d2016-12-16 17:25:57 -0800218 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700219 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
220 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
221 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
222 int64_t timestamp_composition_latch_time_
223 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700224};
225
Jesse Hall1356b0d2015-11-23 17:24:58 -0800226struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800227 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700228 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700229 uint64_t consumer_usage;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800230};
231
232VkSurfaceKHR HandleFromSurface(Surface* surface) {
233 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
234}
235
236Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800237 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800238}
239
Ian Elliott8a977262017-01-19 09:05:58 -0700240// Maximum number of TimingInfo structs to keep per swapchain:
241enum { MAX_TIMING_INFOS = 10 };
242// Minimum number of frames to look for in the past (so we don't cause
243// syncronous requests to Surface Flinger):
244enum { MIN_NUM_FRAMES_AGO = 5 };
245
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300246bool IsSharedPresentMode(VkPresentModeKHR mode) {
247 return mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
248 mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR;
249}
250
Jesse Hall1356b0d2015-11-23 17:24:58 -0800251struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700252 Swapchain(Surface& surface_,
253 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700254 VkPresentModeKHR present_mode,
255 int pre_transform_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700256 : surface(surface_),
257 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700258 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700259 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300260 frame_timestamps_enabled(false),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800261 acquire_next_image_timeout(-1),
Chris Forbes4cd01fb2022-10-19 11:35:16 +1300262 shared(IsSharedPresentMode(present_mode)) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700263 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700264 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700265 window,
Brian Andersondc96fdf2017-03-20 16:54:25 -0700266 &refresh_duration);
Ian Elliott8a977262017-01-19 09:05:58 -0700267 }
Ian Elliott3568bfe2019-05-03 15:54:46 -0600268 uint64_t get_refresh_duration()
269 {
270 ANativeWindow* window = surface.window.get();
271 native_window_get_refresh_cycle_duration(
272 window,
273 &refresh_duration);
274 return static_cast<uint64_t>(refresh_duration);
275
276 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800277
278 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700279 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700280 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700281 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700282 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700283 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800284 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300285 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700286
287 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700288 Image()
289 : image(VK_NULL_HANDLE),
290 dequeue_fence(-1),
291 release_fence(-1),
292 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700293 VkImage image;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800294 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700295 // The fence is only valid when the buffer is dequeued, and should be
296 // -1 any other time. When valid, we own the fd, and must ensure it is
297 // closed: either by closing it explicitly when queueing the buffer,
298 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
299 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700300 // This fence is a dup of the sync fd returned from the driver via
301 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
302 // ensure it is closed upon re-presenting or releasing the image.
303 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700304 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800305 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700306
Yiwei Zhang5e862202019-06-21 14:59:16 -0700307 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700308};
309
310VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
311 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
312}
313
314Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800315 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700316}
317
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700318static bool IsFencePending(int fd) {
319 if (fd < 0)
320 return false;
321
322 errno = 0;
323 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
324}
325
Jesse Halldc225072016-05-30 22:40:14 -0700326void ReleaseSwapchainImage(VkDevice device,
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000327 bool shared_present,
Jesse Halldc225072016-05-30 22:40:14 -0700328 ANativeWindow* window,
329 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700330 Swapchain::Image& image,
331 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700332 ATRACE_CALL();
333
Jesse Halldc225072016-05-30 22:40:14 -0700334 ALOG_ASSERT(release_fence == -1 || image.dequeued,
335 "ReleaseSwapchainImage: can't provide a release fence for "
336 "non-dequeued images");
337
338 if (image.dequeued) {
339 if (release_fence >= 0) {
340 // We get here from vkQueuePresentKHR. The application is
341 // responsible for creating an execution dependency chain from
342 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
343 // (release_fence), so we can drop the dequeue_fence here.
344 if (image.dequeue_fence >= 0)
345 close(image.dequeue_fence);
346 } else {
347 // We get here during swapchain destruction, or various serious
348 // error cases e.g. when we can't create the release_fence during
349 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
350 // have already signalled, since the swapchain images are supposed
351 // to be idle before the swapchain is destroyed. In error cases,
352 // there may be rendering in flight to the image, but since we
353 // weren't able to create a release_fence, waiting for the
354 // dequeue_fence is about the best we can do.
355 release_fence = image.dequeue_fence;
356 }
357 image.dequeue_fence = -1;
358
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000359 // It's invalid to call cancelBuffer on a shared buffer
360 if (window && !shared_present) {
Jesse Halldc225072016-05-30 22:40:14 -0700361 window->cancelBuffer(window, image.buffer.get(), release_fence);
362 } else {
363 if (release_fence >= 0) {
364 sync_wait(release_fence, -1 /* forever */);
365 close(release_fence);
366 }
367 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700368 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700369 image.dequeued = false;
370 }
371
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700372 if (defer_if_pending && IsFencePending(image.release_fence))
373 return;
374
375 if (image.release_fence >= 0) {
376 close(image.release_fence);
377 image.release_fence = -1;
378 }
379
Jesse Halldc225072016-05-30 22:40:14 -0700380 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700381 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700382 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700383 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700384 image.image = VK_NULL_HANDLE;
385 }
386
387 image.buffer.clear();
388}
389
390void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
391 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
392 return;
Jesse Halldc225072016-05-30 22:40:14 -0700393 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +0000394 if (!swapchain->images[i].dequeued) {
395 ReleaseSwapchainImage(device, swapchain->shared, nullptr, -1,
396 swapchain->images[i], true);
397 }
Jesse Halldc225072016-05-30 22:40:14 -0700398 }
399 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700400 swapchain->timing.clear();
401}
402
403uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800404 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
405 return 0;
406 }
Ian Elliott8a977262017-01-19 09:05:58 -0700407
Brian Anderson1049d1d2016-12-16 17:25:57 -0800408 uint32_t num_ready = 0;
409 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
410 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700411 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800412 if (ti.ready()) {
413 // This TimingInfo is ready to be reported to the user. Add it
414 // to the num_ready.
415 num_ready++;
416 continue;
417 }
418 // This TimingInfo is not yet ready to be reported to the user,
419 // and so we should look for any available timestamps that
420 // might make it ready.
421 int64_t desired_present_time = 0;
422 int64_t render_complete_time = 0;
423 int64_t composition_latch_time = 0;
424 int64_t actual_present_time = 0;
425 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800426 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800427 swapchain.surface.window.get(), ti.native_frame_id_,
428 &desired_present_time, &render_complete_time,
429 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700430 nullptr, //&first_composition_start_time,
431 nullptr, //&last_composition_start_time,
432 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800433 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700434 nullptr, //&dequeue_ready_time,
435 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800436
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800437 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800438 continue;
439 }
440
441 // Record the timestamp(s) we received, and then see if this TimingInfo
442 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700443 ti.timestamp_desired_present_time_ = desired_present_time;
444 ti.timestamp_actual_present_time_ = actual_present_time;
445 ti.timestamp_render_complete_time_ = render_complete_time;
446 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447
448 if (ti.ready()) {
449 // The TimingInfo has received enough timestamps, and should now
450 // use those timestamps to calculate the info that should be
451 // reported to the user:
452 ti.calculate(swapchain.refresh_duration);
453 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700454 }
455 }
456 return num_ready;
457}
458
Ian Elliott8a977262017-01-19 09:05:58 -0700459void copy_ready_timings(Swapchain& swapchain,
460 uint32_t* count,
461 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800462 if (swapchain.timing.empty()) {
463 *count = 0;
464 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700465 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800466
467 size_t last_ready = swapchain.timing.size() - 1;
468 while (!swapchain.timing[last_ready].ready()) {
469 if (last_ready == 0) {
470 *count = 0;
471 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700472 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800473 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700474 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800475
476 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700477 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800478 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
479 const TimingInfo& ti = swapchain.timing[i];
480 if (ti.ready()) {
481 ti.get_values(&timings[num_copied]);
482 num_copied++;
483 }
484 num_to_remove++;
485 }
486
487 // Discard old frames that aren't ready if newer frames are ready.
488 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700489 swapchain.timing.erase(swapchain.timing.begin(),
490 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800491
Ian Elliott8a977262017-01-19 09:05:58 -0700492 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700493}
494
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500495android::PixelFormat GetNativePixelFormat(VkFormat format) {
496 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700497 switch (format) {
498 case VK_FORMAT_R8G8B8A8_UNORM:
499 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500500 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700501 break;
502 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500503 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700504 break;
505 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500506 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700507 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800508 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500509 native_format = android::PIXEL_FORMAT_RGBA_1010102;
510 break;
511 case VK_FORMAT_R8_UNORM:
512 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700513 break;
514 default:
515 ALOGV("unsupported swapchain format %d", format);
516 break;
517 }
518 return native_format;
519}
520
521android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
522 switch (colorspace) {
523 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
524 return HAL_DATASPACE_V0_SRGB;
525 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
526 return HAL_DATASPACE_DISPLAY_P3;
527 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
528 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600529 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
530 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700531 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
532 return HAL_DATASPACE_DCI_P3_LINEAR;
533 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
534 return HAL_DATASPACE_DCI_P3;
535 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
536 return HAL_DATASPACE_V0_SRGB_LINEAR;
537 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
538 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600539 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
540 return HAL_DATASPACE_BT2020_LINEAR;
541 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700542 return static_cast<android_dataspace>(
543 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
544 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600545 case VK_COLOR_SPACE_DOLBYVISION_EXT:
546 return static_cast<android_dataspace>(
547 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
548 HAL_DATASPACE_RANGE_FULL);
549 case VK_COLOR_SPACE_HDR10_HLG_EXT:
550 return static_cast<android_dataspace>(
551 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
552 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700553 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
554 return static_cast<android_dataspace>(
555 HAL_DATASPACE_STANDARD_ADOBE_RGB |
556 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
557 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
558 return HAL_DATASPACE_ADOBE_RGB;
559
560 // Pass through is intended to allow app to provide data that is passed
561 // to the display system without modification.
562 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
563 return HAL_DATASPACE_ARBITRARY;
564
565 default:
566 // This indicates that we don't know about the
567 // dataspace specified and we should indicate that
568 // it's unsupported
569 return HAL_DATASPACE_UNKNOWN;
570 }
571}
572
Jesse Halld7b994a2015-09-07 14:17:37 -0700573} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700574
Jesse Halle1b12782015-11-30 11:27:32 -0800575VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800576VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800577 VkInstance instance,
578 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
579 const VkAllocationCallbacks* allocator,
580 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800581 ATRACE_CALL();
582
Jesse Hall1f91d392015-12-11 16:28:44 -0800583 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800584 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800585 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
586 alignof(Surface),
587 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800588 if (!mem)
589 return VK_ERROR_OUT_OF_HOST_MEMORY;
590 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700591
Chia-I Wue8e689f2016-04-18 08:21:31 +0800592 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700593 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700594 int err = native_window_get_consumer_usage(surface->window.get(),
595 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800596 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700597 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
598 strerror(-err), err);
599 surface->~Surface();
600 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700601 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700602 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700603
Yiwei Zhang6435b322018-05-08 11:12:17 -0700604 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800605 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800606 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800607 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
608 err);
609 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800610 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700611 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800612 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700613
Jesse Hall1356b0d2015-11-23 17:24:58 -0800614 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700615 return VK_SUCCESS;
616}
617
Jesse Halle1b12782015-11-30 11:27:32 -0800618VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800619void DestroySurfaceKHR(VkInstance instance,
620 VkSurfaceKHR surface_handle,
621 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800622 ATRACE_CALL();
623
Jesse Hall1356b0d2015-11-23 17:24:58 -0800624 Surface* surface = SurfaceFromHandle(surface_handle);
625 if (!surface)
626 return;
627 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700628 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700629 "destroyed VkSurfaceKHR 0x%" PRIx64
630 " has active VkSwapchainKHR 0x%" PRIx64,
631 reinterpret_cast<uint64_t>(surface_handle),
632 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800633 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800634 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800635 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800636 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800637}
638
Jesse Halle1b12782015-11-30 11:27:32 -0800639VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800640VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
641 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000642 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800643 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000644 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800645 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800646}
647
Jesse Halle1b12782015-11-30 11:27:32 -0800648VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800649VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600650 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800651 VkSurfaceKHR surface,
652 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800653 ATRACE_CALL();
654
Ian Elliottac40c1e2022-12-21 23:16:21 +0000655 int err;
656 int width, height;
657 int transform_hint;
658 int max_buffer_count;
659 if (surface == VK_NULL_HANDLE) {
660 const InstanceData& instance_data = GetData(pdev);
661 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
662 bool surfaceless_enabled =
663 instance_data.hook_extensions.test(surfaceless);
664 if (!surfaceless_enabled) {
665 // It is an error to pass a surface==VK_NULL_HANDLE unless the
666 // VK_GOOGLE_surfaceless_query extension is enabled
667 return VK_ERROR_SURFACE_LOST_KHR;
668 }
669 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
670 // extension for this function is for
671 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
672 // four values cannot be known without a surface. Default values will
673 // be supplied anyway, but cannot be relied upon.
674 width = 0xFFFFFFFF;
675 height = 0xFFFFFFFF;
676 transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
677 capabilities->minImageCount = 0xFFFFFFFF;
678 capabilities->maxImageCount = 0xFFFFFFFF;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600679 } else {
Ian Elliottac40c1e2022-12-21 23:16:21 +0000680 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
681
682 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
683 if (err != android::OK) {
684 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
685 strerror(-err), err);
686 return VK_ERROR_SURFACE_LOST_KHR;
687 }
688 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
689 if (err != android::OK) {
690 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
691 strerror(-err), err);
692 return VK_ERROR_SURFACE_LOST_KHR;
693 }
694
695 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
696 &transform_hint);
697 if (err != android::OK) {
698 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
699 strerror(-err), err);
700 return VK_ERROR_SURFACE_LOST_KHR;
701 }
702
703 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
704 &max_buffer_count);
705 if (err != android::OK) {
706 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
707 strerror(-err), err);
708 return VK_ERROR_SURFACE_LOST_KHR;
709 }
710 capabilities->minImageCount = std::min(max_buffer_count, 3);
711 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800712 }
Ian Elliottac40c1e2022-12-21 23:16:21 +0000713
714 capabilities->currentExtent =
715 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
716
717 // TODO(http://b/134182502): Figure out what the max extent should be.
718 capabilities->minImageExtent = VkExtent2D{1, 1};
719 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
720
721 if (capabilities->maxImageExtent.height <
722 capabilities->currentExtent.height) {
723 capabilities->maxImageExtent.height =
724 capabilities->currentExtent.height;
725 }
726
727 if (capabilities->maxImageExtent.width <
728 capabilities->currentExtent.width) {
729 capabilities->maxImageExtent.width = capabilities->currentExtent.width;
730 }
731
732 capabilities->maxImageArrayLayers = 1;
733
734 capabilities->supportedTransforms = kSupportedTransforms;
735 capabilities->currentTransform =
736 TranslateNativeToVulkanTransform(transform_hint);
737
738 // On Android, window composition is a WindowManager property, not something
739 // associated with the bufferqueue. It can't be changed from here.
740 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
741
742 capabilities->supportedUsageFlags =
743 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
744 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
745 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
746 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
747
748 return VK_SUCCESS;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700749}
750
Jesse Halle1b12782015-11-30 11:27:32 -0800751VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700752VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
753 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800754 uint32_t* count,
755 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800756 ATRACE_CALL();
757
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700758 const InstanceData& instance_data = GetData(pdev);
759
Ian Elliott1ce053f2022-03-16 09:49:53 -0600760 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000761 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600762 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600763 if (surface_handle == VK_NULL_HANDLE) {
764 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
765 bool surfaceless_enabled =
766 instance_data.hook_extensions.test(surfaceless);
767 if (!surfaceless_enabled) {
768 return VK_ERROR_SURFACE_LOST_KHR;
769 }
Chris Forbesb1de3b12022-10-20 09:05:48 +1300770 // Support for VK_GOOGLE_surfaceless_query.
Ian Elliott1ce053f2022-03-16 09:49:53 -0600771
772 // TODO(b/203826952): research proper value; temporarily use the
773 // values seen on Pixel
774 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
775 } else {
776 Surface& surface = *SurfaceFromHandle(surface_handle);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600777 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700778 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700779
Charlie Lao324191f2019-12-13 11:03:16 -0800780 AHardwareBuffer_Desc desc = {};
781 desc.width = 1;
782 desc.height = 1;
783 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600784 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800785 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
786
787 // We must support R8G8B8A8
788 std::vector<VkSurfaceFormatKHR> all_formats = {
789 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000790 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Yiwei Zhang0413cc02022-07-27 04:54:48 +0000791 };
Charlie Lao324191f2019-12-13 11:03:16 -0800792
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000793 if (colorspace_ext) {
794 all_formats.emplace_back(VkSurfaceFormatKHR{
Jason Macnakca506332022-11-09 11:00:36 -0800795 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
796 all_formats.emplace_back(VkSurfaceFormatKHR{
797 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_PASS_THROUGH_EXT});
798 all_formats.emplace_back(VkSurfaceFormatKHR{
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000799 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800800 all_formats.emplace_back(VkSurfaceFormatKHR{
801 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
802 all_formats.emplace_back(VkSurfaceFormatKHR{
803 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
804 }
805
Ian Elliott1ce053f2022-03-16 09:49:53 -0600806 // NOTE: Any new formats that are added must be coordinated across different
807 // Android users. This includes the ANGLE team (a layered implementation of
808 // OpenGL-ES).
809
Charlie Lao324191f2019-12-13 11:03:16 -0800810 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
811 if (AHardwareBuffer_isSupported(&desc)) {
812 all_formats.emplace_back(VkSurfaceFormatKHR{
813 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800814 if (colorspace_ext) {
815 all_formats.emplace_back(
816 VkSurfaceFormatKHR{VK_FORMAT_R5G6B5_UNORM_PACK16,
817 VK_COLOR_SPACE_PASS_THROUGH_EXT});
818 }
Charlie Lao324191f2019-12-13 11:03:16 -0800819 }
820
821 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
822 if (AHardwareBuffer_isSupported(&desc)) {
823 all_formats.emplace_back(VkSurfaceFormatKHR{
824 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800825 if (colorspace_ext) {
826 all_formats.emplace_back(
827 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
828 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800829 all_formats.emplace_back(
830 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
831 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
832 all_formats.emplace_back(
833 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
834 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
835 }
836 }
837
838 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
839 if (AHardwareBuffer_isSupported(&desc)) {
840 all_formats.emplace_back(
841 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
842 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
Jason Macnakca506332022-11-09 11:00:36 -0800843 if (colorspace_ext) {
844 all_formats.emplace_back(
845 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
846 VK_COLOR_SPACE_PASS_THROUGH_EXT});
Charlie Lao324191f2019-12-13 11:03:16 -0800847 all_formats.emplace_back(
848 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
849 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
850 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700851 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700852
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500853 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
854 if (AHardwareBuffer_isSupported(&desc)) {
Jason Macnakca506332022-11-09 11:00:36 -0800855 if (colorspace_ext) {
856 all_formats.emplace_back(VkSurfaceFormatKHR{
857 VK_FORMAT_R8_UNORM, VK_COLOR_SPACE_PASS_THROUGH_EXT});
858 }
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500859 }
860
Ian Elliott6ba85d92022-02-18 16:44:58 -0700861 // NOTE: Any new formats that are added must be coordinated across different
862 // Android users. This includes the ANGLE team (a layered implementation of
863 // OpenGL-ES).
864
Ian Elliottac40c1e2022-12-21 23:16:21 +0000865 VkResult result = VK_SUCCESS;
866 if (formats) {
867 uint32_t transfer_count = all_formats.size();
868 if (transfer_count > *count) {
869 transfer_count = *count;
870 result = VK_INCOMPLETE;
871 }
872 std::copy(all_formats.begin(), all_formats.begin() + transfer_count,
873 formats);
874 *count = transfer_count;
875 } else {
876 *count = all_formats.size();
877 }
878
879 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700880}
881
Jesse Halle1b12782015-11-30 11:27:32 -0800882VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300883VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
884 VkPhysicalDevice physicalDevice,
885 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
886 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800887 ATRACE_CALL();
888
Ian Elliottac40c1e2022-12-21 23:16:21 +0000889 VkResult result = GetPhysicalDeviceSurfaceCapabilitiesKHR(
890 physicalDevice, pSurfaceInfo->surface,
891 &pSurfaceCapabilities->surfaceCapabilities);
Chris Forbes2452cf72017-03-16 16:30:17 +1300892
Ian Elliottac40c1e2022-12-21 23:16:21 +0000893 VkSurfaceCapabilities2KHR* caps = pSurfaceCapabilities;
894 while (caps->pNext) {
895 caps = reinterpret_cast<VkSurfaceCapabilities2KHR*>(caps->pNext);
Chris Forbes06bc0092017-03-16 16:46:05 +1300896
Ian Elliottac40c1e2022-12-21 23:16:21 +0000897 switch (caps->sType) {
Chris Forbes06bc0092017-03-16 16:46:05 +1300898 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
899 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
Ian Elliottac40c1e2022-12-21 23:16:21 +0000900 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(
901 caps);
Chris Forbes06bc0092017-03-16 16:46:05 +1300902 // Claim same set of usage flags are supported for
903 // shared present modes as for other modes.
904 shared_caps->sharedPresentSupportedUsageFlags =
905 pSurfaceCapabilities->surfaceCapabilities
906 .supportedUsageFlags;
907 } break;
908
Ian Elliottbb67b242022-03-16 09:52:28 -0600909 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
910 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
Ian Elliottac40c1e2022-12-21 23:16:21 +0000911 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(caps);
Ian Elliottbb67b242022-03-16 09:52:28 -0600912 protected_caps->supportsProtected = VK_TRUE;
913 } break;
914
Chris Forbes06bc0092017-03-16 16:46:05 +1300915 default:
916 // Ignore all other extension structs
917 break;
918 }
919 }
920
Ian Elliottac40c1e2022-12-21 23:16:21 +0000921 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +1300922}
923
924VKAPI_ATTR
925VkResult GetPhysicalDeviceSurfaceFormats2KHR(
926 VkPhysicalDevice physicalDevice,
927 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
928 uint32_t* pSurfaceFormatCount,
929 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800930 ATRACE_CALL();
931
Chris Forbes2452cf72017-03-16 16:30:17 +1300932 if (!pSurfaceFormats) {
933 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
934 pSurfaceInfo->surface,
935 pSurfaceFormatCount, nullptr);
Trevor David Black929e9cd2022-11-22 04:12:19 +0000936 }
Chris Forbes2452cf72017-03-16 16:30:17 +1300937
Trevor David Black929e9cd2022-11-22 04:12:19 +0000938 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
939 // after the call.
940 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
941 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
942 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
943 surface_formats.data());
Trevor David Black2cc44682022-03-09 00:31:38 +0000944
Trevor David Black929e9cd2022-11-22 04:12:19 +0000945 if (result != VK_SUCCESS && result != VK_INCOMPLETE) {
946 return result;
947 }
Trevor David Black2cc44682022-03-09 00:31:38 +0000948
Trevor David Black929e9cd2022-11-22 04:12:19 +0000949 const auto& driver = GetData(physicalDevice).driver;
950
951 // marshal results individually due to stride difference.
952 uint32_t formats_to_marshal = *pSurfaceFormatCount;
953 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
954 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
955
956 // Query the compression properties for the surface format
957 VkSurfaceFormat2KHR* pSurfaceFormat = &pSurfaceFormats[i];
958 while (pSurfaceFormat->pNext) {
959 pSurfaceFormat =
960 reinterpret_cast<VkSurfaceFormat2KHR*>(pSurfaceFormat->pNext);
961 switch (pSurfaceFormat->sType) {
962 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT: {
Trevor David Black2cc44682022-03-09 00:31:38 +0000963 VkImageCompressionPropertiesEXT* surfaceCompressionProps =
964 reinterpret_cast<VkImageCompressionPropertiesEXT*>(
Trevor David Black929e9cd2022-11-22 04:12:19 +0000965 pSurfaceFormat);
Trevor David Black2cc44682022-03-09 00:31:38 +0000966
967 if (surfaceCompressionProps &&
968 driver.GetPhysicalDeviceImageFormatProperties2KHR) {
969 VkPhysicalDeviceImageFormatInfo2 imageFormatInfo = {};
970 imageFormatInfo.sType =
971 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2;
972 imageFormatInfo.format =
973 pSurfaceFormats[i].surfaceFormat.format;
974 imageFormatInfo.pNext = nullptr;
975
976 VkImageCompressionControlEXT compressionControl = {};
977 compressionControl.sType =
978 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT;
979 compressionControl.pNext = imageFormatInfo.pNext;
980
981 imageFormatInfo.pNext = &compressionControl;
982
983 VkImageCompressionPropertiesEXT compressionProps = {};
984 compressionProps.sType =
985 VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_PROPERTIES_EXT;
986 compressionProps.pNext = nullptr;
987
988 VkImageFormatProperties2KHR imageFormatProps = {};
989 imageFormatProps.sType =
990 VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR;
991 imageFormatProps.pNext = &compressionProps;
992
993 VkResult compressionRes =
994 driver.GetPhysicalDeviceImageFormatProperties2KHR(
995 physicalDevice, &imageFormatInfo,
996 &imageFormatProps);
997 if (compressionRes == VK_SUCCESS) {
998 surfaceCompressionProps->imageCompressionFlags =
999 compressionProps.imageCompressionFlags;
1000 surfaceCompressionProps
1001 ->imageCompressionFixedRateFlags =
1002 compressionProps.imageCompressionFixedRateFlags;
1003 } else {
1004 return compressionRes;
1005 }
1006 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001007 } break;
1008
1009 default:
1010 // Ignore all other extension structs
1011 break;
Chris Forbes2452cf72017-03-16 16:30:17 +13001012 }
1013 }
Chris Forbes2452cf72017-03-16 16:30:17 +13001014 }
Trevor David Black929e9cd2022-11-22 04:12:19 +00001015
1016 return result;
Chris Forbes2452cf72017-03-16 16:30:17 +13001017}
1018
1019VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +13001020VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001021 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +08001022 uint32_t* count,
1023 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001024 ATRACE_CALL();
1025
Yiwei Zhange4a559c2018-02-15 11:27:36 -08001026 int err;
1027 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -06001028 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -06001029 if (surface == VK_NULL_HANDLE) {
1030 const InstanceData& instance_data = GetData(pdev);
1031 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
1032 bool surfaceless_enabled =
1033 instance_data.hook_extensions.test(surfaceless);
1034 if (!surfaceless_enabled) {
1035 return VK_ERROR_SURFACE_LOST_KHR;
1036 }
1037 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
1038 // extension for this function is for
1039 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
1040 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
1041 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
Ian Elliott7e361142022-06-02 10:45:17 -06001042 // surface, and that cannot be relied upon. Therefore, don't return it.
Ian Elliott1ce053f2022-03-16 09:49:53 -06001043 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1044 } else {
1045 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1046
1047 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1048 &query_value);
1049 if (err != android::OK || query_value < 0) {
1050 ALOGE(
1051 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
1052 "value=%d",
1053 strerror(-err), err, query_value);
1054 return VK_ERROR_SURFACE_LOST_KHR;
1055 }
1056 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1057
1058 err =
1059 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
1060 if (err != android::OK || query_value < 0) {
1061 ALOGE(
1062 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
1063 strerror(-err), err, query_value);
1064 return VK_ERROR_SURFACE_LOST_KHR;
1065 }
1066 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
1067
1068 if (min_undequeued_buffers + 1 < max_buffer_count)
1069 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
1070 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
1071 }
Chris Forbese8d79a62017-02-22 12:49:18 +13001072
1073 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -07001074 QueryPresentationProperties(pdev, &present_properties);
1075 if (present_properties.sharedImage) {
1076 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
1077 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +13001078 }
1079
Ian Elliottac40c1e2022-12-21 23:16:21 +00001080 uint32_t num_modes = uint32_t(present_modes.size());
1081
1082 VkResult result = VK_SUCCESS;
1083 if (modes) {
1084 if (*count < num_modes)
1085 result = VK_INCOMPLETE;
1086 *count = std::min(*count, num_modes);
1087 std::copy_n(present_modes.data(), *count, modes);
1088 } else {
1089 *count = num_modes;
1090 }
1091 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001092}
1093
Jesse Halle1b12782015-11-30 11:27:32 -08001094VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001095VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001096 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001097 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001098 ATRACE_CALL();
1099
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001100 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
1101 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1102 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1103 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1104 pDeviceGroupPresentCapabilities->sType);
1105
1106 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1107 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1108
1109 // assume device group of size 1
1110 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1111 pDeviceGroupPresentCapabilities->modes =
1112 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1113
1114 return VK_SUCCESS;
1115}
1116
1117VKAPI_ATTR
1118VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001119 VkDevice,
1120 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001121 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001122 ATRACE_CALL();
1123
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001124 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1125 return VK_SUCCESS;
1126}
1127
1128VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001129VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001130 VkSurfaceKHR surface,
1131 uint32_t* pRectCount,
1132 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001133 ATRACE_CALL();
1134
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001135 if (!pRects) {
1136 *pRectCount = 1;
1137 } else {
1138 uint32_t count = std::min(*pRectCount, 1u);
1139 bool incomplete = *pRectCount < 1;
1140
1141 *pRectCount = count;
1142
1143 if (incomplete) {
1144 return VK_INCOMPLETE;
1145 }
1146
1147 int err;
1148 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1149
1150 int width = 0, height = 0;
1151 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001152 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001153 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1154 strerror(-err), err);
1155 }
1156 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001157 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001158 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1159 strerror(-err), err);
1160 }
1161
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001162 pRects[0].offset.x = 0;
1163 pRects[0].offset.y = 0;
1164 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1165 static_cast<uint32_t>(height)};
1166 }
1167 return VK_SUCCESS;
1168}
1169
Yiwei Zhang533cea92019-06-03 18:43:24 -07001170static void DestroySwapchainInternal(VkDevice device,
1171 VkSwapchainKHR swapchain_handle,
1172 const VkAllocationCallbacks* allocator) {
1173 ATRACE_CALL();
1174
1175 const auto& dispatch = GetData(device).driver;
1176 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1177 if (!swapchain) {
1178 return;
1179 }
1180
1181 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1182 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1183
1184 if (window && swapchain->frame_timestamps_enabled) {
1185 native_window_enable_frame_timestamps(window, false);
1186 }
1187
1188 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhangac1f0982022-04-09 07:10:10 +00001189 ReleaseSwapchainImage(device, swapchain->shared, window, -1,
1190 swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001191 }
1192
1193 if (active) {
1194 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1195 }
1196
1197 if (!allocator) {
1198 allocator = &GetData(device).allocator;
1199 }
1200
1201 swapchain->~Swapchain();
1202 allocator->pfnFree(allocator->pUserData, swapchain);
1203}
1204
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001205VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001206VkResult CreateSwapchainKHR(VkDevice device,
1207 const VkSwapchainCreateInfoKHR* create_info,
1208 const VkAllocationCallbacks* allocator,
1209 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001210 ATRACE_CALL();
1211
Jesse Halld7b994a2015-09-07 14:17:37 -07001212 int err;
1213 VkResult result = VK_SUCCESS;
1214
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001215 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1216 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1217 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1218 " oldSwapchain=0x%" PRIx64,
1219 reinterpret_cast<uint64_t>(create_info->surface),
1220 create_info->minImageCount, create_info->imageFormat,
1221 create_info->imageColorSpace, create_info->imageExtent.width,
1222 create_info->imageExtent.height, create_info->imageUsage,
1223 create_info->preTransform, create_info->presentMode,
1224 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1225
Jesse Hall1f91d392015-12-11 16:28:44 -08001226 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001227 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001228
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001229 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001230 GetNativePixelFormat(create_info->imageFormat);
1231 android_dataspace native_dataspace =
1232 GetNativeDataspace(create_info->imageColorSpace);
1233 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1234 ALOGE(
1235 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1236 "failed: Unsupported color space",
1237 create_info->imageColorSpace);
1238 return VK_ERROR_INITIALIZATION_FAILED;
1239 }
1240
Jesse Hall42a9eec2016-06-03 12:39:49 -07001241 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001242 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001243 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001244 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001245 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001246 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001247 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001248 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001249 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1250 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001251 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001252 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001253
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001254 Surface& surface = *SurfaceFromHandle(create_info->surface);
1255
Jesse Halldc225072016-05-30 22:40:14 -07001256 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001257 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001258 " because it already has active swapchain 0x%" PRIx64
1259 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1260 reinterpret_cast<uint64_t>(create_info->surface),
1261 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1262 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1263 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1264 }
1265 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1266 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1267
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001268 // -- Reset the native window --
1269 // The native window might have been used previously, and had its properties
1270 // changed from defaults. That will affect the answer we get for queries
1271 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1272 // attempt such queries.
1273
Jesse Halldc225072016-05-30 22:40:14 -07001274 // The native window only allows dequeueing all buffers before any have
1275 // been queued, since after that point at least one is assumed to be in
1276 // non-FREE state at any given time. Disconnecting and re-connecting
1277 // orphans the previous buffers, getting us back to the state where we can
1278 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001279 //
1280 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001281 ANativeWindow* window = surface.window.get();
1282 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1283 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001284 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001285 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1286 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001287 strerror(-err), err);
1288
Nicolas Capens147b7da2021-04-09 14:53:06 -04001289 err =
1290 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001291 if (err != android::OK) {
1292 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1293 strerror(-err), err);
1294 return VK_ERROR_SURFACE_LOST_KHR;
1295 }
1296
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301297 int swap_interval =
1298 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001299 err = window->setSwapInterval(window, swap_interval);
1300 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001301 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1302 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001303 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001304 }
1305
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001306 err = native_window_set_shared_buffer_mode(window, false);
1307 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001308 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1309 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001310 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001311 }
1312
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001313 err = native_window_set_auto_refresh(window, false);
1314 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001315 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1316 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001317 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001318 }
1319
Jesse Halld7b994a2015-09-07 14:17:37 -07001320 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001321
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001322 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001323
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001324 err = native_window_set_buffers_format(window, native_pixel_format);
1325 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001326 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1327 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001328 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001329 }
Yiwei Zhang51572c22022-07-22 23:08:30 +00001330
1331 /* Respect consumer default dataspace upon HAL_DATASPACE_ARBITRARY. */
1332 if (native_dataspace != HAL_DATASPACE_ARBITRARY) {
1333 err = native_window_set_buffers_data_space(window, native_dataspace);
1334 if (err != android::OK) {
1335 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
1336 native_dataspace, strerror(-err), err);
1337 return VK_ERROR_SURFACE_LOST_KHR;
1338 }
Jesse Hall517274a2016-02-10 00:07:18 -08001339 }
1340
Jesse Hall3dd678a2016-01-08 21:52:01 -08001341 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001342 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001343 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001344 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001345 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1346 create_info->imageExtent.width, create_info->imageExtent.height,
1347 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001348 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001349 }
1350
Jesse Hall178b6962016-02-24 15:39:50 -08001351 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1352 // applied during rendering. native_window_set_transform() expects the
1353 // inverse: the transform the app is requesting that the compositor perform
1354 // during composition. With native windows, pre-transform works by rendering
1355 // with the same transform the compositor is applying (as in Vulkan), but
1356 // then requesting the inverse transform, so that when the compositor does
1357 // it's job the two transforms cancel each other out and the compositor ends
1358 // up applying an identity transform to the app's buffer.
1359 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001360 window, InvertTransformToNative(create_info->preTransform));
1361 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001362 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1363 InvertTransformToNative(create_info->preTransform),
1364 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001365 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001366 }
1367
Jesse Hallf64ca122015-11-03 16:11:10 -08001368 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001369 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1370 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001371 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1372 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001373 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001374 }
1375
Chris Forbes97ef4612017-03-30 19:37:50 +13001376 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
Ian Elliottac40c1e2022-12-21 23:16:21 +00001377 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1378 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001379 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001380 err = native_window_set_shared_buffer_mode(window, true);
1381 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001382 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1383 return VK_ERROR_SURFACE_LOST_KHR;
1384 }
1385 }
1386
1387 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001388 err = native_window_set_auto_refresh(window, true);
1389 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001390 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1391 return VK_ERROR_SURFACE_LOST_KHR;
1392 }
1393 }
1394
Ian Elliott16c443c2021-11-30 17:10:32 -07001395 int query_value;
1396 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1397 &query_value);
1398 if (err != android::OK || query_value < 0) {
1399 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1400 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001401 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001402 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001403 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1404 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1405 const auto requested_images =
1406 swap_interval ? create_info->minImageCount : mailbox_num_images;
1407 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001408
Ian Elliott5396b702021-12-13 19:32:34 -07001409 // Lower layer insists that we have at least min_undequeued_buffers + 1
1410 // buffers. This is wasteful and we'd like to relax it in the shared case,
1411 // but not all the pieces are in place for that to work yet. Note we only
1412 // lie to the lower layer--we don't want to give the app back a swapchain
1413 // with extra images (which they can't actually use!).
1414 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1415 err = native_window_set_buffer_count(
1416 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001417 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001418 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1419 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001420 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001421 }
1422
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001423 // In shared mode the num_images must be one regardless of how many
1424 // buffers were allocated for the buffer queue.
1425 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1426 num_images = 1;
1427 }
1428
Trevor David Black2cc44682022-03-09 00:31:38 +00001429 void* usage_info_pNext = nullptr;
1430 VkImageCompressionControlEXT image_compression = {};
John Reck97678d42022-08-23 11:24:51 -04001431 uint64_t native_usage = 0;
Trevor David Black2cc44682022-03-09 00:31:38 +00001432 if (dispatch.GetSwapchainGrallocUsage3ANDROID) {
1433 ATRACE_BEGIN("GetSwapchainGrallocUsage3ANDROID");
1434 VkGrallocUsageInfoANDROID gralloc_usage_info = {};
1435 gralloc_usage_info.sType = VK_STRUCTURE_TYPE_GRALLOC_USAGE_INFO_ANDROID;
1436 gralloc_usage_info.format = create_info->imageFormat;
1437 gralloc_usage_info.imageUsage = create_info->imageUsage;
1438
1439 // Look through the pNext chain for an image compression control struct
1440 // if one is found AND the appropriate extensions are enabled,
1441 // append it to be the gralloc usage pNext chain
1442 const VkSwapchainCreateInfoKHR* create_infos = create_info;
1443 while (create_infos->pNext) {
1444 create_infos = reinterpret_cast<const VkSwapchainCreateInfoKHR*>(
1445 create_infos->pNext);
1446 switch (create_infos->sType) {
1447 case VK_STRUCTURE_TYPE_IMAGE_COMPRESSION_CONTROL_EXT: {
1448 const VkImageCompressionControlEXT* compression_infos =
1449 reinterpret_cast<const VkImageCompressionControlEXT*>(
1450 create_infos);
1451 image_compression = *compression_infos;
1452 image_compression.pNext = nullptr;
1453 usage_info_pNext = &image_compression;
1454 } break;
1455
1456 default:
1457 // Ignore all other info structs
1458 break;
1459 }
1460 }
1461 gralloc_usage_info.pNext = usage_info_pNext;
1462
1463 result = dispatch.GetSwapchainGrallocUsage3ANDROID(
1464 device, &gralloc_usage_info, &native_usage);
1465 ATRACE_END();
1466 if (result != VK_SUCCESS) {
1467 ALOGE("vkGetSwapchainGrallocUsage3ANDROID failed: %d", result);
1468 return VK_ERROR_SURFACE_LOST_KHR;
1469 }
1470 } else if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001471 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001472 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001473 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1474 device, create_info->imageFormat, create_info->imageUsage,
1475 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001476 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001477 if (result != VK_SUCCESS) {
1478 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001479 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001480 }
John Reck97678d42022-08-23 11:24:51 -04001481 native_usage =
Trevor David Black2cc44682022-03-09 00:31:38 +00001482 convertGralloc1ToBufferUsage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001483 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001484 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
John Reck97678d42022-08-23 11:24:51 -04001485 int32_t legacy_usage = 0;
Jesse Hall1f91d392015-12-11 16:28:44 -08001486 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001487 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001488 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001489 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001490 if (result != VK_SUCCESS) {
1491 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001492 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001493 }
John Reck97678d42022-08-23 11:24:51 -04001494 native_usage = static_cast<uint64_t>(legacy_usage);
Jesse Hall70f93352015-11-04 09:41:31 -08001495 }
John Reck97678d42022-08-23 11:24:51 -04001496 native_usage |= surface.consumer_usage;
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001497
1498 bool createProtectedSwapchain = false;
1499 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1500 createProtectedSwapchain = true;
1501 native_usage |= BufferUsage::PROTECTED;
1502 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001503 err = native_window_set_usage(window, native_usage);
1504 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001505 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001506 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001507 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001508
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001509 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001510 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1511 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001512 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1513 strerror(-err), err);
1514 return VK_ERROR_SURFACE_LOST_KHR;
1515 }
1516
Jesse Halld7b994a2015-09-07 14:17:37 -07001517 // -- Allocate our Swapchain object --
1518 // After this point, we must deallocate the swapchain on error.
1519
Jesse Hall1f91d392015-12-11 16:28:44 -08001520 void* mem = allocator->pfnAllocation(allocator->pUserData,
1521 sizeof(Swapchain), alignof(Swapchain),
1522 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001523 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001524 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001525 Swapchain* swapchain = new (mem)
1526 Swapchain(surface, num_images, create_info->presentMode,
1527 TranslateVulkanToNativeTransform(create_info->preTransform));
Ian Elliottac40c1e2022-12-21 23:16:21 +00001528 // -- Dequeue all buffers and create a VkImage for each --
1529 // Any failures during or after this must cancel the dequeued buffers.
Jesse Halld7b994a2015-09-07 14:17:37 -07001530
Chris Forbesb56287a2017-01-12 14:28:58 +13001531 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1532#pragma clang diagnostic push
1533#pragma clang diagnostic ignored "-Wold-style-cast"
1534 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1535#pragma clang diagnostic pop
Trevor David Black2cc44682022-03-09 00:31:38 +00001536 .pNext = usage_info_pNext,
Chris Forbesb56287a2017-01-12 14:28:58 +13001537 .usage = swapchain_image_usage,
1538 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001539 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001540#pragma clang diagnostic push
1541#pragma clang diagnostic ignored "-Wold-style-cast"
1542 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1543#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001544 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001545 };
1546 VkImageCreateInfo image_create = {
1547 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
Ian Elliottac40c1e2022-12-21 23:16:21 +00001548 .pNext = &image_native_buffer,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001549 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001550 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001551 .format = create_info->imageFormat,
Ian Elliottac40c1e2022-12-21 23:16:21 +00001552 .extent = {0, 0, 1},
Jesse Halld7b994a2015-09-07 14:17:37 -07001553 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001554 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001555 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001556 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001557 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001558 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001559 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001560 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1561 };
1562
Ian Elliottac40c1e2022-12-21 23:16:21 +00001563 for (uint32_t i = 0; i < num_images; i++) {
1564 Swapchain::Image& img = swapchain->images[i];
Jesse Halld7b994a2015-09-07 14:17:37 -07001565
Ian Elliottac40c1e2022-12-21 23:16:21 +00001566 ANativeWindowBuffer* buffer;
1567 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1568 if (err != android::OK) {
1569 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
1570 switch (-err) {
1571 case ENOMEM:
1572 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1573 break;
1574 default:
1575 result = VK_ERROR_SURFACE_LOST_KHR;
1576 break;
Yiwei Zhang702beb42019-11-29 17:59:55 -08001577 }
Ian Elliottac40c1e2022-12-21 23:16:21 +00001578 break;
Jesse Halld7b994a2015-09-07 14:17:37 -07001579 }
Ian Elliottac40c1e2022-12-21 23:16:21 +00001580 img.buffer = buffer;
1581 img.dequeued = true;
Jesse Halld7b994a2015-09-07 14:17:37 -07001582
Ian Elliottac40c1e2022-12-21 23:16:21 +00001583 image_create.extent =
1584 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
1585 static_cast<uint32_t>(img.buffer->height),
1586 1};
1587 image_native_buffer.handle = img.buffer->handle;
1588 image_native_buffer.stride = img.buffer->stride;
1589 image_native_buffer.format = img.buffer->format;
1590 image_native_buffer.usage = int(img.buffer->usage);
1591 android_convertGralloc0To1Usage(int(img.buffer->usage),
1592 &image_native_buffer.usage2.producer,
1593 &image_native_buffer.usage2.consumer);
1594 image_native_buffer.usage3 = img.buffer->usage;
Jesse Halld7b994a2015-09-07 14:17:37 -07001595
Ian Elliottac40c1e2022-12-21 23:16:21 +00001596 ATRACE_BEGIN("CreateImage");
1597 result =
1598 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
1599 ATRACE_END();
1600 if (result != VK_SUCCESS) {
1601 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1602 break;
Jesse Halld7b994a2015-09-07 14:17:37 -07001603 }
Ian Elliottac40c1e2022-12-21 23:16:21 +00001604 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001605
Ian Elliottac40c1e2022-12-21 23:16:21 +00001606 // -- Cancel all buffers, returning them to the queue --
1607 // If an error occurred before, also destroy the VkImage and release the
1608 // buffer reference. Otherwise, we retain a strong reference to the buffer.
1609 for (uint32_t i = 0; i < num_images; i++) {
1610 Swapchain::Image& img = swapchain->images[i];
1611 if (img.dequeued) {
1612 if (!swapchain->shared) {
1613 window->cancelBuffer(window, img.buffer.get(),
1614 img.dequeue_fence);
1615 img.dequeue_fence = -1;
1616 img.dequeued = false;
Chris Forbese0ced032017-03-30 19:44:15 +13001617 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001618 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001619 }
1620
1621 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001622 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1623 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001624 return result;
1625 }
1626
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001627 if (transform_hint != swapchain->pre_transform) {
1628 // Log that the app is not doing pre-rotation.
1629 android::GraphicsEnv::getInstance().setTargetStats(
1630 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1631 }
1632
Serdar Kocdemirb2901c92022-11-17 00:39:05 +00001633 // Set stats for creating a Vulkan swapchain
1634 android::GraphicsEnv::getInstance().setTargetStats(
1635 android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
1636
Jesse Halldc225072016-05-30 22:40:14 -07001637 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1638 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001639 return VK_SUCCESS;
1640}
1641
Jesse Halle1b12782015-11-30 11:27:32 -08001642VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001643void DestroySwapchainKHR(VkDevice device,
1644 VkSwapchainKHR swapchain_handle,
1645 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001646 ATRACE_CALL();
1647
Yiwei Zhang533cea92019-06-03 18:43:24 -07001648 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001649}
1650
Jesse Halle1b12782015-11-30 11:27:32 -08001651VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001652VkResult GetSwapchainImagesKHR(VkDevice,
1653 VkSwapchainKHR swapchain_handle,
1654 uint32_t* count,
1655 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001656 ATRACE_CALL();
1657
Jesse Halld7b994a2015-09-07 14:17:37 -07001658 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001659 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1660 "getting images for non-active swapchain 0x%" PRIx64
1661 "; only dequeued image handles are valid",
1662 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001663 VkResult result = VK_SUCCESS;
1664 if (images) {
1665 uint32_t n = swapchain.num_images;
1666 if (*count < swapchain.num_images) {
1667 n = *count;
1668 result = VK_INCOMPLETE;
1669 }
1670 for (uint32_t i = 0; i < n; i++)
1671 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001672 *count = n;
1673 } else {
1674 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001675 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001676 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001677}
1678
Jesse Halle1b12782015-11-30 11:27:32 -08001679VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001680VkResult AcquireNextImageKHR(VkDevice device,
1681 VkSwapchainKHR swapchain_handle,
1682 uint64_t timeout,
1683 VkSemaphore semaphore,
1684 VkFence vk_fence,
1685 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001686 ATRACE_CALL();
1687
Jesse Halld7b994a2015-09-07 14:17:37 -07001688 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001689 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001690 VkResult result;
1691 int err;
1692
Jesse Halldc225072016-05-30 22:40:14 -07001693 if (swapchain.surface.swapchain_handle != swapchain_handle)
1694 return VK_ERROR_OUT_OF_DATE_KHR;
1695
Chris Forbesc88409c2017-03-30 19:47:37 +13001696 if (swapchain.shared) {
1697 // In shared mode, we keep the buffer dequeued all the time, so we don't
1698 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1699 // the semaphore and fence passed to us will be signalled.
1700 *image_index = 0;
1701 result = GetData(device).driver.AcquireImageANDROID(
1702 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1703 return result;
1704 }
1705
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001706 const nsecs_t acquire_next_image_timeout =
1707 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1708 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1709 // Cache the timeout to avoid the duplicate binder cost.
1710 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1711 acquire_next_image_timeout);
1712 if (err != android::OK) {
1713 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1714 strerror(-err), err);
1715 return VK_ERROR_SURFACE_LOST_KHR;
1716 }
1717 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1718 }
1719
Jesse Halld7b994a2015-09-07 14:17:37 -07001720 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001721 int fence_fd;
1722 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001723 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001724 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1725 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1726 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001727 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001728 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001729 }
1730
1731 uint32_t idx;
1732 for (idx = 0; idx < swapchain.num_images; idx++) {
1733 if (swapchain.images[idx].buffer.get() == buffer) {
1734 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001735 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001736 break;
1737 }
1738 }
1739 if (idx == swapchain.num_images) {
1740 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001741 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001742 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001743 }
1744
1745 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001746 if (fence_fd != -1) {
1747 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001748 if (fence_clone == -1) {
1749 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1750 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001751 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001752 }
1753 }
1754
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001755 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001756 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001757 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001758 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1759 // even if the call fails. We could close it ourselves on failure, but
1760 // that would create a race condition if the driver closes it on a
1761 // failure path: some other thread might create an fd with the same
1762 // number between the time the driver closes it and the time we close
1763 // it. We must assume one of: the driver *always* closes it even on
1764 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001765 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001766 swapchain.images[idx].dequeued = false;
1767 swapchain.images[idx].dequeue_fence = -1;
1768 return result;
1769 }
1770
1771 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001772 return VK_SUCCESS;
1773}
1774
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001775VKAPI_ATTR
1776VkResult AcquireNextImage2KHR(VkDevice device,
1777 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1778 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001779 ATRACE_CALL();
1780
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001781 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1782 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1783 pAcquireInfo->fence, pImageIndex);
1784}
1785
Jesse Halldc225072016-05-30 22:40:14 -07001786static VkResult WorstPresentResult(VkResult a, VkResult b) {
1787 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1788 // (in spec version 1.0.14).
1789 static const VkResult kWorstToBest[] = {
1790 VK_ERROR_DEVICE_LOST,
1791 VK_ERROR_SURFACE_LOST_KHR,
1792 VK_ERROR_OUT_OF_DATE_KHR,
1793 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1794 VK_ERROR_OUT_OF_HOST_MEMORY,
1795 VK_SUBOPTIMAL_KHR,
1796 };
1797 for (auto result : kWorstToBest) {
1798 if (a == result || b == result)
1799 return result;
1800 }
1801 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1802 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1803 return a != VK_SUCCESS ? a : b;
1804}
1805
Chris Forbes4cd01fb2022-10-19 11:35:16 +13001806// KHR_incremental_present aspect of QueuePresentKHR
1807static void SetSwapchainSurfaceDamage(ANativeWindow *window, const VkPresentRegionKHR *pRegion) {
1808 std::vector<android_native_rect_t> rects(pRegion->rectangleCount);
1809 for (auto i = 0u; i < pRegion->rectangleCount; i++) {
1810 auto const& rect = pRegion->pRectangles[i];
1811 if (rect.layer > 0) {
1812 ALOGV("vkQueuePresentKHR ignoring invalid layer (%u); using layer 0 instead",
1813 rect.layer);
1814 }
1815
1816 rects[i].left = rect.offset.x;
1817 rects[i].bottom = rect.offset.y;
1818 rects[i].right = rect.offset.x + rect.extent.width;
1819 rects[i].top = rect.offset.y + rect.extent.height;
1820 }
1821 native_window_set_surface_damage(window, rects.data(), rects.size());
1822}
1823
1824// GOOGLE_display_timing aspect of QueuePresentKHR
1825static void SetSwapchainFrameTimestamp(Swapchain &swapchain, const VkPresentTimeGOOGLE *pTime) {
1826 ANativeWindow *window = swapchain.surface.window.get();
1827
1828 // We don't know whether the app will actually use GOOGLE_display_timing
1829 // with a particular swapchain until QueuePresent; enable it on the BQ
1830 // now if needed
1831 if (!swapchain.frame_timestamps_enabled) {
1832 ALOGV("Calling native_window_enable_frame_timestamps(true)");
1833 native_window_enable_frame_timestamps(window, true);
1834 swapchain.frame_timestamps_enabled = true;
1835 }
1836
1837 // Record the nativeFrameId so it can be later correlated to
1838 // this present.
1839 uint64_t nativeFrameId = 0;
1840 int err = native_window_get_next_frame_id(
1841 window, &nativeFrameId);
1842 if (err != android::OK) {
1843 ALOGE("Failed to get next native frame ID.");
1844 }
1845
1846 // Add a new timing record with the user's presentID and
1847 // the nativeFrameId.
1848 swapchain.timing.emplace_back(pTime, nativeFrameId);
1849 if (swapchain.timing.size() > MAX_TIMING_INFOS) {
1850 swapchain.timing.erase(
1851 swapchain.timing.begin(),
1852 swapchain.timing.begin() + swapchain.timing.size() - MAX_TIMING_INFOS);
1853 }
1854 if (pTime->desiredPresentTime) {
1855 ALOGV(
1856 "Calling native_window_set_buffers_timestamp(%" PRId64 ")",
1857 pTime->desiredPresentTime);
1858 native_window_set_buffers_timestamp(
1859 window,
1860 static_cast<int64_t>(pTime->desiredPresentTime));
1861 }
1862}
1863
1864static VkResult PresentOneSwapchain(
1865 VkQueue queue,
1866 Swapchain& swapchain,
1867 uint32_t imageIndex,
1868 const VkPresentRegionKHR *pRegion,
1869 const VkPresentTimeGOOGLE *pTime,
1870 uint32_t waitSemaphoreCount,
1871 const VkSemaphore *pWaitSemaphores) {
1872
1873 VkDevice device = GetData(queue).driver_device;
1874 const auto& dispatch = GetData(queue).driver;
1875
1876 Swapchain::Image& img = swapchain.images[imageIndex];
1877 VkResult swapchain_result = VK_SUCCESS;
1878 VkResult result;
1879 int err;
1880
1881 // XXX: long standing issue: QueueSignalReleaseImageANDROID consumes the
1882 // wait semaphores, so this doesn't actually work for the multiple swapchain
1883 // case.
1884 int fence = -1;
1885 result = dispatch.QueueSignalReleaseImageANDROID(
1886 queue, waitSemaphoreCount,
1887 pWaitSemaphores, img.image, &fence);
1888 if (result != VK_SUCCESS) {
1889 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
1890 swapchain_result = result;
1891 }
1892 if (img.release_fence >= 0)
1893 close(img.release_fence);
1894 img.release_fence = fence < 0 ? -1 : dup(fence);
1895
1896 if (swapchain.surface.swapchain_handle == HandleFromSwapchain(&swapchain)) {
1897 ANativeWindow* window = swapchain.surface.window.get();
1898 if (swapchain_result == VK_SUCCESS) {
1899
1900 if (pRegion) {
1901 SetSwapchainSurfaceDamage(window, pRegion);
1902 }
1903 if (pTime) {
1904 SetSwapchainFrameTimestamp(swapchain, pTime);
1905 }
1906
1907 err = window->queueBuffer(window, img.buffer.get(), fence);
1908 // queueBuffer always closes fence, even on error
1909 if (err != android::OK) {
1910 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1911 swapchain_result = WorstPresentResult(
1912 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
1913 } else {
1914 if (img.dequeue_fence >= 0) {
1915 close(img.dequeue_fence);
1916 img.dequeue_fence = -1;
1917 }
1918 img.dequeued = false;
1919 }
1920
1921 // If the swapchain is in shared mode, immediately dequeue the
1922 // buffer so it can be presented again without an intervening
1923 // call to AcquireNextImageKHR. We expect to get the same buffer
1924 // back from every call to dequeueBuffer in this mode.
1925 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
1926 ANativeWindowBuffer* buffer;
1927 int fence_fd;
1928 err = window->dequeueBuffer(window, &buffer, &fence_fd);
1929 if (err != android::OK) {
1930 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1931 swapchain_result = WorstPresentResult(swapchain_result,
1932 VK_ERROR_SURFACE_LOST_KHR);
1933 } else if (img.buffer != buffer) {
1934 ALOGE("got wrong image back for shared swapchain");
1935 swapchain_result = WorstPresentResult(swapchain_result,
1936 VK_ERROR_SURFACE_LOST_KHR);
1937 } else {
1938 img.dequeue_fence = fence_fd;
1939 img.dequeued = true;
1940 }
1941 }
1942 }
1943 if (swapchain_result != VK_SUCCESS) {
1944 OrphanSwapchain(device, &swapchain);
1945 }
1946 // Android will only return VK_SUBOPTIMAL_KHR for vkQueuePresentKHR,
1947 // and only when the window's transform/rotation changes. Extent
1948 // changes will not cause VK_SUBOPTIMAL_KHR because of the
1949 // application issues that were caused when the following transform
1950 // change was added.
1951 int window_transform_hint;
1952 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
1953 &window_transform_hint);
1954 if (err != android::OK) {
1955 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1956 strerror(-err), err);
1957 swapchain_result = WorstPresentResult(
1958 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
1959 }
1960 if (swapchain.pre_transform != window_transform_hint) {
1961 swapchain_result =
1962 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
1963 }
1964 } else {
1965 ReleaseSwapchainImage(device, swapchain.shared, nullptr, fence,
1966 img, true);
1967 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
1968 }
1969
1970 return swapchain_result;
1971}
1972
Jesse Halle1b12782015-11-30 11:27:32 -08001973VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001974VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001975 ATRACE_CALL();
1976
Jesse Halld7b994a2015-09-07 14:17:37 -07001977 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1978 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1979 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07001980
Jesse Halld7b994a2015-09-07 14:17:37 -07001981 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07001982
Ian Elliottcb351132016-12-13 10:30:40 -07001983 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001984 const VkPresentRegionsKHR* present_regions = nullptr;
1985 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001986 const VkPresentRegionsKHR* next =
1987 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1988 while (next) {
1989 switch (next->sType) {
1990 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1991 present_regions = next;
1992 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07001993 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001994 present_times =
1995 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1996 break;
Ian Elliottcb351132016-12-13 10:30:40 -07001997 default:
1998 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1999 next->sType);
2000 break;
2001 }
2002 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
2003 }
2004 ALOGV_IF(
2005 present_regions &&
2006 present_regions->swapchainCount != present_info->swapchainCount,
2007 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002008 ALOGV_IF(present_times &&
2009 present_times->swapchainCount != present_info->swapchainCount,
2010 "VkPresentTimesInfoGOOGLE::swapchainCount != "
2011 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -07002012 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002013 (present_regions) ? present_regions->pRegions : nullptr;
2014 const VkPresentTimeGOOGLE* times =
2015 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07002016
Jesse Halld7b994a2015-09-07 14:17:37 -07002017 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
2018 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08002019 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Halld7b994a2015-09-07 14:17:37 -07002020
Chris Forbes4cd01fb2022-10-19 11:35:16 +13002021 VkResult swapchain_result = PresentOneSwapchain(
2022 queue,
2023 swapchain,
2024 present_info->pImageIndices[sc],
2025 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr,
2026 times ? &times[sc] : nullptr,
2027 present_info->waitSemaphoreCount,
2028 present_info->pWaitSemaphores);
Jesse Halld7b994a2015-09-07 14:17:37 -07002029
Jesse Halla9e57032015-11-30 01:03:10 -08002030 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07002031 present_info->pResults[sc] = swapchain_result;
2032
2033 if (swapchain_result != final_result)
2034 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07002035 }
2036
2037 return final_result;
2038}
Jesse Hallb1352bc2015-09-04 16:12:33 -07002039
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002040VKAPI_ATTR
2041VkResult GetRefreshCycleDurationGOOGLE(
2042 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07002043 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002044 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002045 ATRACE_CALL();
2046
Ian Elliott62c48c92017-01-20 13:13:20 -07002047 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002048 VkResult result = VK_SUCCESS;
2049
Ian Elliott3568bfe2019-05-03 15:54:46 -06002050 pDisplayTimingProperties->refreshDuration = swapchain.get_refresh_duration();
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002051
2052 return result;
2053}
2054
2055VKAPI_ATTR
2056VkResult GetPastPresentationTimingGOOGLE(
2057 VkDevice,
2058 VkSwapchainKHR swapchain_handle,
2059 uint32_t* count,
2060 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002061 ATRACE_CALL();
2062
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002063 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002064 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2065 return VK_ERROR_OUT_OF_DATE_KHR;
2066 }
2067
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002068 ANativeWindow* window = swapchain.surface.window.get();
2069 VkResult result = VK_SUCCESS;
2070
2071 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07002072 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002073 native_window_enable_frame_timestamps(window, true);
2074 swapchain.frame_timestamps_enabled = true;
2075 }
2076
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002077 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07002078 // Get the latest ready timing count before copying, since the copied
2079 // timing info will be erased in copy_ready_timings function.
2080 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07002081 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07002082 // Check the *count here against the recorded ready timing count, since
2083 // *count can be overwritten per spec describes.
2084 if (*count < n) {
2085 result = VK_INCOMPLETE;
2086 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002087 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07002088 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07002089 }
2090
2091 return result;
2092}
2093
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002094VKAPI_ATTR
2095VkResult GetSwapchainStatusKHR(
2096 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13002097 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002098 ATRACE_CALL();
2099
Chris Forbes4e18ba82017-01-20 12:50:17 +13002100 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002101 VkResult result = VK_SUCCESS;
2102
Chris Forbes4e18ba82017-01-20 12:50:17 +13002103 if (swapchain.surface.swapchain_handle != swapchain_handle) {
2104 return VK_ERROR_OUT_OF_DATE_KHR;
2105 }
2106
Yiwei Zhanga885c062019-10-24 12:07:57 -07002107 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13002108
2109 return result;
2110}
2111
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002112VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002113 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002114 uint32_t swapchainCount,
2115 const VkSwapchainKHR* pSwapchains,
2116 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08002117 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08002118
2119 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
2120 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
2121 if (!swapchain)
2122 continue;
2123
2124 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
2125
2126 ANativeWindow* window = swapchain->surface.window.get();
2127
2128 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
2129 const android_smpte2086_metadata smpteMetdata = {
2130 {vulkanMetadata.displayPrimaryRed.x,
2131 vulkanMetadata.displayPrimaryRed.y},
2132 {vulkanMetadata.displayPrimaryGreen.x,
2133 vulkanMetadata.displayPrimaryGreen.y},
2134 {vulkanMetadata.displayPrimaryBlue.x,
2135 vulkanMetadata.displayPrimaryBlue.y},
2136 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
2137 vulkanMetadata.maxLuminance,
2138 vulkanMetadata.minLuminance};
2139 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
2140
2141 const android_cta861_3_metadata cta8613Metadata = {
2142 vulkanMetadata.maxContentLightLevel,
2143 vulkanMetadata.maxFrameAverageLightLevel};
2144 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
2145 }
2146
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07002147 return;
2148}
2149
Yiwei Zhang0f475222019-04-11 19:38:00 -07002150static void InterceptBindImageMemory2(
2151 uint32_t bind_info_count,
2152 const VkBindImageMemoryInfo* bind_infos,
2153 std::vector<VkNativeBufferANDROID>* out_native_buffers,
2154 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
2155 out_native_buffers->clear();
2156 out_bind_infos->clear();
2157
2158 if (!bind_info_count)
2159 return;
2160
2161 std::unordered_set<uint32_t> intercepted_indexes;
2162
2163 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2164 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2165 bind_infos[idx].pNext);
2166 while (info &&
2167 info->sType !=
2168 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2169 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2170 info->pNext);
2171 }
2172
2173 if (!info)
2174 continue;
2175
2176 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2177 "swapchain handle must not be NULL");
2178 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2179 ALOG_ASSERT(
2180 info->imageIndex < swapchain->num_images,
2181 "imageIndex must be less than the number of images in swapchain");
2182
2183 ANativeWindowBuffer* buffer =
2184 swapchain->images[info->imageIndex].buffer.get();
2185 VkNativeBufferANDROID native_buffer = {
2186#pragma clang diagnostic push
2187#pragma clang diagnostic ignored "-Wold-style-cast"
2188 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2189#pragma clang diagnostic pop
2190 .pNext = bind_infos[idx].pNext,
2191 .handle = buffer->handle,
2192 .stride = buffer->stride,
2193 .format = buffer->format,
2194 .usage = int(buffer->usage),
2195 };
2196 // Reserve enough space to avoid letting re-allocation invalidate the
2197 // addresses of the elements inside.
2198 out_native_buffers->reserve(bind_info_count);
2199 out_native_buffers->emplace_back(native_buffer);
2200
2201 // Reserve the space now since we know how much is needed now.
2202 out_bind_infos->reserve(bind_info_count);
2203 out_bind_infos->emplace_back(bind_infos[idx]);
2204 out_bind_infos->back().pNext = &out_native_buffers->back();
2205
2206 intercepted_indexes.insert(idx);
2207 }
2208
2209 if (intercepted_indexes.empty())
2210 return;
2211
2212 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2213 if (intercepted_indexes.count(idx))
2214 continue;
2215 out_bind_infos->emplace_back(bind_infos[idx]);
2216 }
2217}
2218
Yiwei Zhang23143102019-04-10 18:24:05 -07002219VKAPI_ATTR
2220VkResult BindImageMemory2(VkDevice device,
2221 uint32_t bindInfoCount,
2222 const VkBindImageMemoryInfo* pBindInfos) {
2223 ATRACE_CALL();
2224
Yiwei Zhang0f475222019-04-11 19:38:00 -07002225 // out_native_buffers is for maintaining the lifecycle of the constructed
2226 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2227 std::vector<VkNativeBufferANDROID> out_native_buffers;
2228 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2229 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2230 &out_bind_infos);
2231 return GetData(device).driver.BindImageMemory2(
2232 device, bindInfoCount,
2233 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002234}
2235
2236VKAPI_ATTR
2237VkResult BindImageMemory2KHR(VkDevice device,
2238 uint32_t bindInfoCount,
2239 const VkBindImageMemoryInfo* pBindInfos) {
2240 ATRACE_CALL();
2241
Yiwei Zhang0f475222019-04-11 19:38:00 -07002242 std::vector<VkNativeBufferANDROID> out_native_buffers;
2243 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2244 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2245 &out_bind_infos);
2246 return GetData(device).driver.BindImageMemory2KHR(
2247 device, bindInfoCount,
2248 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002249}
2250
Chia-I Wu62262232016-03-26 07:06:44 +08002251} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002252} // namespace vulkan