blob: 45bc4c95d91c88fedbe85b3136be85723045404e [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>
Mark Salyzyn7823e122016-09-29 08:08:05 -070022#include <log/log.h>
Jesse Halld7b994a2015-09-07 14:17:37 -070023#include <sync/sync.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070024#include <system/window.h>
25#include <ui/BufferQueueDefs.h>
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -050026#include <ui/DebugUtils.h>
27#include <ui/PixelFormat.h>
Chia-I Wue8e689f2016-04-18 08:21:31 +080028#include <utils/StrongPointer.h>
Yiwei Zhang705c2e62019-12-18 23:12:43 -080029#include <utils/Timers.h>
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -080030#include <utils/Trace.h>
Yiwei Zhang0f475222019-04-11 19:38:00 -070031
32#include <algorithm>
33#include <unordered_set>
34#include <vector>
Jesse Halld7b994a2015-09-07 14:17:37 -070035
Chia-I Wu4a6a9162016-03-26 07:17:34 +080036#include "driver.h"
Jesse Halld7b994a2015-09-07 14:17:37 -070037
Daniel Kochf25f5bb2017-10-05 00:26:58 -040038using android::hardware::graphics::common::V1_0::BufferUsage;
39
Chia-I Wu62262232016-03-26 07:06:44 +080040namespace vulkan {
41namespace driver {
Jesse Hall5ae3abb2015-10-08 14:00:22 -070042
Jesse Halld7b994a2015-09-07 14:17:37 -070043namespace {
44
Jesse Hall55bc0972016-02-23 16:43:29 -080045const VkSurfaceTransformFlagsKHR kSupportedTransforms =
46 VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
47 VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
48 VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR |
49 VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR |
Yiwei Zhang70a21962019-05-31 17:26:52 -070050 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR |
51 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR |
52 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR |
53 VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR |
Jesse Hall55bc0972016-02-23 16:43:29 -080054 VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
55
56VkSurfaceTransformFlagBitsKHR TranslateNativeToVulkanTransform(int native) {
57 // Native and Vulkan transforms are isomorphic, but are represented
58 // differently. Vulkan transforms are built up of an optional horizontal
59 // mirror, followed by a clockwise 0/90/180/270-degree rotation. Native
60 // transforms are built up from a horizontal flip, vertical flip, and
61 // 90-degree rotation, all optional but always in that order.
62
Jesse Hall55bc0972016-02-23 16:43:29 -080063 switch (native) {
Yiwei Zhang70a21962019-05-31 17:26:52 -070064 case 0:
Jesse Hall55bc0972016-02-23 16:43:29 -080065 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070066 case NATIVE_WINDOW_TRANSFORM_FLIP_H:
67 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR;
68 case NATIVE_WINDOW_TRANSFORM_FLIP_V:
69 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR;
70 case NATIVE_WINDOW_TRANSFORM_ROT_180:
Jesse Hall55bc0972016-02-23 16:43:29 -080071 return VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070072 case NATIVE_WINDOW_TRANSFORM_ROT_90:
Jesse Hall55bc0972016-02-23 16:43:29 -080073 return VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR;
Yiwei Zhang70a21962019-05-31 17:26:52 -070074 case NATIVE_WINDOW_TRANSFORM_FLIP_H | NATIVE_WINDOW_TRANSFORM_ROT_90:
75 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR;
76 case NATIVE_WINDOW_TRANSFORM_FLIP_V | NATIVE_WINDOW_TRANSFORM_ROT_90:
77 return VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR;
78 case NATIVE_WINDOW_TRANSFORM_ROT_270:
Jesse Hall55bc0972016-02-23 16:43:29 -080079 return VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR;
80 case NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY:
81 default:
82 return VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
83 }
84}
85
Yiwei Zhang70a21962019-05-31 17:26:52 -070086int TranslateVulkanToNativeTransform(VkSurfaceTransformFlagBitsKHR transform) {
87 switch (transform) {
88 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
89 return NATIVE_WINDOW_TRANSFORM_ROT_90;
90 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
91 return NATIVE_WINDOW_TRANSFORM_ROT_180;
92 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
93 return NATIVE_WINDOW_TRANSFORM_ROT_270;
94 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
95 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
96 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
97 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
98 NATIVE_WINDOW_TRANSFORM_ROT_90;
99 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
100 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
101 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
102 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
103 NATIVE_WINDOW_TRANSFORM_ROT_90;
104 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
105 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
106 default:
107 return 0;
108 }
109}
110
Jesse Hall178b6962016-02-24 15:39:50 -0800111int InvertTransformToNative(VkSurfaceTransformFlagBitsKHR transform) {
112 switch (transform) {
113 case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
114 return NATIVE_WINDOW_TRANSFORM_ROT_270;
115 case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
116 return NATIVE_WINDOW_TRANSFORM_ROT_180;
117 case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
118 return NATIVE_WINDOW_TRANSFORM_ROT_90;
Yiwei Zhang70a21962019-05-31 17:26:52 -0700119 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR:
120 return NATIVE_WINDOW_TRANSFORM_FLIP_H;
121 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR:
122 return NATIVE_WINDOW_TRANSFORM_FLIP_H |
123 NATIVE_WINDOW_TRANSFORM_ROT_90;
124 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR:
125 return NATIVE_WINDOW_TRANSFORM_FLIP_V;
126 case VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR:
127 return NATIVE_WINDOW_TRANSFORM_FLIP_V |
128 NATIVE_WINDOW_TRANSFORM_ROT_90;
Jesse Hall178b6962016-02-24 15:39:50 -0800129 case VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:
130 case VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR:
131 default:
132 return 0;
133 }
134}
135
Ian Elliott8a977262017-01-19 09:05:58 -0700136class TimingInfo {
137 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800138 TimingInfo(const VkPresentTimeGOOGLE* qp, uint64_t nativeFrameId)
Ian Elliott2c6355d2017-01-19 11:02:13 -0700139 : vals_{qp->presentID, qp->desiredPresentTime, 0, 0, 0},
Brian Anderson1049d1d2016-12-16 17:25:57 -0800140 native_frame_id_(nativeFrameId) {}
141 bool ready() const {
Brian Andersondc96fdf2017-03-20 16:54:25 -0700142 return (timestamp_desired_present_time_ !=
143 NATIVE_WINDOW_TIMESTAMP_PENDING &&
144 timestamp_actual_present_time_ !=
145 NATIVE_WINDOW_TIMESTAMP_PENDING &&
146 timestamp_render_complete_time_ !=
147 NATIVE_WINDOW_TIMESTAMP_PENDING &&
148 timestamp_composition_latch_time_ !=
149 NATIVE_WINDOW_TIMESTAMP_PENDING);
Ian Elliott8a977262017-01-19 09:05:58 -0700150 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700151 void calculate(int64_t rdur) {
152 bool anyTimestampInvalid =
153 (timestamp_actual_present_time_ ==
154 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
155 (timestamp_render_complete_time_ ==
156 NATIVE_WINDOW_TIMESTAMP_INVALID) ||
157 (timestamp_composition_latch_time_ ==
158 NATIVE_WINDOW_TIMESTAMP_INVALID);
159 if (anyTimestampInvalid) {
160 ALOGE("Unexpectedly received invalid timestamp.");
161 vals_.actualPresentTime = 0;
162 vals_.earliestPresentTime = 0;
163 vals_.presentMargin = 0;
164 return;
165 }
166
167 vals_.actualPresentTime =
168 static_cast<uint64_t>(timestamp_actual_present_time_);
169 int64_t margin = (timestamp_composition_latch_time_ -
Ian Elliott8a977262017-01-19 09:05:58 -0700170 timestamp_render_complete_time_);
171 // Calculate vals_.earliestPresentTime, and potentially adjust
172 // vals_.presentMargin. The initial value of vals_.earliestPresentTime
173 // is vals_.actualPresentTime. If we can subtract rdur (the duration
174 // of a refresh cycle) from vals_.earliestPresentTime (and also from
175 // vals_.presentMargin) and still leave a positive margin, then we can
176 // report to the application that it could have presented earlier than
177 // it did (per the extension specification). If for some reason, we
178 // can do this subtraction repeatedly, we do, since
179 // vals_.earliestPresentTime really is supposed to be the "earliest".
Brian Andersondc96fdf2017-03-20 16:54:25 -0700180 int64_t early_time = timestamp_actual_present_time_;
Ian Elliott8a977262017-01-19 09:05:58 -0700181 while ((margin > rdur) &&
182 ((early_time - rdur) > timestamp_composition_latch_time_)) {
183 early_time -= rdur;
184 margin -= rdur;
185 }
Brian Andersondc96fdf2017-03-20 16:54:25 -0700186 vals_.earliestPresentTime = static_cast<uint64_t>(early_time);
187 vals_.presentMargin = static_cast<uint64_t>(margin);
Ian Elliott8a977262017-01-19 09:05:58 -0700188 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800189 void get_values(VkPastPresentationTimingGOOGLE* values) const {
190 *values = vals_;
191 }
Ian Elliott8a977262017-01-19 09:05:58 -0700192
193 public:
Brian Anderson1049d1d2016-12-16 17:25:57 -0800194 VkPastPresentationTimingGOOGLE vals_ { 0, 0, 0, 0, 0 };
Ian Elliott8a977262017-01-19 09:05:58 -0700195
Brian Anderson1049d1d2016-12-16 17:25:57 -0800196 uint64_t native_frame_id_ { 0 };
Brian Andersondc96fdf2017-03-20 16:54:25 -0700197 int64_t timestamp_desired_present_time_{ NATIVE_WINDOW_TIMESTAMP_PENDING };
198 int64_t timestamp_actual_present_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
199 int64_t timestamp_render_complete_time_ { NATIVE_WINDOW_TIMESTAMP_PENDING };
200 int64_t timestamp_composition_latch_time_
201 { NATIVE_WINDOW_TIMESTAMP_PENDING };
Ian Elliott8a977262017-01-19 09:05:58 -0700202};
203
Jesse Hall1356b0d2015-11-23 17:24:58 -0800204struct Surface {
Chia-I Wue8e689f2016-04-18 08:21:31 +0800205 android::sp<ANativeWindow> window;
Jesse Halldc225072016-05-30 22:40:14 -0700206 VkSwapchainKHR swapchain_handle;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700207 uint64_t consumer_usage;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800208};
209
210VkSurfaceKHR HandleFromSurface(Surface* surface) {
211 return VkSurfaceKHR(reinterpret_cast<uint64_t>(surface));
212}
213
214Surface* SurfaceFromHandle(VkSurfaceKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800215 return reinterpret_cast<Surface*>(handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800216}
217
Ian Elliott8a977262017-01-19 09:05:58 -0700218// Maximum number of TimingInfo structs to keep per swapchain:
219enum { MAX_TIMING_INFOS = 10 };
220// Minimum number of frames to look for in the past (so we don't cause
221// syncronous requests to Surface Flinger):
222enum { MIN_NUM_FRAMES_AGO = 5 };
223
Jesse Hall1356b0d2015-11-23 17:24:58 -0800224struct Swapchain {
Ian Elliottffedb652017-02-14 10:58:30 -0700225 Swapchain(Surface& surface_,
226 uint32_t num_images_,
silence_dogood73597592019-05-23 16:57:37 -0700227 VkPresentModeKHR present_mode,
228 int pre_transform_)
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700229 : surface(surface_),
230 num_images(num_images_),
Ian Elliottffedb652017-02-14 10:58:30 -0700231 mailbox_mode(present_mode == VK_PRESENT_MODE_MAILBOX_KHR),
silence_dogood73597592019-05-23 16:57:37 -0700232 pre_transform(pre_transform_),
Chris Forbesf8835642017-03-30 19:31:40 +1300233 frame_timestamps_enabled(false),
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800234 acquire_next_image_timeout(-1),
Chris Forbesf8835642017-03-30 19:31:40 +1300235 shared(present_mode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800236 present_mode ==
237 VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Ian Elliott62c48c92017-01-20 13:13:20 -0700238 ANativeWindow* window = surface.window.get();
Ian Elliottbe833a22017-01-25 13:09:20 -0700239 native_window_get_refresh_cycle_duration(
Ian Elliott62c48c92017-01-20 13:13:20 -0700240 window,
Brian Andersondc96fdf2017-03-20 16:54:25 -0700241 &refresh_duration);
Ian Elliott8a977262017-01-19 09:05:58 -0700242 }
Ian Elliott3568bfe2019-05-03 15:54:46 -0600243 uint64_t get_refresh_duration()
244 {
245 ANativeWindow* window = surface.window.get();
246 native_window_get_refresh_cycle_duration(
247 window,
248 &refresh_duration);
249 return static_cast<uint64_t>(refresh_duration);
250
251 }
Jesse Hall1356b0d2015-11-23 17:24:58 -0800252
253 Surface& surface;
Jesse Halld7b994a2015-09-07 14:17:37 -0700254 uint32_t num_images;
Ian Elliottffedb652017-02-14 10:58:30 -0700255 bool mailbox_mode;
silence_dogood73597592019-05-23 16:57:37 -0700256 int pre_transform;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -0700257 bool frame_timestamps_enabled;
Brian Andersondc96fdf2017-03-20 16:54:25 -0700258 int64_t refresh_duration;
Yiwei Zhang705c2e62019-12-18 23:12:43 -0800259 nsecs_t acquire_next_image_timeout;
Chris Forbesf8835642017-03-30 19:31:40 +1300260 bool shared;
Jesse Halld7b994a2015-09-07 14:17:37 -0700261
262 struct Image {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700263 Image()
264 : image(VK_NULL_HANDLE),
265 dequeue_fence(-1),
266 release_fence(-1),
267 dequeued(false) {}
Jesse Halld7b994a2015-09-07 14:17:37 -0700268 VkImage image;
Chia-I Wue8e689f2016-04-18 08:21:31 +0800269 android::sp<ANativeWindowBuffer> buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -0700270 // The fence is only valid when the buffer is dequeued, and should be
271 // -1 any other time. When valid, we own the fd, and must ensure it is
272 // closed: either by closing it explicitly when queueing the buffer,
273 // or by passing ownership e.g. to ANativeWindow::cancelBuffer().
274 int dequeue_fence;
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700275 // This fence is a dup of the sync fd returned from the driver via
276 // vkQueueSignalReleaseImageANDROID upon vkQueuePresentKHR. We must
277 // ensure it is closed upon re-presenting or releasing the image.
278 int release_fence;
Jesse Halld7b994a2015-09-07 14:17:37 -0700279 bool dequeued;
Pawin Vongmasa6e1193a2017-03-07 13:08:40 -0800280 } images[android::BufferQueueDefs::NUM_BUFFER_SLOTS];
Ian Elliott8a977262017-01-19 09:05:58 -0700281
Yiwei Zhang5e862202019-06-21 14:59:16 -0700282 std::vector<TimingInfo> timing;
Jesse Halld7b994a2015-09-07 14:17:37 -0700283};
284
285VkSwapchainKHR HandleFromSwapchain(Swapchain* swapchain) {
286 return VkSwapchainKHR(reinterpret_cast<uint64_t>(swapchain));
287}
288
289Swapchain* SwapchainFromHandle(VkSwapchainKHR handle) {
Jesse Halla3a7a1d2015-11-24 11:37:23 -0800290 return reinterpret_cast<Swapchain*>(handle);
Jesse Halld7b994a2015-09-07 14:17:37 -0700291}
292
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700293static bool IsFencePending(int fd) {
294 if (fd < 0)
295 return false;
296
297 errno = 0;
298 return sync_wait(fd, 0 /* timeout */) == -1 && errno == ETIME;
299}
300
Jesse Halldc225072016-05-30 22:40:14 -0700301void ReleaseSwapchainImage(VkDevice device,
302 ANativeWindow* window,
303 int release_fence,
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700304 Swapchain::Image& image,
305 bool defer_if_pending) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700306 ATRACE_CALL();
307
Jesse Halldc225072016-05-30 22:40:14 -0700308 ALOG_ASSERT(release_fence == -1 || image.dequeued,
309 "ReleaseSwapchainImage: can't provide a release fence for "
310 "non-dequeued images");
311
312 if (image.dequeued) {
313 if (release_fence >= 0) {
314 // We get here from vkQueuePresentKHR. The application is
315 // responsible for creating an execution dependency chain from
316 // vkAcquireNextImage (dequeue_fence) to vkQueuePresentKHR
317 // (release_fence), so we can drop the dequeue_fence here.
318 if (image.dequeue_fence >= 0)
319 close(image.dequeue_fence);
320 } else {
321 // We get here during swapchain destruction, or various serious
322 // error cases e.g. when we can't create the release_fence during
323 // vkQueuePresentKHR. In non-error cases, the dequeue_fence should
324 // have already signalled, since the swapchain images are supposed
325 // to be idle before the swapchain is destroyed. In error cases,
326 // there may be rendering in flight to the image, but since we
327 // weren't able to create a release_fence, waiting for the
328 // dequeue_fence is about the best we can do.
329 release_fence = image.dequeue_fence;
330 }
331 image.dequeue_fence = -1;
332
333 if (window) {
334 window->cancelBuffer(window, image.buffer.get(), release_fence);
335 } else {
336 if (release_fence >= 0) {
337 sync_wait(release_fence, -1 /* forever */);
338 close(release_fence);
339 }
340 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700341 release_fence = -1;
Jesse Halldc225072016-05-30 22:40:14 -0700342 image.dequeued = false;
343 }
344
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700345 if (defer_if_pending && IsFencePending(image.release_fence))
346 return;
347
348 if (image.release_fence >= 0) {
349 close(image.release_fence);
350 image.release_fence = -1;
351 }
352
Jesse Halldc225072016-05-30 22:40:14 -0700353 if (image.image) {
Yiwei Zhang533cea92019-06-03 18:43:24 -0700354 ATRACE_BEGIN("DestroyImage");
Jesse Halldc225072016-05-30 22:40:14 -0700355 GetData(device).driver.DestroyImage(device, image.image, nullptr);
Yiwei Zhang533cea92019-06-03 18:43:24 -0700356 ATRACE_END();
Jesse Halldc225072016-05-30 22:40:14 -0700357 image.image = VK_NULL_HANDLE;
358 }
359
360 image.buffer.clear();
361}
362
363void OrphanSwapchain(VkDevice device, Swapchain* swapchain) {
364 if (swapchain->surface.swapchain_handle != HandleFromSwapchain(swapchain))
365 return;
Jesse Halldc225072016-05-30 22:40:14 -0700366 for (uint32_t i = 0; i < swapchain->num_images; i++) {
367 if (!swapchain->images[i].dequeued)
Yiwei Zhang9df5bff2020-09-22 10:08:03 -0700368 ReleaseSwapchainImage(device, nullptr, -1, swapchain->images[i],
369 true);
Jesse Halldc225072016-05-30 22:40:14 -0700370 }
371 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
Ian Elliott8a977262017-01-19 09:05:58 -0700372 swapchain->timing.clear();
373}
374
375uint32_t get_num_ready_timings(Swapchain& swapchain) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800376 if (swapchain.timing.size() < MIN_NUM_FRAMES_AGO) {
377 return 0;
378 }
Ian Elliott8a977262017-01-19 09:05:58 -0700379
Brian Anderson1049d1d2016-12-16 17:25:57 -0800380 uint32_t num_ready = 0;
381 const size_t num_timings = swapchain.timing.size() - MIN_NUM_FRAMES_AGO + 1;
382 for (uint32_t i = 0; i < num_timings; i++) {
Yiwei Zhang5e862202019-06-21 14:59:16 -0700383 TimingInfo& ti = swapchain.timing[i];
Brian Anderson1049d1d2016-12-16 17:25:57 -0800384 if (ti.ready()) {
385 // This TimingInfo is ready to be reported to the user. Add it
386 // to the num_ready.
387 num_ready++;
388 continue;
389 }
390 // This TimingInfo is not yet ready to be reported to the user,
391 // and so we should look for any available timestamps that
392 // might make it ready.
393 int64_t desired_present_time = 0;
394 int64_t render_complete_time = 0;
395 int64_t composition_latch_time = 0;
396 int64_t actual_present_time = 0;
397 // Obtain timestamps:
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800398 int err = native_window_get_frame_timestamps(
Brian Anderson1049d1d2016-12-16 17:25:57 -0800399 swapchain.surface.window.get(), ti.native_frame_id_,
400 &desired_present_time, &render_complete_time,
401 &composition_latch_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700402 nullptr, //&first_composition_start_time,
403 nullptr, //&last_composition_start_time,
404 nullptr, //&composition_finish_time,
Brian Anderson1049d1d2016-12-16 17:25:57 -0800405 &actual_present_time,
Yi Kongbcbc73a2018-07-18 10:13:04 -0700406 nullptr, //&dequeue_ready_time,
407 nullptr /*&reads_done_time*/);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800408
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800409 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800410 continue;
411 }
412
413 // Record the timestamp(s) we received, and then see if this TimingInfo
414 // is ready to be reported to the user:
Brian Andersondc96fdf2017-03-20 16:54:25 -0700415 ti.timestamp_desired_present_time_ = desired_present_time;
416 ti.timestamp_actual_present_time_ = actual_present_time;
417 ti.timestamp_render_complete_time_ = render_complete_time;
418 ti.timestamp_composition_latch_time_ = composition_latch_time;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800419
420 if (ti.ready()) {
421 // The TimingInfo has received enough timestamps, and should now
422 // use those timestamps to calculate the info that should be
423 // reported to the user:
424 ti.calculate(swapchain.refresh_duration);
425 num_ready++;
Ian Elliott8a977262017-01-19 09:05:58 -0700426 }
427 }
428 return num_ready;
429}
430
Ian Elliott8a977262017-01-19 09:05:58 -0700431void copy_ready_timings(Swapchain& swapchain,
432 uint32_t* count,
433 VkPastPresentationTimingGOOGLE* timings) {
Brian Anderson1049d1d2016-12-16 17:25:57 -0800434 if (swapchain.timing.empty()) {
435 *count = 0;
436 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700437 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800438
439 size_t last_ready = swapchain.timing.size() - 1;
440 while (!swapchain.timing[last_ready].ready()) {
441 if (last_ready == 0) {
442 *count = 0;
443 return;
Ian Elliott8a977262017-01-19 09:05:58 -0700444 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800445 last_ready--;
Ian Elliott8a977262017-01-19 09:05:58 -0700446 }
Brian Anderson1049d1d2016-12-16 17:25:57 -0800447
448 uint32_t num_copied = 0;
Yiwei Zhang5e862202019-06-21 14:59:16 -0700449 int32_t num_to_remove = 0;
Brian Anderson1049d1d2016-12-16 17:25:57 -0800450 for (uint32_t i = 0; i <= last_ready && num_copied < *count; i++) {
451 const TimingInfo& ti = swapchain.timing[i];
452 if (ti.ready()) {
453 ti.get_values(&timings[num_copied]);
454 num_copied++;
455 }
456 num_to_remove++;
457 }
458
459 // Discard old frames that aren't ready if newer frames are ready.
460 // We don't expect to get the timing info for those old frames.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700461 swapchain.timing.erase(swapchain.timing.begin(),
462 swapchain.timing.begin() + num_to_remove);
Brian Anderson1049d1d2016-12-16 17:25:57 -0800463
Ian Elliott8a977262017-01-19 09:05:58 -0700464 *count = num_copied;
Jesse Halldc225072016-05-30 22:40:14 -0700465}
466
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500467android::PixelFormat GetNativePixelFormat(VkFormat format) {
468 android::PixelFormat native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700469 switch (format) {
470 case VK_FORMAT_R8G8B8A8_UNORM:
471 case VK_FORMAT_R8G8B8A8_SRGB:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500472 native_format = android::PIXEL_FORMAT_RGBA_8888;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700473 break;
474 case VK_FORMAT_R5G6B5_UNORM_PACK16:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500475 native_format = android::PIXEL_FORMAT_RGB_565;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700476 break;
477 case VK_FORMAT_R16G16B16A16_SFLOAT:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500478 native_format = android::PIXEL_FORMAT_RGBA_FP16;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700479 break;
Yiwei Zhangc1ea8152019-02-05 15:11:32 -0800480 case VK_FORMAT_A2B10G10R10_UNORM_PACK32:
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500481 native_format = android::PIXEL_FORMAT_RGBA_1010102;
482 break;
483 case VK_FORMAT_R8_UNORM:
484 native_format = android::PIXEL_FORMAT_R_8;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700485 break;
486 default:
487 ALOGV("unsupported swapchain format %d", format);
488 break;
489 }
490 return native_format;
491}
492
493android_dataspace GetNativeDataspace(VkColorSpaceKHR colorspace) {
494 switch (colorspace) {
495 case VK_COLOR_SPACE_SRGB_NONLINEAR_KHR:
496 return HAL_DATASPACE_V0_SRGB;
497 case VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT:
498 return HAL_DATASPACE_DISPLAY_P3;
499 case VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT:
500 return HAL_DATASPACE_V0_SCRGB_LINEAR;
Courtney Goeltzenleuchterb52abee2017-08-07 17:13:04 -0600501 case VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT:
502 return HAL_DATASPACE_V0_SCRGB;
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700503 case VK_COLOR_SPACE_DCI_P3_LINEAR_EXT:
504 return HAL_DATASPACE_DCI_P3_LINEAR;
505 case VK_COLOR_SPACE_DCI_P3_NONLINEAR_EXT:
506 return HAL_DATASPACE_DCI_P3;
507 case VK_COLOR_SPACE_BT709_LINEAR_EXT:
508 return HAL_DATASPACE_V0_SRGB_LINEAR;
509 case VK_COLOR_SPACE_BT709_NONLINEAR_EXT:
510 return HAL_DATASPACE_V0_SRGB;
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600511 case VK_COLOR_SPACE_BT2020_LINEAR_EXT:
512 return HAL_DATASPACE_BT2020_LINEAR;
513 case VK_COLOR_SPACE_HDR10_ST2084_EXT:
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700514 return static_cast<android_dataspace>(
515 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
516 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchterc45673f2017-03-13 15:58:15 -0600517 case VK_COLOR_SPACE_DOLBYVISION_EXT:
518 return static_cast<android_dataspace>(
519 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_ST2084 |
520 HAL_DATASPACE_RANGE_FULL);
521 case VK_COLOR_SPACE_HDR10_HLG_EXT:
522 return static_cast<android_dataspace>(
523 HAL_DATASPACE_STANDARD_BT2020 | HAL_DATASPACE_TRANSFER_HLG |
524 HAL_DATASPACE_RANGE_FULL);
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -0700525 case VK_COLOR_SPACE_ADOBERGB_LINEAR_EXT:
526 return static_cast<android_dataspace>(
527 HAL_DATASPACE_STANDARD_ADOBE_RGB |
528 HAL_DATASPACE_TRANSFER_LINEAR | HAL_DATASPACE_RANGE_FULL);
529 case VK_COLOR_SPACE_ADOBERGB_NONLINEAR_EXT:
530 return HAL_DATASPACE_ADOBE_RGB;
531
532 // Pass through is intended to allow app to provide data that is passed
533 // to the display system without modification.
534 case VK_COLOR_SPACE_PASS_THROUGH_EXT:
535 return HAL_DATASPACE_ARBITRARY;
536
537 default:
538 // This indicates that we don't know about the
539 // dataspace specified and we should indicate that
540 // it's unsupported
541 return HAL_DATASPACE_UNKNOWN;
542 }
543}
544
Jesse Halld7b994a2015-09-07 14:17:37 -0700545} // anonymous namespace
Jesse Hallb1352bc2015-09-04 16:12:33 -0700546
Jesse Halle1b12782015-11-30 11:27:32 -0800547VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800548VkResult CreateAndroidSurfaceKHR(
Jesse Hallf9fa9a52016-01-08 16:08:51 -0800549 VkInstance instance,
550 const VkAndroidSurfaceCreateInfoKHR* pCreateInfo,
551 const VkAllocationCallbacks* allocator,
552 VkSurfaceKHR* out_surface) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800553 ATRACE_CALL();
554
Jesse Hall1f91d392015-12-11 16:28:44 -0800555 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800556 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800557 void* mem = allocator->pfnAllocation(allocator->pUserData, sizeof(Surface),
558 alignof(Surface),
559 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800560 if (!mem)
561 return VK_ERROR_OUT_OF_HOST_MEMORY;
562 Surface* surface = new (mem) Surface;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700563
Chia-I Wue8e689f2016-04-18 08:21:31 +0800564 surface->window = pCreateInfo->window;
Jesse Halldc225072016-05-30 22:40:14 -0700565 surface->swapchain_handle = VK_NULL_HANDLE;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700566 int err = native_window_get_consumer_usage(surface->window.get(),
567 &surface->consumer_usage);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800568 if (err != android::OK) {
Yiwei Zhang6435b322018-05-08 11:12:17 -0700569 ALOGE("native_window_get_consumer_usage() failed: %s (%d)",
570 strerror(-err), err);
571 surface->~Surface();
572 allocator->pfnFree(allocator->pUserData, surface);
Yiwei Zhang70a21962019-05-31 17:26:52 -0700573 return VK_ERROR_SURFACE_LOST_KHR;
Yiwei Zhang6435b322018-05-08 11:12:17 -0700574 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700575
Yiwei Zhang6435b322018-05-08 11:12:17 -0700576 err =
Jesse Hall1356b0d2015-11-23 17:24:58 -0800577 native_window_api_connect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Yiwei Zhangf5030b42019-12-19 00:10:04 -0800578 if (err != android::OK) {
Jesse Hall1356b0d2015-11-23 17:24:58 -0800579 ALOGE("native_window_api_connect() failed: %s (%d)", strerror(-err),
580 err);
581 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800582 allocator->pfnFree(allocator->pUserData, surface);
Mike Stroyan762c8132017-02-22 11:43:09 -0700583 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800584 }
Jesse Hallb1352bc2015-09-04 16:12:33 -0700585
Jesse Hall1356b0d2015-11-23 17:24:58 -0800586 *out_surface = HandleFromSurface(surface);
Jesse Hallb1352bc2015-09-04 16:12:33 -0700587 return VK_SUCCESS;
588}
589
Jesse Halle1b12782015-11-30 11:27:32 -0800590VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800591void DestroySurfaceKHR(VkInstance instance,
592 VkSurfaceKHR surface_handle,
593 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800594 ATRACE_CALL();
595
Jesse Hall1356b0d2015-11-23 17:24:58 -0800596 Surface* surface = SurfaceFromHandle(surface_handle);
597 if (!surface)
598 return;
599 native_window_api_disconnect(surface->window.get(), NATIVE_WINDOW_API_EGL);
Jesse Hall42a9eec2016-06-03 12:39:49 -0700600 ALOGV_IF(surface->swapchain_handle != VK_NULL_HANDLE,
Jesse Halldc225072016-05-30 22:40:14 -0700601 "destroyed VkSurfaceKHR 0x%" PRIx64
602 " has active VkSwapchainKHR 0x%" PRIx64,
603 reinterpret_cast<uint64_t>(surface_handle),
604 reinterpret_cast<uint64_t>(surface->swapchain_handle));
Jesse Hall1356b0d2015-11-23 17:24:58 -0800605 surface->~Surface();
Jesse Hall1f91d392015-12-11 16:28:44 -0800606 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +0800607 allocator = &GetData(instance).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -0800608 allocator->pfnFree(allocator->pUserData, surface);
Jesse Hall1356b0d2015-11-23 17:24:58 -0800609}
610
Jesse Halle1b12782015-11-30 11:27:32 -0800611VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800612VkResult GetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice /*pdev*/,
613 uint32_t /*queue_family*/,
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000614 VkSurfaceKHR /*surface_handle*/,
Chia-I Wu62262232016-03-26 07:06:44 +0800615 VkBool32* supported) {
Yiwei Zhangc7e46c42021-02-04 22:53:59 +0000616 *supported = VK_TRUE;
Jesse Halla6429252015-11-29 18:59:42 -0800617 return VK_SUCCESS;
Jesse Hall1356b0d2015-11-23 17:24:58 -0800618}
619
Jesse Halle1b12782015-11-30 11:27:32 -0800620VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +0800621VkResult GetPhysicalDeviceSurfaceCapabilitiesKHR(
Ian Elliott1ce053f2022-03-16 09:49:53 -0600622 VkPhysicalDevice pdev,
Jesse Hallb00daad2015-11-29 19:46:20 -0800623 VkSurfaceKHR surface,
624 VkSurfaceCapabilitiesKHR* capabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800625 ATRACE_CALL();
626
Jesse Halld7b994a2015-09-07 14:17:37 -0700627 int err;
Jesse Halld7b994a2015-09-07 14:17:37 -0700628 int width, height;
Jesse Hall55bc0972016-02-23 16:43:29 -0800629 int transform_hint;
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800630 int max_buffer_count;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600631 if (surface == VK_NULL_HANDLE) {
632 const InstanceData& instance_data = GetData(pdev);
633 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
634 bool surfaceless_enabled =
635 instance_data.hook_extensions.test(surfaceless);
636 if (!surfaceless_enabled) {
637 // It is an error to pass a surface==VK_NULL_HANDLE unless the
638 // VK_GOOGLE_surfaceless_query extension is enabled
639 return VK_ERROR_SURFACE_LOST_KHR;
640 }
641 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
642 // extension for this function is for
643 // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
644 // four values cannot be known without a surface. Default values will
645 // be supplied anyway, but cannot be relied upon.
646 width = 1000;
647 height = 1000;
648 transform_hint = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
649 max_buffer_count = 10;
650 } else {
651 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
652
653 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
654 if (err != android::OK) {
655 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
656 strerror(-err), err);
657 return VK_ERROR_SURFACE_LOST_KHR;
658 }
659 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
660 if (err != android::OK) {
661 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
662 strerror(-err), err);
663 return VK_ERROR_SURFACE_LOST_KHR;
664 }
665
666 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
667 &transform_hint);
668 if (err != android::OK) {
669 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
670 strerror(-err), err);
671 return VK_ERROR_SURFACE_LOST_KHR;
672 }
673
674 err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
675 &max_buffer_count);
676 if (err != android::OK) {
677 ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
678 strerror(-err), err);
679 return VK_ERROR_SURFACE_LOST_KHR;
680 }
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800681 }
Ian Elliott16c443c2021-11-30 17:10:32 -0700682 capabilities->minImageCount = std::min(max_buffer_count, 3);
Yiwei Zhangdbd96152018-02-08 14:22:53 -0800683 capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
Jesse Halld7b994a2015-09-07 14:17:37 -0700684
Jesse Hallfe2662d2016-02-09 13:26:59 -0800685 capabilities->currentExtent =
686 VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
687
Yiwei Zhang70a21962019-05-31 17:26:52 -0700688 // TODO(http://b/134182502): Figure out what the max extent should be.
Jesse Hallb00daad2015-11-29 19:46:20 -0800689 capabilities->minImageExtent = VkExtent2D{1, 1};
690 capabilities->maxImageExtent = VkExtent2D{4096, 4096};
Jesse Halld7b994a2015-09-07 14:17:37 -0700691
Jesse Hallfe2662d2016-02-09 13:26:59 -0800692 capabilities->maxImageArrayLayers = 1;
693
Jesse Hall55bc0972016-02-23 16:43:29 -0800694 capabilities->supportedTransforms = kSupportedTransforms;
695 capabilities->currentTransform =
696 TranslateNativeToVulkanTransform(transform_hint);
Jesse Halld7b994a2015-09-07 14:17:37 -0700697
Jesse Hallfe2662d2016-02-09 13:26:59 -0800698 // On Android, window composition is a WindowManager property, not something
699 // associated with the bufferqueue. It can't be changed from here.
700 capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -0700701
Jesse Hallb00daad2015-11-29 19:46:20 -0800702 capabilities->supportedUsageFlags =
Jesse Hall3fbc8562015-11-29 22:10:52 -0800703 VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
704 VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
705 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
Jesse Halld7b994a2015-09-07 14:17:37 -0700706 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
707
Jesse Hallb1352bc2015-09-04 16:12:33 -0700708 return VK_SUCCESS;
709}
710
Jesse Halle1b12782015-11-30 11:27:32 -0800711VKAPI_ATTR
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700712VkResult GetPhysicalDeviceSurfaceFormatsKHR(VkPhysicalDevice pdev,
713 VkSurfaceKHR surface_handle,
Chia-I Wu62262232016-03-26 07:06:44 +0800714 uint32_t* count,
715 VkSurfaceFormatKHR* formats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800716 ATRACE_CALL();
717
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700718 const InstanceData& instance_data = GetData(pdev);
719
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700720 bool wide_color_support = false;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600721 uint64_t consumer_usage = 0;
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000722 bool colorspace_ext =
Ian Elliottf6df08e2022-03-16 21:27:49 -0600723 instance_data.hook_extensions.test(ProcHook::EXT_swapchain_colorspace);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600724 if (surface_handle == VK_NULL_HANDLE) {
725 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
726 bool surfaceless_enabled =
727 instance_data.hook_extensions.test(surfaceless);
728 if (!surfaceless_enabled) {
729 return VK_ERROR_SURFACE_LOST_KHR;
730 }
731 // Support for VK_GOOGLE_surfaceless_query. The EGL loader
732 // unconditionally supports wide color formats, even if they will cause
733 // a SurfaceFlinger fallback. Based on that, wide_color_support will be
734 // set to true in this case.
735 wide_color_support = true;
736
737 // TODO(b/203826952): research proper value; temporarily use the
738 // values seen on Pixel
739 consumer_usage = AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY;
740 } else {
741 Surface& surface = *SurfaceFromHandle(surface_handle);
742 int err = native_window_get_wide_color_support(surface.window.get(),
743 &wide_color_support);
744 if (err) {
745 return VK_ERROR_SURFACE_LOST_KHR;
746 }
747 ALOGV("wide_color_support is: %d", wide_color_support);
748
749 consumer_usage = surface.consumer_usage;
Ian Elliott6ba85d92022-02-18 16:44:58 -0700750 }
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000751 wide_color_support = wide_color_support && colorspace_ext;
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700752
Charlie Lao324191f2019-12-13 11:03:16 -0800753 AHardwareBuffer_Desc desc = {};
754 desc.width = 1;
755 desc.height = 1;
756 desc.layers = 1;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600757 desc.usage = consumer_usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
Charlie Lao324191f2019-12-13 11:03:16 -0800758 AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER;
759
760 // We must support R8G8B8A8
761 std::vector<VkSurfaceFormatKHR> all_formats = {
762 {VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR},
Trevor David Black320ef3a2022-03-09 22:50:09 +0000763 {VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR}};
Charlie Lao324191f2019-12-13 11:03:16 -0800764
Trevor David Black5e13d0c2022-03-10 21:18:35 +0000765 if (colorspace_ext) {
766 all_formats.emplace_back(VkSurfaceFormatKHR{
767 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_BT709_LINEAR_EXT});
768 }
769
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700770 if (wide_color_support) {
Charlie Lao324191f2019-12-13 11:03:16 -0800771 all_formats.emplace_back(VkSurfaceFormatKHR{
772 VK_FORMAT_R8G8B8A8_UNORM, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
773 all_formats.emplace_back(VkSurfaceFormatKHR{
774 VK_FORMAT_R8G8B8A8_SRGB, VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
775 }
776
Ian Elliott1ce053f2022-03-16 09:49:53 -0600777 // NOTE: Any new formats that are added must be coordinated across different
778 // Android users. This includes the ANGLE team (a layered implementation of
779 // OpenGL-ES).
780
Charlie Lao324191f2019-12-13 11:03:16 -0800781 desc.format = AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;
782 if (AHardwareBuffer_isSupported(&desc)) {
783 all_formats.emplace_back(VkSurfaceFormatKHR{
784 VK_FORMAT_R5G6B5_UNORM_PACK16, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
785 }
786
787 desc.format = AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;
788 if (AHardwareBuffer_isSupported(&desc)) {
789 all_formats.emplace_back(VkSurfaceFormatKHR{
790 VK_FORMAT_R16G16B16A16_SFLOAT, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
791 if (wide_color_support) {
792 all_formats.emplace_back(
793 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
794 VK_COLOR_SPACE_EXTENDED_SRGB_LINEAR_EXT});
795 all_formats.emplace_back(
796 VkSurfaceFormatKHR{VK_FORMAT_R16G16B16A16_SFLOAT,
797 VK_COLOR_SPACE_EXTENDED_SRGB_NONLINEAR_EXT});
798 }
799 }
800
801 desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;
802 if (AHardwareBuffer_isSupported(&desc)) {
803 all_formats.emplace_back(
804 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
805 VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
806 if (wide_color_support) {
807 all_formats.emplace_back(
808 VkSurfaceFormatKHR{VK_FORMAT_A2B10G10R10_UNORM_PACK32,
809 VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
810 }
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700811 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700812
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -0500813 desc.format = AHARDWAREBUFFER_FORMAT_R8_UNORM;
814 if (AHardwareBuffer_isSupported(&desc)) {
815 all_formats.emplace_back(
816 VkSurfaceFormatKHR{VK_FORMAT_R8_UNORM,
817 VK_COLOR_SPACE_PASS_THROUGH_EXT});
818 }
819
Ian Elliott6ba85d92022-02-18 16:44:58 -0700820 // NOTE: Any new formats that are added must be coordinated across different
821 // Android users. This includes the ANGLE team (a layered implementation of
822 // OpenGL-ES).
823
Jesse Halld7b994a2015-09-07 14:17:37 -0700824 VkResult result = VK_SUCCESS;
825 if (formats) {
Charlie Lao324191f2019-12-13 11:03:16 -0800826 uint32_t transfer_count = all_formats.size();
827 if (transfer_count > *count) {
828 transfer_count = *count;
Jesse Halld7b994a2015-09-07 14:17:37 -0700829 result = VK_INCOMPLETE;
Courtney Goeltzenleuchtere278daf2017-02-02 16:54:57 -0700830 }
Charlie Lao324191f2019-12-13 11:03:16 -0800831 std::copy(all_formats.begin(), all_formats.begin() + transfer_count,
832 formats);
833 *count = transfer_count;
Jesse Hall7331e222016-09-15 21:26:01 -0700834 } else {
Charlie Lao324191f2019-12-13 11:03:16 -0800835 *count = all_formats.size();
Jesse Halld7b994a2015-09-07 14:17:37 -0700836 }
Charlie Lao324191f2019-12-13 11:03:16 -0800837
Jesse Halld7b994a2015-09-07 14:17:37 -0700838 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700839}
840
Jesse Halle1b12782015-11-30 11:27:32 -0800841VKAPI_ATTR
Chris Forbes2452cf72017-03-16 16:30:17 +1300842VkResult GetPhysicalDeviceSurfaceCapabilities2KHR(
843 VkPhysicalDevice physicalDevice,
844 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
845 VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800846 ATRACE_CALL();
847
Chris Forbes2452cf72017-03-16 16:30:17 +1300848 VkResult result = GetPhysicalDeviceSurfaceCapabilitiesKHR(
849 physicalDevice, pSurfaceInfo->surface,
850 &pSurfaceCapabilities->surfaceCapabilities);
851
Chris Forbes06bc0092017-03-16 16:46:05 +1300852 VkSurfaceCapabilities2KHR* caps = pSurfaceCapabilities;
853 while (caps->pNext) {
854 caps = reinterpret_cast<VkSurfaceCapabilities2KHR*>(caps->pNext);
855
856 switch (caps->sType) {
857 case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
858 VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
859 reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(
860 caps);
861 // Claim same set of usage flags are supported for
862 // shared present modes as for other modes.
863 shared_caps->sharedPresentSupportedUsageFlags =
864 pSurfaceCapabilities->surfaceCapabilities
865 .supportedUsageFlags;
866 } break;
867
Ian Elliottbb67b242022-03-16 09:52:28 -0600868 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
869 VkSurfaceProtectedCapabilitiesKHR* protected_caps =
870 reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(caps);
871 protected_caps->supportsProtected = VK_TRUE;
872 } break;
873
Chris Forbes06bc0092017-03-16 16:46:05 +1300874 default:
875 // Ignore all other extension structs
876 break;
877 }
878 }
879
Chris Forbes2452cf72017-03-16 16:30:17 +1300880 return result;
881}
882
883VKAPI_ATTR
884VkResult GetPhysicalDeviceSurfaceFormats2KHR(
885 VkPhysicalDevice physicalDevice,
886 const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo,
887 uint32_t* pSurfaceFormatCount,
888 VkSurfaceFormat2KHR* pSurfaceFormats) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800889 ATRACE_CALL();
890
Chris Forbes2452cf72017-03-16 16:30:17 +1300891 if (!pSurfaceFormats) {
892 return GetPhysicalDeviceSurfaceFormatsKHR(physicalDevice,
893 pSurfaceInfo->surface,
894 pSurfaceFormatCount, nullptr);
895 } else {
896 // temp vector for forwarding; we'll marshal it into the pSurfaceFormats
897 // after the call.
Yiwei Zhang5e862202019-06-21 14:59:16 -0700898 std::vector<VkSurfaceFormatKHR> surface_formats(*pSurfaceFormatCount);
Chris Forbes2452cf72017-03-16 16:30:17 +1300899 VkResult result = GetPhysicalDeviceSurfaceFormatsKHR(
900 physicalDevice, pSurfaceInfo->surface, pSurfaceFormatCount,
Yiwei Zhang5e862202019-06-21 14:59:16 -0700901 surface_formats.data());
Chris Forbes2452cf72017-03-16 16:30:17 +1300902
903 if (result == VK_SUCCESS || result == VK_INCOMPLETE) {
904 // marshal results individually due to stride difference.
905 // completely ignore any chained extension structs.
906 uint32_t formats_to_marshal = *pSurfaceFormatCount;
907 for (uint32_t i = 0u; i < formats_to_marshal; i++) {
908 pSurfaceFormats[i].surfaceFormat = surface_formats[i];
909 }
910 }
911
912 return result;
913 }
914}
915
916VKAPI_ATTR
Chris Forbese8d79a62017-02-22 12:49:18 +1300917VkResult GetPhysicalDeviceSurfacePresentModesKHR(VkPhysicalDevice pdev,
Yiwei Zhange4a559c2018-02-15 11:27:36 -0800918 VkSurfaceKHR surface,
Chia-I Wu62262232016-03-26 07:06:44 +0800919 uint32_t* count,
920 VkPresentModeKHR* modes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800921 ATRACE_CALL();
922
Yiwei Zhange4a559c2018-02-15 11:27:36 -0800923 int err;
924 int query_value;
Ian Elliotte7f036c2022-03-15 16:49:21 -0600925 std::vector<VkPresentModeKHR> present_modes;
Ian Elliott1ce053f2022-03-16 09:49:53 -0600926 if (surface == VK_NULL_HANDLE) {
927 const InstanceData& instance_data = GetData(pdev);
928 ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
929 bool surfaceless_enabled =
930 instance_data.hook_extensions.test(surfaceless);
931 if (!surfaceless_enabled) {
932 return VK_ERROR_SURFACE_LOST_KHR;
933 }
934 // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
935 // extension for this function is for
936 // VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR and
937 // VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR. We technically cannot
938 // know if VK_PRESENT_MODE_SHARED_MAILBOX_KHR is supported without a
939 // surface, and that cannot be relied upon.
Ian Elliotte7f036c2022-03-15 16:49:21 -0600940 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
Ian Elliott1ce053f2022-03-16 09:49:53 -0600941 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
942 } else {
943 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
944
945 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
946 &query_value);
947 if (err != android::OK || query_value < 0) {
948 ALOGE(
949 "NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d) "
950 "value=%d",
951 strerror(-err), err, query_value);
952 return VK_ERROR_SURFACE_LOST_KHR;
953 }
954 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
955
956 err =
957 window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT, &query_value);
958 if (err != android::OK || query_value < 0) {
959 ALOGE(
960 "NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d) value=%d",
961 strerror(-err), err, query_value);
962 return VK_ERROR_SURFACE_LOST_KHR;
963 }
964 uint32_t max_buffer_count = static_cast<uint32_t>(query_value);
965
966 if (min_undequeued_buffers + 1 < max_buffer_count)
967 present_modes.push_back(VK_PRESENT_MODE_MAILBOX_KHR);
968 present_modes.push_back(VK_PRESENT_MODE_FIFO_KHR);
969 }
Chris Forbese8d79a62017-02-22 12:49:18 +1300970
971 VkPhysicalDevicePresentationPropertiesANDROID present_properties;
Yiwei Zhang93b521c2020-07-11 16:32:09 -0700972 QueryPresentationProperties(pdev, &present_properties);
973 if (present_properties.sharedImage) {
974 present_modes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
975 present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
Chris Forbese8d79a62017-02-22 12:49:18 +1300976 }
977
978 uint32_t num_modes = uint32_t(present_modes.size());
Jesse Halld7b994a2015-09-07 14:17:37 -0700979
980 VkResult result = VK_SUCCESS;
981 if (modes) {
Chris Forbese8d79a62017-02-22 12:49:18 +1300982 if (*count < num_modes)
Jesse Halld7b994a2015-09-07 14:17:37 -0700983 result = VK_INCOMPLETE;
Chris Forbese8d79a62017-02-22 12:49:18 +1300984 *count = std::min(*count, num_modes);
Yiwei Zhang5e862202019-06-21 14:59:16 -0700985 std::copy_n(present_modes.data(), *count, modes);
Jesse Hall7331e222016-09-15 21:26:01 -0700986 } else {
Chris Forbese8d79a62017-02-22 12:49:18 +1300987 *count = num_modes;
Jesse Halld7b994a2015-09-07 14:17:37 -0700988 }
Jesse Halld7b994a2015-09-07 14:17:37 -0700989 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -0700990}
991
Jesse Halle1b12782015-11-30 11:27:32 -0800992VKAPI_ATTR
Daniel Kochf25f5bb2017-10-05 00:26:58 -0400993VkResult GetDeviceGroupPresentCapabilitiesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -0600994 VkDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -0400995 VkDeviceGroupPresentCapabilitiesKHR* pDeviceGroupPresentCapabilities) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -0800996 ATRACE_CALL();
997
Daniel Kochf25f5bb2017-10-05 00:26:58 -0400998 ALOGV_IF(pDeviceGroupPresentCapabilities->sType !=
999 VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHR,
1000 "vkGetDeviceGroupPresentCapabilitiesKHR: invalid "
1001 "VkDeviceGroupPresentCapabilitiesKHR structure type %d",
1002 pDeviceGroupPresentCapabilities->sType);
1003
1004 memset(pDeviceGroupPresentCapabilities->presentMask, 0,
1005 sizeof(pDeviceGroupPresentCapabilities->presentMask));
1006
1007 // assume device group of size 1
1008 pDeviceGroupPresentCapabilities->presentMask[0] = 1 << 0;
1009 pDeviceGroupPresentCapabilities->modes =
1010 VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1011
1012 return VK_SUCCESS;
1013}
1014
1015VKAPI_ATTR
1016VkResult GetDeviceGroupSurfacePresentModesKHR(
Ian Elliottcd8ad332017-10-13 09:21:12 -06001017 VkDevice,
1018 VkSurfaceKHR,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001019 VkDeviceGroupPresentModeFlagsKHR* pModes) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001020 ATRACE_CALL();
1021
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001022 *pModes = VK_DEVICE_GROUP_PRESENT_MODE_LOCAL_BIT_KHR;
1023 return VK_SUCCESS;
1024}
1025
1026VKAPI_ATTR
Ian Elliottcd8ad332017-10-13 09:21:12 -06001027VkResult GetPhysicalDevicePresentRectanglesKHR(VkPhysicalDevice,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001028 VkSurfaceKHR surface,
1029 uint32_t* pRectCount,
1030 VkRect2D* pRects) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001031 ATRACE_CALL();
1032
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001033 if (!pRects) {
1034 *pRectCount = 1;
1035 } else {
1036 uint32_t count = std::min(*pRectCount, 1u);
1037 bool incomplete = *pRectCount < 1;
1038
1039 *pRectCount = count;
1040
1041 if (incomplete) {
1042 return VK_INCOMPLETE;
1043 }
1044
1045 int err;
1046 ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
1047
1048 int width = 0, height = 0;
1049 err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001050 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001051 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1052 strerror(-err), err);
1053 }
1054 err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001055 if (err != android::OK) {
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001056 ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
1057 strerror(-err), err);
1058 }
1059
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001060 pRects[0].offset.x = 0;
1061 pRects[0].offset.y = 0;
1062 pRects[0].extent = VkExtent2D{static_cast<uint32_t>(width),
1063 static_cast<uint32_t>(height)};
1064 }
1065 return VK_SUCCESS;
1066}
1067
Yiwei Zhang533cea92019-06-03 18:43:24 -07001068static void DestroySwapchainInternal(VkDevice device,
1069 VkSwapchainKHR swapchain_handle,
1070 const VkAllocationCallbacks* allocator) {
1071 ATRACE_CALL();
1072
1073 const auto& dispatch = GetData(device).driver;
1074 Swapchain* swapchain = SwapchainFromHandle(swapchain_handle);
1075 if (!swapchain) {
1076 return;
1077 }
1078
1079 bool active = swapchain->surface.swapchain_handle == swapchain_handle;
1080 ANativeWindow* window = active ? swapchain->surface.window.get() : nullptr;
1081
1082 if (window && swapchain->frame_timestamps_enabled) {
1083 native_window_enable_frame_timestamps(window, false);
1084 }
1085
1086 for (uint32_t i = 0; i < swapchain->num_images; i++) {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -07001087 ReleaseSwapchainImage(device, window, -1, swapchain->images[i], false);
Yiwei Zhang533cea92019-06-03 18:43:24 -07001088 }
1089
1090 if (active) {
1091 swapchain->surface.swapchain_handle = VK_NULL_HANDLE;
1092 }
1093
1094 if (!allocator) {
1095 allocator = &GetData(device).allocator;
1096 }
1097
1098 swapchain->~Swapchain();
1099 allocator->pfnFree(allocator->pUserData, swapchain);
1100}
1101
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001102VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001103VkResult CreateSwapchainKHR(VkDevice device,
1104 const VkSwapchainCreateInfoKHR* create_info,
1105 const VkAllocationCallbacks* allocator,
1106 VkSwapchainKHR* swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001107 ATRACE_CALL();
1108
Jesse Halld7b994a2015-09-07 14:17:37 -07001109 int err;
1110 VkResult result = VK_SUCCESS;
1111
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001112 ALOGV("vkCreateSwapchainKHR: surface=0x%" PRIx64
1113 " minImageCount=%u imageFormat=%u imageColorSpace=%u"
1114 " imageExtent=%ux%u imageUsage=%#x preTransform=%u presentMode=%u"
1115 " oldSwapchain=0x%" PRIx64,
1116 reinterpret_cast<uint64_t>(create_info->surface),
1117 create_info->minImageCount, create_info->imageFormat,
1118 create_info->imageColorSpace, create_info->imageExtent.width,
1119 create_info->imageExtent.height, create_info->imageUsage,
1120 create_info->preTransform, create_info->presentMode,
1121 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1122
Jesse Hall1f91d392015-12-11 16:28:44 -08001123 if (!allocator)
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001124 allocator = &GetData(device).allocator;
Jesse Hall1f91d392015-12-11 16:28:44 -08001125
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001126 android::PixelFormat native_pixel_format =
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001127 GetNativePixelFormat(create_info->imageFormat);
1128 android_dataspace native_dataspace =
1129 GetNativeDataspace(create_info->imageColorSpace);
1130 if (native_dataspace == HAL_DATASPACE_UNKNOWN) {
1131 ALOGE(
1132 "CreateSwapchainKHR(VkSwapchainCreateInfoKHR.imageColorSpace = %d) "
1133 "failed: Unsupported color space",
1134 create_info->imageColorSpace);
1135 return VK_ERROR_INITIALIZATION_FAILED;
1136 }
1137
Jesse Hall42a9eec2016-06-03 12:39:49 -07001138 ALOGV_IF(create_info->imageArrayLayers != 1,
Jesse Halldc225072016-05-30 22:40:14 -07001139 "swapchain imageArrayLayers=%u not supported",
Jesse Hall715b86a2016-01-16 16:34:29 -08001140 create_info->imageArrayLayers);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001141 ALOGV_IF((create_info->preTransform & ~kSupportedTransforms) != 0,
Jesse Halldc225072016-05-30 22:40:14 -07001142 "swapchain preTransform=%#x not supported",
Jesse Hall55bc0972016-02-23 16:43:29 -08001143 create_info->preTransform);
Jesse Hall42a9eec2016-06-03 12:39:49 -07001144 ALOGV_IF(!(create_info->presentMode == VK_PRESENT_MODE_FIFO_KHR ||
Chris Forbes980ad052017-01-18 16:55:07 +13001145 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ||
Chris Forbes1d5f68c2017-01-31 10:17:01 +13001146 create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1147 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR),
Jesse Halldc225072016-05-30 22:40:14 -07001148 "swapchain presentMode=%u not supported",
Jesse Hall0ae0dce2016-02-09 22:13:34 -08001149 create_info->presentMode);
Jesse Halld7b994a2015-09-07 14:17:37 -07001150
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001151 Surface& surface = *SurfaceFromHandle(create_info->surface);
1152
Jesse Halldc225072016-05-30 22:40:14 -07001153 if (surface.swapchain_handle != create_info->oldSwapchain) {
Jesse Hall42a9eec2016-06-03 12:39:49 -07001154 ALOGV("Can't create a swapchain for VkSurfaceKHR 0x%" PRIx64
Jesse Halldc225072016-05-30 22:40:14 -07001155 " because it already has active swapchain 0x%" PRIx64
1156 " but VkSwapchainCreateInfo::oldSwapchain=0x%" PRIx64,
1157 reinterpret_cast<uint64_t>(create_info->surface),
1158 reinterpret_cast<uint64_t>(surface.swapchain_handle),
1159 reinterpret_cast<uint64_t>(create_info->oldSwapchain));
1160 return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR;
1161 }
1162 if (create_info->oldSwapchain != VK_NULL_HANDLE)
1163 OrphanSwapchain(device, SwapchainFromHandle(create_info->oldSwapchain));
1164
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001165 // -- Reset the native window --
1166 // The native window might have been used previously, and had its properties
1167 // changed from defaults. That will affect the answer we get for queries
1168 // like MIN_UNDEQUED_BUFFERS. Reset to a known/default state before we
1169 // attempt such queries.
1170
Jesse Halldc225072016-05-30 22:40:14 -07001171 // The native window only allows dequeueing all buffers before any have
1172 // been queued, since after that point at least one is assumed to be in
1173 // non-FREE state at any given time. Disconnecting and re-connecting
1174 // orphans the previous buffers, getting us back to the state where we can
1175 // dequeue all buffers.
Yiwei Zhang70a21962019-05-31 17:26:52 -07001176 //
1177 // TODO(http://b/134186185) recycle swapchain images more efficiently
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001178 ANativeWindow* window = surface.window.get();
1179 err = native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
1180 ALOGW_IF(err != android::OK, "native_window_api_disconnect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001181 strerror(-err), err);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001182 err = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
1183 ALOGW_IF(err != android::OK, "native_window_api_connect failed: %s (%d)",
Jesse Halldc225072016-05-30 22:40:14 -07001184 strerror(-err), err);
1185
Nicolas Capens147b7da2021-04-09 14:53:06 -04001186 err =
1187 window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT, nsecs_t{-1});
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001188 if (err != android::OK) {
1189 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1190 strerror(-err), err);
1191 return VK_ERROR_SURFACE_LOST_KHR;
1192 }
1193
Hrishikesh Manohar9b7e4532017-01-10 17:52:11 +05301194 int swap_interval =
1195 create_info->presentMode == VK_PRESENT_MODE_MAILBOX_KHR ? 0 : 1;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001196 err = window->setSwapInterval(window, swap_interval);
1197 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001198 ALOGE("native_window->setSwapInterval(1) failed: %s (%d)",
1199 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001200 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001201 }
1202
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001203 err = native_window_set_shared_buffer_mode(window, false);
1204 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001205 ALOGE("native_window_set_shared_buffer_mode(false) failed: %s (%d)",
1206 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001207 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001208 }
1209
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001210 err = native_window_set_auto_refresh(window, false);
1211 if (err != android::OK) {
Chris Forbesb8042d22017-01-18 18:07:05 +13001212 ALOGE("native_window_set_auto_refresh(false) failed: %s (%d)",
1213 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001214 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbesb8042d22017-01-18 18:07:05 +13001215 }
1216
Jesse Halld7b994a2015-09-07 14:17:37 -07001217 // -- Configure the native window --
Jesse Halld7b994a2015-09-07 14:17:37 -07001218
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001219 const auto& dispatch = GetData(device).driver;
Jesse Hall70f93352015-11-04 09:41:31 -08001220
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001221 err = native_window_set_buffers_format(window, native_pixel_format);
1222 if (err != android::OK) {
Leon Scroggins IIIcb45fe72021-11-30 16:17:15 -05001223 ALOGE("native_window_set_buffers_format(%s) failed: %s (%d)",
1224 decodePixelFormat(native_pixel_format).c_str(), strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001225 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001226 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001227 err = native_window_set_buffers_data_space(window, native_dataspace);
1228 if (err != android::OK) {
Jesse Hall517274a2016-02-10 00:07:18 -08001229 ALOGE("native_window_set_buffers_data_space(%d) failed: %s (%d)",
Courtney Goeltzenleuchter7d4a64a2017-02-17 12:59:11 -07001230 native_dataspace, strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001231 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall517274a2016-02-10 00:07:18 -08001232 }
1233
Jesse Hall3dd678a2016-01-08 21:52:01 -08001234 err = native_window_set_buffers_dimensions(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001235 window, static_cast<int>(create_info->imageExtent.width),
Jesse Hall3dd678a2016-01-08 21:52:01 -08001236 static_cast<int>(create_info->imageExtent.height));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001237 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001238 ALOGE("native_window_set_buffers_dimensions(%d,%d) failed: %s (%d)",
1239 create_info->imageExtent.width, create_info->imageExtent.height,
1240 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001241 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001242 }
1243
Jesse Hall178b6962016-02-24 15:39:50 -08001244 // VkSwapchainCreateInfo::preTransform indicates the transformation the app
1245 // applied during rendering. native_window_set_transform() expects the
1246 // inverse: the transform the app is requesting that the compositor perform
1247 // during composition. With native windows, pre-transform works by rendering
1248 // with the same transform the compositor is applying (as in Vulkan), but
1249 // then requesting the inverse transform, so that when the compositor does
1250 // it's job the two transforms cancel each other out and the compositor ends
1251 // up applying an identity transform to the app's buffer.
1252 err = native_window_set_buffers_transform(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001253 window, InvertTransformToNative(create_info->preTransform));
1254 if (err != android::OK) {
Jesse Hall178b6962016-02-24 15:39:50 -08001255 ALOGE("native_window_set_buffers_transform(%d) failed: %s (%d)",
1256 InvertTransformToNative(create_info->preTransform),
1257 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001258 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall178b6962016-02-24 15:39:50 -08001259 }
1260
Jesse Hallf64ca122015-11-03 16:11:10 -08001261 err = native_window_set_scaling_mode(
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001262 window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1263 if (err != android::OK) {
Jesse Hallf64ca122015-11-03 16:11:10 -08001264 ALOGE("native_window_set_scaling_mode(SCALE_TO_WINDOW) failed: %s (%d)",
1265 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001266 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hallf64ca122015-11-03 16:11:10 -08001267 }
1268
Chris Forbes97ef4612017-03-30 19:37:50 +13001269 VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
1270 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
1271 create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
1272 swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001273 err = native_window_set_shared_buffer_mode(window, true);
1274 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001275 ALOGE("native_window_set_shared_buffer_mode failed: %s (%d)", strerror(-err), err);
1276 return VK_ERROR_SURFACE_LOST_KHR;
1277 }
1278 }
1279
1280 if (create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001281 err = native_window_set_auto_refresh(window, true);
1282 if (err != android::OK) {
Chris Forbes97ef4612017-03-30 19:37:50 +13001283 ALOGE("native_window_set_auto_refresh failed: %s (%d)", strerror(-err), err);
1284 return VK_ERROR_SURFACE_LOST_KHR;
1285 }
1286 }
1287
Ian Elliott16c443c2021-11-30 17:10:32 -07001288 int query_value;
1289 err = window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
1290 &query_value);
1291 if (err != android::OK || query_value < 0) {
1292 ALOGE("window->query failed: %s (%d) value=%d", strerror(-err), err,
1293 query_value);
Mike Stroyan762c8132017-02-22 11:43:09 -07001294 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001295 }
Ian Elliott16c443c2021-11-30 17:10:32 -07001296 uint32_t min_undequeued_buffers = static_cast<uint32_t>(query_value);
1297 const auto mailbox_num_images = std::max(3u, create_info->minImageCount);
1298 const auto requested_images =
1299 swap_interval ? create_info->minImageCount : mailbox_num_images;
1300 uint32_t num_images = requested_images - 1 + min_undequeued_buffers;
Chris Forbes2c8fc752017-03-17 11:28:32 +13001301
Ian Elliott5396b702021-12-13 19:32:34 -07001302 // Lower layer insists that we have at least min_undequeued_buffers + 1
1303 // buffers. This is wasteful and we'd like to relax it in the shared case,
1304 // but not all the pieces are in place for that to work yet. Note we only
1305 // lie to the lower layer--we don't want to give the app back a swapchain
1306 // with extra images (which they can't actually use!).
1307 uint32_t min_buffer_count = min_undequeued_buffers + 1;
1308 err = native_window_set_buffer_count(
1309 window, std::max(min_buffer_count, num_images));
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001310 if (err != android::OK) {
Jesse Hall3d1c82a2016-04-22 15:28:29 -07001311 ALOGE("native_window_set_buffer_count(%d) failed: %s (%d)", num_images,
1312 strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001313 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001314 }
1315
Ian Elliott12b7e2f2021-12-21 23:24:20 -07001316 // In shared mode the num_images must be one regardless of how many
1317 // buffers were allocated for the buffer queue.
1318 if (swapchain_image_usage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID) {
1319 num_images = 1;
1320 }
1321
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001322 int32_t legacy_usage = 0;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001323 if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
Jesse Halld1abd742017-02-09 21:45:51 -08001324 uint64_t consumer_usage, producer_usage;
Yiwei Zhang533cea92019-06-03 18:43:24 -07001325 ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
Courtney Goeltzenleuchter894780b2017-04-03 16:11:30 -06001326 result = dispatch.GetSwapchainGrallocUsage2ANDROID(
1327 device, create_info->imageFormat, create_info->imageUsage,
1328 swapchain_image_usage, &consumer_usage, &producer_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001329 ATRACE_END();
Chris Forbes8c47dc92017-01-12 11:13:58 +13001330 if (result != VK_SUCCESS) {
1331 ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001332 return VK_ERROR_SURFACE_LOST_KHR;
Chris Forbes8c47dc92017-01-12 11:13:58 +13001333 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001334 legacy_usage =
Jesse Hall79927812017-03-23 11:03:23 -07001335 android_convertGralloc1To0Usage(producer_usage, consumer_usage);
Chris Forbes8c47dc92017-01-12 11:13:58 +13001336 } else if (dispatch.GetSwapchainGrallocUsageANDROID) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001337 ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
Jesse Hall1f91d392015-12-11 16:28:44 -08001338 result = dispatch.GetSwapchainGrallocUsageANDROID(
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001339 device, create_info->imageFormat, create_info->imageUsage,
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001340 &legacy_usage);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001341 ATRACE_END();
Jesse Hall70f93352015-11-04 09:41:31 -08001342 if (result != VK_SUCCESS) {
1343 ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
Mike Stroyan762c8132017-02-22 11:43:09 -07001344 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001345 }
Jesse Hall70f93352015-11-04 09:41:31 -08001346 }
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001347 uint64_t native_usage = static_cast<uint64_t>(legacy_usage);
1348
1349 bool createProtectedSwapchain = false;
1350 if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {
1351 createProtectedSwapchain = true;
1352 native_usage |= BufferUsage::PROTECTED;
1353 }
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001354 err = native_window_set_usage(window, native_usage);
1355 if (err != android::OK) {
Jesse Hall70f93352015-11-04 09:41:31 -08001356 ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001357 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Hall70f93352015-11-04 09:41:31 -08001358 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001359
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001360 int transform_hint;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001361 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT, &transform_hint);
1362 if (err != android::OK) {
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001363 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1364 strerror(-err), err);
1365 return VK_ERROR_SURFACE_LOST_KHR;
1366 }
1367
Jesse Halld7b994a2015-09-07 14:17:37 -07001368 // -- Allocate our Swapchain object --
1369 // After this point, we must deallocate the swapchain on error.
1370
Jesse Hall1f91d392015-12-11 16:28:44 -08001371 void* mem = allocator->pfnAllocation(allocator->pUserData,
1372 sizeof(Swapchain), alignof(Swapchain),
1373 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001374 if (!mem)
Jesse Halld7b994a2015-09-07 14:17:37 -07001375 return VK_ERROR_OUT_OF_HOST_MEMORY;
silence_dogood73597592019-05-23 16:57:37 -07001376 Swapchain* swapchain = new (mem)
1377 Swapchain(surface, num_images, create_info->presentMode,
1378 TranslateVulkanToNativeTransform(create_info->preTransform));
Jesse Halld7b994a2015-09-07 14:17:37 -07001379 // -- Dequeue all buffers and create a VkImage for each --
1380 // Any failures during or after this must cancel the dequeued buffers.
1381
Chris Forbesb56287a2017-01-12 14:28:58 +13001382 VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
1383#pragma clang diagnostic push
1384#pragma clang diagnostic ignored "-Wold-style-cast"
1385 .sType = VK_STRUCTURE_TYPE_SWAPCHAIN_IMAGE_CREATE_INFO_ANDROID,
1386#pragma clang diagnostic pop
1387 .pNext = nullptr,
1388 .usage = swapchain_image_usage,
1389 };
Jesse Halld7b994a2015-09-07 14:17:37 -07001390 VkNativeBufferANDROID image_native_buffer = {
Jesse Halld7b994a2015-09-07 14:17:37 -07001391#pragma clang diagnostic push
1392#pragma clang diagnostic ignored "-Wold-style-cast"
1393 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
1394#pragma clang diagnostic pop
Chris Forbesb56287a2017-01-12 14:28:58 +13001395 .pNext = &swapchain_image_create,
Jesse Halld7b994a2015-09-07 14:17:37 -07001396 };
1397 VkImageCreateInfo image_create = {
1398 .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
1399 .pNext = &image_native_buffer,
Nick Desaulnierse745a3e2019-10-18 10:38:45 -07001400 .flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
Jesse Halld7b994a2015-09-07 14:17:37 -07001401 .imageType = VK_IMAGE_TYPE_2D,
Jesse Hall517274a2016-02-10 00:07:18 -08001402 .format = create_info->imageFormat,
Jesse Halld7b994a2015-09-07 14:17:37 -07001403 .extent = {0, 0, 1},
1404 .mipLevels = 1,
Jesse Halla15a4bf2015-11-19 22:48:02 -08001405 .arrayLayers = 1,
Jesse Hall091ed9e2015-11-30 00:55:29 -08001406 .samples = VK_SAMPLE_COUNT_1_BIT,
Jesse Halld7b994a2015-09-07 14:17:37 -07001407 .tiling = VK_IMAGE_TILING_OPTIMAL,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001408 .usage = create_info->imageUsage,
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001409 .sharingMode = create_info->imageSharingMode,
Jesse Hall03b6fe12015-11-24 12:44:21 -08001410 .queueFamilyIndexCount = create_info->queueFamilyIndexCount,
Jesse Halld7b994a2015-09-07 14:17:37 -07001411 .pQueueFamilyIndices = create_info->pQueueFamilyIndices,
1412 };
1413
Jesse Halld7b994a2015-09-07 14:17:37 -07001414 for (uint32_t i = 0; i < num_images; i++) {
1415 Swapchain::Image& img = swapchain->images[i];
1416
1417 ANativeWindowBuffer* buffer;
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001418 err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
1419 if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001420 ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
Yiwei Zhang702beb42019-11-29 17:59:55 -08001421 switch (-err) {
1422 case ENOMEM:
1423 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
1424 break;
1425 default:
1426 result = VK_ERROR_SURFACE_LOST_KHR;
1427 break;
1428 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001429 break;
1430 }
Chia-I Wue8e689f2016-04-18 08:21:31 +08001431 img.buffer = buffer;
Jesse Halld7b994a2015-09-07 14:17:37 -07001432 img.dequeued = true;
1433
1434 image_create.extent =
Jesse Hall3dd678a2016-01-08 21:52:01 -08001435 VkExtent3D{static_cast<uint32_t>(img.buffer->width),
1436 static_cast<uint32_t>(img.buffer->height),
1437 1};
Jesse Halld7b994a2015-09-07 14:17:37 -07001438 image_native_buffer.handle = img.buffer->handle;
1439 image_native_buffer.stride = img.buffer->stride;
1440 image_native_buffer.format = img.buffer->format;
Mathias Agopiancb496ac2017-05-22 14:21:00 -07001441 image_native_buffer.usage = int(img.buffer->usage);
Chris Forbes8e0c3f52017-05-19 14:47:29 -07001442 android_convertGralloc0To1Usage(int(img.buffer->usage),
1443 &image_native_buffer.usage2.producer,
1444 &image_native_buffer.usage2.consumer);
Jesse Halld7b994a2015-09-07 14:17:37 -07001445
Yiwei Zhang533cea92019-06-03 18:43:24 -07001446 ATRACE_BEGIN("CreateImage");
Jesse Hall03b6fe12015-11-24 12:44:21 -08001447 result =
Jesse Hall1f91d392015-12-11 16:28:44 -08001448 dispatch.CreateImage(device, &image_create, nullptr, &img.image);
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001449 ATRACE_END();
Jesse Halld7b994a2015-09-07 14:17:37 -07001450 if (result != VK_SUCCESS) {
1451 ALOGD("vkCreateImage w/ native buffer failed: %u", result);
1452 break;
1453 }
1454 }
1455
1456 // -- Cancel all buffers, returning them to the queue --
1457 // If an error occurred before, also destroy the VkImage and release the
1458 // buffer reference. Otherwise, we retain a strong reference to the buffer.
Chris Forbes31b85c22018-05-29 15:03:28 -07001459 for (uint32_t i = 0; i < num_images; i++) {
1460 Swapchain::Image& img = swapchain->images[i];
1461 if (img.dequeued) {
1462 if (!swapchain->shared) {
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001463 window->cancelBuffer(window, img.buffer.get(),
1464 img.dequeue_fence);
Chris Forbese0ced032017-03-30 19:44:15 +13001465 img.dequeue_fence = -1;
1466 img.dequeued = false;
1467 }
Chris Forbes31b85c22018-05-29 15:03:28 -07001468 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001469 }
1470
1471 if (result != VK_SUCCESS) {
Yiwei Zhang533cea92019-06-03 18:43:24 -07001472 DestroySwapchainInternal(device, HandleFromSwapchain(swapchain),
1473 allocator);
Jesse Halld7b994a2015-09-07 14:17:37 -07001474 return result;
1475 }
1476
Yiwei Zhang69395cd2019-07-03 16:55:39 -07001477 if (transform_hint != swapchain->pre_transform) {
1478 // Log that the app is not doing pre-rotation.
1479 android::GraphicsEnv::getInstance().setTargetStats(
1480 android::GpuStatsInfo::Stats::FALSE_PREROTATION);
1481 }
1482
Jesse Halldc225072016-05-30 22:40:14 -07001483 surface.swapchain_handle = HandleFromSwapchain(swapchain);
1484 *swapchain_handle = surface.swapchain_handle;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001485 return VK_SUCCESS;
1486}
1487
Jesse Halle1b12782015-11-30 11:27:32 -08001488VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001489void DestroySwapchainKHR(VkDevice device,
1490 VkSwapchainKHR swapchain_handle,
1491 const VkAllocationCallbacks* allocator) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001492 ATRACE_CALL();
1493
Yiwei Zhang533cea92019-06-03 18:43:24 -07001494 DestroySwapchainInternal(device, swapchain_handle, allocator);
Jesse Hallb1352bc2015-09-04 16:12:33 -07001495}
1496
Jesse Halle1b12782015-11-30 11:27:32 -08001497VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001498VkResult GetSwapchainImagesKHR(VkDevice,
1499 VkSwapchainKHR swapchain_handle,
1500 uint32_t* count,
1501 VkImage* images) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001502 ATRACE_CALL();
1503
Jesse Halld7b994a2015-09-07 14:17:37 -07001504 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Halldc225072016-05-30 22:40:14 -07001505 ALOGW_IF(swapchain.surface.swapchain_handle != swapchain_handle,
1506 "getting images for non-active swapchain 0x%" PRIx64
1507 "; only dequeued image handles are valid",
1508 reinterpret_cast<uint64_t>(swapchain_handle));
Jesse Halld7b994a2015-09-07 14:17:37 -07001509 VkResult result = VK_SUCCESS;
1510 if (images) {
1511 uint32_t n = swapchain.num_images;
1512 if (*count < swapchain.num_images) {
1513 n = *count;
1514 result = VK_INCOMPLETE;
1515 }
1516 for (uint32_t i = 0; i < n; i++)
1517 images[i] = swapchain.images[i].image;
Jesse Hall7331e222016-09-15 21:26:01 -07001518 *count = n;
1519 } else {
1520 *count = swapchain.num_images;
Jesse Halld7b994a2015-09-07 14:17:37 -07001521 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001522 return result;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001523}
1524
Jesse Halle1b12782015-11-30 11:27:32 -08001525VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001526VkResult AcquireNextImageKHR(VkDevice device,
1527 VkSwapchainKHR swapchain_handle,
1528 uint64_t timeout,
1529 VkSemaphore semaphore,
1530 VkFence vk_fence,
1531 uint32_t* image_index) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001532 ATRACE_CALL();
1533
Jesse Halld7b994a2015-09-07 14:17:37 -07001534 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Jesse Hall1356b0d2015-11-23 17:24:58 -08001535 ANativeWindow* window = swapchain.surface.window.get();
Jesse Halld7b994a2015-09-07 14:17:37 -07001536 VkResult result;
1537 int err;
1538
Jesse Halldc225072016-05-30 22:40:14 -07001539 if (swapchain.surface.swapchain_handle != swapchain_handle)
1540 return VK_ERROR_OUT_OF_DATE_KHR;
1541
Chris Forbesc88409c2017-03-30 19:47:37 +13001542 if (swapchain.shared) {
1543 // In shared mode, we keep the buffer dequeued all the time, so we don't
1544 // want to dequeue a buffer here. Instead, just ask the driver to ensure
1545 // the semaphore and fence passed to us will be signalled.
1546 *image_index = 0;
1547 result = GetData(device).driver.AcquireImageANDROID(
1548 device, swapchain.images[*image_index].image, -1, semaphore, vk_fence);
1549 return result;
1550 }
1551
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001552 const nsecs_t acquire_next_image_timeout =
1553 timeout > (uint64_t)std::numeric_limits<nsecs_t>::max() ? -1 : timeout;
1554 if (acquire_next_image_timeout != swapchain.acquire_next_image_timeout) {
1555 // Cache the timeout to avoid the duplicate binder cost.
1556 err = window->perform(window, NATIVE_WINDOW_SET_DEQUEUE_TIMEOUT,
1557 acquire_next_image_timeout);
1558 if (err != android::OK) {
1559 ALOGE("window->perform(SET_DEQUEUE_TIMEOUT) failed: %s (%d)",
1560 strerror(-err), err);
1561 return VK_ERROR_SURFACE_LOST_KHR;
1562 }
1563 swapchain.acquire_next_image_timeout = acquire_next_image_timeout;
1564 }
1565
Jesse Halld7b994a2015-09-07 14:17:37 -07001566 ANativeWindowBuffer* buffer;
Jesse Hall06193802015-12-03 16:12:51 -08001567 int fence_fd;
1568 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangc0f8a2c2020-04-30 20:23:13 -07001569 if (err == android::TIMED_OUT || err == android::INVALID_OPERATION) {
Yiwei Zhang705c2e62019-12-18 23:12:43 -08001570 ALOGW("dequeueBuffer timed out: %s (%d)", strerror(-err), err);
1571 return timeout ? VK_TIMEOUT : VK_NOT_READY;
1572 } else if (err != android::OK) {
Jesse Halld7b994a2015-09-07 14:17:37 -07001573 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
Mike Stroyan762c8132017-02-22 11:43:09 -07001574 return VK_ERROR_SURFACE_LOST_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001575 }
1576
1577 uint32_t idx;
1578 for (idx = 0; idx < swapchain.num_images; idx++) {
1579 if (swapchain.images[idx].buffer.get() == buffer) {
1580 swapchain.images[idx].dequeued = true;
Jesse Hall06193802015-12-03 16:12:51 -08001581 swapchain.images[idx].dequeue_fence = fence_fd;
Jesse Halld7b994a2015-09-07 14:17:37 -07001582 break;
1583 }
1584 }
1585 if (idx == swapchain.num_images) {
1586 ALOGE("dequeueBuffer returned unrecognized buffer");
Jesse Hall06193802015-12-03 16:12:51 -08001587 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001588 return VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001589 }
1590
1591 int fence_clone = -1;
Jesse Hall06193802015-12-03 16:12:51 -08001592 if (fence_fd != -1) {
1593 fence_clone = dup(fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001594 if (fence_clone == -1) {
1595 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)",
1596 strerror(errno), errno);
Jesse Hall06193802015-12-03 16:12:51 -08001597 sync_wait(fence_fd, -1 /* forever */);
Jesse Halld7b994a2015-09-07 14:17:37 -07001598 }
1599 }
1600
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001601 result = GetData(device).driver.AcquireImageANDROID(
Jesse Hall1f91d392015-12-11 16:28:44 -08001602 device, swapchain.images[idx].image, fence_clone, semaphore, vk_fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001603 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001604 // NOTE: we're relying on AcquireImageANDROID to close fence_clone,
1605 // even if the call fails. We could close it ourselves on failure, but
1606 // that would create a race condition if the driver closes it on a
1607 // failure path: some other thread might create an fd with the same
1608 // number between the time the driver closes it and the time we close
1609 // it. We must assume one of: the driver *always* closes it even on
1610 // failure, or *never* closes it on failure.
Jesse Hall06193802015-12-03 16:12:51 -08001611 window->cancelBuffer(window, buffer, fence_fd);
Jesse Halld7b994a2015-09-07 14:17:37 -07001612 swapchain.images[idx].dequeued = false;
1613 swapchain.images[idx].dequeue_fence = -1;
1614 return result;
1615 }
1616
1617 *image_index = idx;
Jesse Hallb1352bc2015-09-04 16:12:33 -07001618 return VK_SUCCESS;
1619}
1620
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001621VKAPI_ATTR
1622VkResult AcquireNextImage2KHR(VkDevice device,
1623 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1624 uint32_t* pImageIndex) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001625 ATRACE_CALL();
1626
Daniel Kochf25f5bb2017-10-05 00:26:58 -04001627 return AcquireNextImageKHR(device, pAcquireInfo->swapchain,
1628 pAcquireInfo->timeout, pAcquireInfo->semaphore,
1629 pAcquireInfo->fence, pImageIndex);
1630}
1631
Jesse Halldc225072016-05-30 22:40:14 -07001632static VkResult WorstPresentResult(VkResult a, VkResult b) {
1633 // See the error ranking for vkQueuePresentKHR at the end of section 29.6
1634 // (in spec version 1.0.14).
1635 static const VkResult kWorstToBest[] = {
1636 VK_ERROR_DEVICE_LOST,
1637 VK_ERROR_SURFACE_LOST_KHR,
1638 VK_ERROR_OUT_OF_DATE_KHR,
1639 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1640 VK_ERROR_OUT_OF_HOST_MEMORY,
1641 VK_SUBOPTIMAL_KHR,
1642 };
1643 for (auto result : kWorstToBest) {
1644 if (a == result || b == result)
1645 return result;
1646 }
1647 ALOG_ASSERT(a == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", a);
1648 ALOG_ASSERT(b == VK_SUCCESS, "invalid vkQueuePresentKHR result %d", b);
1649 return a != VK_SUCCESS ? a : b;
1650}
1651
Jesse Halle1b12782015-11-30 11:27:32 -08001652VKAPI_ATTR
Chia-I Wu62262232016-03-26 07:06:44 +08001653VkResult QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001654 ATRACE_CALL();
1655
Jesse Halld7b994a2015-09-07 14:17:37 -07001656 ALOGV_IF(present_info->sType != VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
1657 "vkQueuePresentKHR: invalid VkPresentInfoKHR structure type %d",
1658 present_info->sType);
Jesse Halld7b994a2015-09-07 14:17:37 -07001659
Jesse Halldc225072016-05-30 22:40:14 -07001660 VkDevice device = GetData(queue).driver_device;
Chia-I Wu4a6a9162016-03-26 07:17:34 +08001661 const auto& dispatch = GetData(queue).driver;
Jesse Halld7b994a2015-09-07 14:17:37 -07001662 VkResult final_result = VK_SUCCESS;
Jesse Halldc225072016-05-30 22:40:14 -07001663
Ian Elliottcb351132016-12-13 10:30:40 -07001664 // Look at the pNext chain for supported extension structs:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001665 const VkPresentRegionsKHR* present_regions = nullptr;
1666 const VkPresentTimesInfoGOOGLE* present_times = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001667 const VkPresentRegionsKHR* next =
1668 reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
1669 while (next) {
1670 switch (next->sType) {
1671 case VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR:
1672 present_regions = next;
1673 break;
Ian Elliott14866bb2017-01-20 09:15:48 -07001674 case VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE:
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001675 present_times =
1676 reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
1677 break;
Ian Elliottcb351132016-12-13 10:30:40 -07001678 default:
1679 ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
1680 next->sType);
1681 break;
1682 }
1683 next = reinterpret_cast<const VkPresentRegionsKHR*>(next->pNext);
1684 }
1685 ALOGV_IF(
1686 present_regions &&
1687 present_regions->swapchainCount != present_info->swapchainCount,
1688 "VkPresentRegions::swapchainCount != VkPresentInfo::swapchainCount");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001689 ALOGV_IF(present_times &&
1690 present_times->swapchainCount != present_info->swapchainCount,
1691 "VkPresentTimesInfoGOOGLE::swapchainCount != "
1692 "VkPresentInfo::swapchainCount");
Ian Elliottcb351132016-12-13 10:30:40 -07001693 const VkPresentRegionKHR* regions =
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001694 (present_regions) ? present_regions->pRegions : nullptr;
1695 const VkPresentTimeGOOGLE* times =
1696 (present_times) ? present_times->pTimes : nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001697 const VkAllocationCallbacks* allocator = &GetData(device).allocator;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001698 android_native_rect_t* rects = nullptr;
Ian Elliottcb351132016-12-13 10:30:40 -07001699 uint32_t nrects = 0;
1700
Jesse Halld7b994a2015-09-07 14:17:37 -07001701 for (uint32_t sc = 0; sc < present_info->swapchainCount; sc++) {
1702 Swapchain& swapchain =
Jesse Hall03b6fe12015-11-24 12:44:21 -08001703 *SwapchainFromHandle(present_info->pSwapchains[sc]);
Jesse Hallf4ab2b12015-11-30 16:04:55 -08001704 uint32_t image_idx = present_info->pImageIndices[sc];
Jesse Hall5ae3abb2015-10-08 14:00:22 -07001705 Swapchain::Image& img = swapchain.images[image_idx];
Ian Elliottffedb652017-02-14 10:58:30 -07001706 const VkPresentRegionKHR* region =
1707 (regions && !swapchain.mailbox_mode) ? &regions[sc] : nullptr;
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001708 const VkPresentTimeGOOGLE* time = (times) ? &times[sc] : nullptr;
Jesse Halldc225072016-05-30 22:40:14 -07001709 VkResult swapchain_result = VK_SUCCESS;
Jesse Halld7b994a2015-09-07 14:17:37 -07001710 VkResult result;
1711 int err;
1712
Jesse Halld7b994a2015-09-07 14:17:37 -07001713 int fence = -1;
Jesse Hall275d76c2016-01-08 22:39:16 -08001714 result = dispatch.QueueSignalReleaseImageANDROID(
1715 queue, present_info->waitSemaphoreCount,
1716 present_info->pWaitSemaphores, img.image, &fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001717 if (result != VK_SUCCESS) {
Jesse Hallab9aeef2015-11-04 10:56:20 -08001718 ALOGE("QueueSignalReleaseImageANDROID failed: %d", result);
Jesse Halldc225072016-05-30 22:40:14 -07001719 swapchain_result = result;
Jesse Halld7b994a2015-09-07 14:17:37 -07001720 }
Yiwei Zhang9df5bff2020-09-22 10:08:03 -07001721 if (img.release_fence >= 0)
1722 close(img.release_fence);
1723 img.release_fence = fence < 0 ? -1 : dup(fence);
Jesse Halld7b994a2015-09-07 14:17:37 -07001724
Jesse Halldc225072016-05-30 22:40:14 -07001725 if (swapchain.surface.swapchain_handle ==
1726 present_info->pSwapchains[sc]) {
1727 ANativeWindow* window = swapchain.surface.window.get();
1728 if (swapchain_result == VK_SUCCESS) {
Ian Elliottcb351132016-12-13 10:30:40 -07001729 if (region) {
1730 // Process the incremental-present hint for this swapchain:
1731 uint32_t rcount = region->rectangleCount;
1732 if (rcount > nrects) {
1733 android_native_rect_t* new_rects =
1734 static_cast<android_native_rect_t*>(
1735 allocator->pfnReallocation(
1736 allocator->pUserData, rects,
1737 sizeof(android_native_rect_t) * rcount,
1738 alignof(android_native_rect_t),
1739 VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1740 if (new_rects) {
1741 rects = new_rects;
1742 nrects = rcount;
1743 } else {
1744 rcount = 0; // Ignore the hint for this swapchain
1745 }
1746 }
1747 for (uint32_t r = 0; r < rcount; ++r) {
1748 if (region->pRectangles[r].layer > 0) {
1749 ALOGV(
1750 "vkQueuePresentKHR ignoring invalid layer "
1751 "(%u); using layer 0 instead",
1752 region->pRectangles[r].layer);
1753 }
1754 int x = region->pRectangles[r].offset.x;
1755 int y = region->pRectangles[r].offset.y;
1756 int width = static_cast<int>(
1757 region->pRectangles[r].extent.width);
1758 int height = static_cast<int>(
1759 region->pRectangles[r].extent.height);
1760 android_native_rect_t* cur_rect = &rects[r];
1761 cur_rect->left = x;
1762 cur_rect->top = y + height;
1763 cur_rect->right = x + width;
1764 cur_rect->bottom = y;
1765 }
1766 native_window_set_surface_damage(window, rects, rcount);
1767 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001768 if (time) {
1769 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001770 ALOGV(
1771 "Calling "
1772 "native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001773 native_window_enable_frame_timestamps(window, true);
1774 swapchain.frame_timestamps_enabled = true;
1775 }
Brian Anderson1049d1d2016-12-16 17:25:57 -08001776
1777 // Record the nativeFrameId so it can be later correlated to
1778 // this present.
1779 uint64_t nativeFrameId = 0;
1780 err = native_window_get_next_frame_id(
1781 window, &nativeFrameId);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001782 if (err != android::OK) {
Brian Anderson1049d1d2016-12-16 17:25:57 -08001783 ALOGE("Failed to get next native frame ID.");
1784 }
1785
1786 // Add a new timing record with the user's presentID and
1787 // the nativeFrameId.
Yiwei Zhang5e862202019-06-21 14:59:16 -07001788 swapchain.timing.emplace_back(time, nativeFrameId);
Brian Anderson1049d1d2016-12-16 17:25:57 -08001789 while (swapchain.timing.size() > MAX_TIMING_INFOS) {
Yiwei Zhang5e862202019-06-21 14:59:16 -07001790 swapchain.timing.erase(swapchain.timing.begin());
Ian Elliott8a977262017-01-19 09:05:58 -07001791 }
1792 if (time->desiredPresentTime) {
1793 // Set the desiredPresentTime:
1794 ALOGV(
1795 "Calling "
1796 "native_window_set_buffers_timestamp(%" PRId64 ")",
1797 time->desiredPresentTime);
1798 native_window_set_buffers_timestamp(
1799 window,
1800 static_cast<int64_t>(time->desiredPresentTime));
1801 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001802 }
Chris Forbesfca0f292017-03-30 19:48:39 +13001803
Jesse Halldc225072016-05-30 22:40:14 -07001804 err = window->queueBuffer(window, img.buffer.get(), fence);
1805 // queueBuffer always closes fence, even on error
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001806 if (err != android::OK) {
Jesse Halldc225072016-05-30 22:40:14 -07001807 ALOGE("queueBuffer failed: %s (%d)", strerror(-err), err);
1808 swapchain_result = WorstPresentResult(
Yiwei Zhang492dd5f2021-03-09 22:54:38 +00001809 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
Yiwei Zhang0b468472019-06-03 18:57:19 -07001810 } else {
1811 if (img.dequeue_fence >= 0) {
1812 close(img.dequeue_fence);
1813 img.dequeue_fence = -1;
1814 }
1815 img.dequeued = false;
Jesse Halldc225072016-05-30 22:40:14 -07001816 }
Chris Forbesfca0f292017-03-30 19:48:39 +13001817
1818 // If the swapchain is in shared mode, immediately dequeue the
1819 // buffer so it can be presented again without an intervening
1820 // call to AcquireNextImageKHR. We expect to get the same buffer
1821 // back from every call to dequeueBuffer in this mode.
1822 if (swapchain.shared && swapchain_result == VK_SUCCESS) {
1823 ANativeWindowBuffer* buffer;
1824 int fence_fd;
1825 err = window->dequeueBuffer(window, &buffer, &fence_fd);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001826 if (err != android::OK) {
Chris Forbesfca0f292017-03-30 19:48:39 +13001827 ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), err);
1828 swapchain_result = WorstPresentResult(swapchain_result,
1829 VK_ERROR_SURFACE_LOST_KHR);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001830 } else if (img.buffer != buffer) {
Chris Forbesfca0f292017-03-30 19:48:39 +13001831 ALOGE("got wrong image back for shared swapchain");
1832 swapchain_result = WorstPresentResult(swapchain_result,
1833 VK_ERROR_SURFACE_LOST_KHR);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001834 } else {
Chris Forbesfca0f292017-03-30 19:48:39 +13001835 img.dequeue_fence = fence_fd;
1836 img.dequeued = true;
1837 }
1838 }
Jesse Halldc225072016-05-30 22:40:14 -07001839 }
1840 if (swapchain_result != VK_SUCCESS) {
Jesse Halldc225072016-05-30 22:40:14 -07001841 OrphanSwapchain(device, &swapchain);
1842 }
silence_dogood73597592019-05-23 16:57:37 -07001843 int window_transform_hint;
1844 err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
1845 &window_transform_hint);
Yiwei Zhangf5030b42019-12-19 00:10:04 -08001846 if (err != android::OK) {
silence_dogood73597592019-05-23 16:57:37 -07001847 ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
1848 strerror(-err), err);
1849 swapchain_result = WorstPresentResult(
1850 swapchain_result, VK_ERROR_SURFACE_LOST_KHR);
1851 }
1852 if (swapchain.pre_transform != window_transform_hint) {
1853 swapchain_result =
1854 WorstPresentResult(swapchain_result, VK_SUBOPTIMAL_KHR);
1855 }
Jesse Halldc225072016-05-30 22:40:14 -07001856 } else {
Yiwei Zhang9df5bff2020-09-22 10:08:03 -07001857 ReleaseSwapchainImage(device, nullptr, fence, img, true);
Jesse Halldc225072016-05-30 22:40:14 -07001858 swapchain_result = VK_ERROR_OUT_OF_DATE_KHR;
Jesse Halld7b994a2015-09-07 14:17:37 -07001859 }
1860
Jesse Halla9e57032015-11-30 01:03:10 -08001861 if (present_info->pResults)
Jesse Halldc225072016-05-30 22:40:14 -07001862 present_info->pResults[sc] = swapchain_result;
1863
1864 if (swapchain_result != final_result)
1865 final_result = WorstPresentResult(final_result, swapchain_result);
Jesse Halld7b994a2015-09-07 14:17:37 -07001866 }
Ian Elliottcb351132016-12-13 10:30:40 -07001867 if (rects) {
1868 allocator->pfnFree(allocator->pUserData, rects);
1869 }
Jesse Halld7b994a2015-09-07 14:17:37 -07001870
1871 return final_result;
1872}
Jesse Hallb1352bc2015-09-04 16:12:33 -07001873
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001874VKAPI_ATTR
1875VkResult GetRefreshCycleDurationGOOGLE(
1876 VkDevice,
Ian Elliott62c48c92017-01-20 13:13:20 -07001877 VkSwapchainKHR swapchain_handle,
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001878 VkRefreshCycleDurationGOOGLE* pDisplayTimingProperties) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001879 ATRACE_CALL();
1880
Ian Elliott62c48c92017-01-20 13:13:20 -07001881 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001882 VkResult result = VK_SUCCESS;
1883
Ian Elliott3568bfe2019-05-03 15:54:46 -06001884 pDisplayTimingProperties->refreshDuration = swapchain.get_refresh_duration();
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001885
1886 return result;
1887}
1888
1889VKAPI_ATTR
1890VkResult GetPastPresentationTimingGOOGLE(
1891 VkDevice,
1892 VkSwapchainKHR swapchain_handle,
1893 uint32_t* count,
1894 VkPastPresentationTimingGOOGLE* timings) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001895 ATRACE_CALL();
1896
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001897 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Yiwei Zhang9d187832019-07-22 15:15:47 -07001898 if (swapchain.surface.swapchain_handle != swapchain_handle) {
1899 return VK_ERROR_OUT_OF_DATE_KHR;
1900 }
1901
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001902 ANativeWindow* window = swapchain.surface.window.get();
1903 VkResult result = VK_SUCCESS;
1904
1905 if (!swapchain.frame_timestamps_enabled) {
Ian Elliott8a977262017-01-19 09:05:58 -07001906 ALOGV("Calling native_window_enable_frame_timestamps(true)");
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001907 native_window_enable_frame_timestamps(window, true);
1908 swapchain.frame_timestamps_enabled = true;
1909 }
1910
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001911 if (timings) {
Yiwei Zhang9d187832019-07-22 15:15:47 -07001912 // Get the latest ready timing count before copying, since the copied
1913 // timing info will be erased in copy_ready_timings function.
1914 uint32_t n = get_num_ready_timings(swapchain);
Ian Elliott8a977262017-01-19 09:05:58 -07001915 copy_ready_timings(swapchain, count, timings);
Yiwei Zhang9d187832019-07-22 15:15:47 -07001916 // Check the *count here against the recorded ready timing count, since
1917 // *count can be overwritten per spec describes.
1918 if (*count < n) {
1919 result = VK_INCOMPLETE;
1920 }
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001921 } else {
Ian Elliott8a977262017-01-19 09:05:58 -07001922 *count = get_num_ready_timings(swapchain);
Ian Elliott4c8bb2a2016-12-29 11:07:26 -07001923 }
1924
1925 return result;
1926}
1927
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001928VKAPI_ATTR
1929VkResult GetSwapchainStatusKHR(
1930 VkDevice,
Chris Forbes4e18ba82017-01-20 12:50:17 +13001931 VkSwapchainKHR swapchain_handle) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001932 ATRACE_CALL();
1933
Chris Forbes4e18ba82017-01-20 12:50:17 +13001934 Swapchain& swapchain = *SwapchainFromHandle(swapchain_handle);
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001935 VkResult result = VK_SUCCESS;
1936
Chris Forbes4e18ba82017-01-20 12:50:17 +13001937 if (swapchain.surface.swapchain_handle != swapchain_handle) {
1938 return VK_ERROR_OUT_OF_DATE_KHR;
1939 }
1940
Yiwei Zhanga885c062019-10-24 12:07:57 -07001941 // TODO(b/143296009): Implement this function properly
Chris Forbes0f2ac2e2017-01-18 13:33:53 +13001942
1943 return result;
1944}
1945
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07001946VKAPI_ATTR void SetHdrMetadataEXT(
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08001947 VkDevice,
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07001948 uint32_t swapchainCount,
1949 const VkSwapchainKHR* pSwapchains,
1950 const VkHdrMetadataEXT* pHdrMetadataEXTs) {
Yiwei Zhangfdd0c2a2019-01-30 20:16:37 -08001951 ATRACE_CALL();
Courtney Goeltzenleuchter7671d462018-01-24 11:51:01 -08001952
1953 for (uint32_t idx = 0; idx < swapchainCount; idx++) {
1954 Swapchain* swapchain = SwapchainFromHandle(pSwapchains[idx]);
1955 if (!swapchain)
1956 continue;
1957
1958 if (swapchain->surface.swapchain_handle != pSwapchains[idx]) continue;
1959
1960 ANativeWindow* window = swapchain->surface.window.get();
1961
1962 VkHdrMetadataEXT vulkanMetadata = pHdrMetadataEXTs[idx];
1963 const android_smpte2086_metadata smpteMetdata = {
1964 {vulkanMetadata.displayPrimaryRed.x,
1965 vulkanMetadata.displayPrimaryRed.y},
1966 {vulkanMetadata.displayPrimaryGreen.x,
1967 vulkanMetadata.displayPrimaryGreen.y},
1968 {vulkanMetadata.displayPrimaryBlue.x,
1969 vulkanMetadata.displayPrimaryBlue.y},
1970 {vulkanMetadata.whitePoint.x, vulkanMetadata.whitePoint.y},
1971 vulkanMetadata.maxLuminance,
1972 vulkanMetadata.minLuminance};
1973 native_window_set_buffers_smpte2086_metadata(window, &smpteMetdata);
1974
1975 const android_cta861_3_metadata cta8613Metadata = {
1976 vulkanMetadata.maxContentLightLevel,
1977 vulkanMetadata.maxFrameAverageLightLevel};
1978 native_window_set_buffers_cta861_3_metadata(window, &cta8613Metadata);
1979 }
1980
Courtney Goeltzenleuchterd634c482017-01-05 15:55:31 -07001981 return;
1982}
1983
Yiwei Zhang0f475222019-04-11 19:38:00 -07001984static void InterceptBindImageMemory2(
1985 uint32_t bind_info_count,
1986 const VkBindImageMemoryInfo* bind_infos,
1987 std::vector<VkNativeBufferANDROID>* out_native_buffers,
1988 std::vector<VkBindImageMemoryInfo>* out_bind_infos) {
1989 out_native_buffers->clear();
1990 out_bind_infos->clear();
1991
1992 if (!bind_info_count)
1993 return;
1994
1995 std::unordered_set<uint32_t> intercepted_indexes;
1996
1997 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
1998 auto info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
1999 bind_infos[idx].pNext);
2000 while (info &&
2001 info->sType !=
2002 VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR) {
2003 info = reinterpret_cast<const VkBindImageMemorySwapchainInfoKHR*>(
2004 info->pNext);
2005 }
2006
2007 if (!info)
2008 continue;
2009
2010 ALOG_ASSERT(info->swapchain != VK_NULL_HANDLE,
2011 "swapchain handle must not be NULL");
2012 const Swapchain* swapchain = SwapchainFromHandle(info->swapchain);
2013 ALOG_ASSERT(
2014 info->imageIndex < swapchain->num_images,
2015 "imageIndex must be less than the number of images in swapchain");
2016
2017 ANativeWindowBuffer* buffer =
2018 swapchain->images[info->imageIndex].buffer.get();
2019 VkNativeBufferANDROID native_buffer = {
2020#pragma clang diagnostic push
2021#pragma clang diagnostic ignored "-Wold-style-cast"
2022 .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
2023#pragma clang diagnostic pop
2024 .pNext = bind_infos[idx].pNext,
2025 .handle = buffer->handle,
2026 .stride = buffer->stride,
2027 .format = buffer->format,
2028 .usage = int(buffer->usage),
2029 };
2030 // Reserve enough space to avoid letting re-allocation invalidate the
2031 // addresses of the elements inside.
2032 out_native_buffers->reserve(bind_info_count);
2033 out_native_buffers->emplace_back(native_buffer);
2034
2035 // Reserve the space now since we know how much is needed now.
2036 out_bind_infos->reserve(bind_info_count);
2037 out_bind_infos->emplace_back(bind_infos[idx]);
2038 out_bind_infos->back().pNext = &out_native_buffers->back();
2039
2040 intercepted_indexes.insert(idx);
2041 }
2042
2043 if (intercepted_indexes.empty())
2044 return;
2045
2046 for (uint32_t idx = 0; idx < bind_info_count; idx++) {
2047 if (intercepted_indexes.count(idx))
2048 continue;
2049 out_bind_infos->emplace_back(bind_infos[idx]);
2050 }
2051}
2052
Yiwei Zhang23143102019-04-10 18:24:05 -07002053VKAPI_ATTR
2054VkResult BindImageMemory2(VkDevice device,
2055 uint32_t bindInfoCount,
2056 const VkBindImageMemoryInfo* pBindInfos) {
2057 ATRACE_CALL();
2058
Yiwei Zhang0f475222019-04-11 19:38:00 -07002059 // out_native_buffers is for maintaining the lifecycle of the constructed
2060 // VkNativeBufferANDROID objects inside InterceptBindImageMemory2.
2061 std::vector<VkNativeBufferANDROID> out_native_buffers;
2062 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2063 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2064 &out_bind_infos);
2065 return GetData(device).driver.BindImageMemory2(
2066 device, bindInfoCount,
2067 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002068}
2069
2070VKAPI_ATTR
2071VkResult BindImageMemory2KHR(VkDevice device,
2072 uint32_t bindInfoCount,
2073 const VkBindImageMemoryInfo* pBindInfos) {
2074 ATRACE_CALL();
2075
Yiwei Zhang0f475222019-04-11 19:38:00 -07002076 std::vector<VkNativeBufferANDROID> out_native_buffers;
2077 std::vector<VkBindImageMemoryInfo> out_bind_infos;
2078 InterceptBindImageMemory2(bindInfoCount, pBindInfos, &out_native_buffers,
2079 &out_bind_infos);
2080 return GetData(device).driver.BindImageMemory2KHR(
2081 device, bindInfoCount,
2082 out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
Yiwei Zhang23143102019-04-10 18:24:05 -07002083}
2084
Chia-I Wu62262232016-03-26 07:06:44 +08002085} // namespace driver
Jesse Hallb1352bc2015-09-04 16:12:33 -07002086} // namespace vulkan