blob: 61f6feab94c3ec718316d86f6c4858d88e44d21a [file] [log] [blame]
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001#include <dvr/graphics.h>
2
Alex Vakulenko4fe60582017-02-02 11:35:59 -08003#include <inttypes.h>
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08004#include <sys/timerfd.h>
5#include <array>
6#include <vector>
7
Alex Vakulenko4fe60582017-02-02 11:35:59 -08008#include <log/log.h>
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08009#include <utils/Trace.h>
10
11#ifndef VK_USE_PLATFORM_ANDROID_KHR
12#define VK_USE_PLATFORM_ANDROID_KHR 1
13#endif
14#include <vulkan/vulkan.h>
15
16#include <pdx/file_handle.h>
17#include <private/dvr/clock_ns.h>
18#include <private/dvr/debug.h>
19#include <private/dvr/display_types.h>
20#include <private/dvr/frame_history.h>
21#include <private/dvr/gl_fenced_flush.h>
22#include <private/dvr/graphics/vr_gl_extensions.h>
23#include <private/dvr/graphics_private.h>
24#include <private/dvr/late_latch.h>
25#include <private/dvr/native_buffer_queue.h>
26#include <private/dvr/sensor_constants.h>
27#include <private/dvr/video_mesh_surface_client.h>
28#include <private/dvr/vsync_client.h>
29
30#include <android/native_window.h>
31
32#ifndef EGL_CONTEXT_MAJOR_VERSION
33#define EGL_CONTEXT_MAJOR_VERSION 0x3098
34#define EGL_CONTEXT_MINOR_VERSION 0x30FB
35#endif
36
37using android::pdx::LocalHandle;
38using android::pdx::LocalChannelHandle;
39
40using android::dvr::DisplaySurfaceAttributeEnum;
41using android::dvr::DisplaySurfaceAttributeValue;
42
43namespace {
44
45constexpr int kDefaultDisplaySurfaceUsage =
46 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
47constexpr int kDefaultDisplaySurfaceFormat = HAL_PIXEL_FORMAT_RGBA_8888;
48// TODO(alexst): revisit this count when HW encode is available for casting.
49constexpr int kDefaultBufferCount = 4;
50
51// Use with dvrBeginRenderFrame to disable EDS for the current frame.
52constexpr float32x4_t DVR_POSE_NO_EDS = {10.0f, 0.0f, 0.0f, 0.0f};
53
54// Use with dvrBeginRenderFrame to indicate that GPU late-latching is being used
55// for determining the render pose.
56constexpr float32x4_t DVR_POSE_LATE_LATCH = {20.0f, 0.0f, 0.0f, 0.0f};
57
58#ifndef NDEBUG
59
60static const char* GetGlCallbackType(GLenum type) {
61 switch (type) {
62 case GL_DEBUG_TYPE_ERROR_KHR:
63 return "ERROR";
64 case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR:
65 return "DEPRECATED_BEHAVIOR";
66 case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR:
67 return "UNDEFINED_BEHAVIOR";
68 case GL_DEBUG_TYPE_PORTABILITY_KHR:
69 return "PORTABILITY";
70 case GL_DEBUG_TYPE_PERFORMANCE_KHR:
71 return "PERFORMANCE";
72 case GL_DEBUG_TYPE_OTHER_KHR:
73 return "OTHER";
74 default:
75 return "UNKNOWN";
76 }
77}
78
79static void on_gl_error(GLenum /*source*/, GLenum type, GLuint /*id*/,
80 GLenum severity, GLsizei /*length*/,
81 const char* message, const void* /*user_param*/) {
82 char msg[400];
83 snprintf(msg, sizeof(msg), "[" __FILE__ ":%u] GL %s: %s", __LINE__,
84 GetGlCallbackType(type), message);
85 switch (severity) {
86 case GL_DEBUG_SEVERITY_LOW_KHR:
87 ALOGI("%s", msg);
88 break;
89 case GL_DEBUG_SEVERITY_MEDIUM_KHR:
90 ALOGW("%s", msg);
91 break;
92 case GL_DEBUG_SEVERITY_HIGH_KHR:
93 ALOGE("%s", msg);
94 break;
95 }
96 fprintf(stderr, "%s\n", msg);
97}
98
99#endif
100
101int DvrToHalSurfaceFormat(int dvr_surface_format) {
102 switch (dvr_surface_format) {
103 case DVR_SURFACE_FORMAT_RGBA_8888:
104 return HAL_PIXEL_FORMAT_RGBA_8888;
105 case DVR_SURFACE_FORMAT_RGB_565:
106 return HAL_PIXEL_FORMAT_RGB_565;
107 default:
108 return HAL_PIXEL_FORMAT_RGBA_8888;
109 }
110}
111
112int SelectEGLConfig(EGLDisplay dpy, EGLint* attr, unsigned format,
113 EGLConfig* config) {
114 std::array<EGLint, 4> desired_rgba;
115 switch (format) {
116 case HAL_PIXEL_FORMAT_RGBA_8888:
117 case HAL_PIXEL_FORMAT_BGRA_8888:
118 desired_rgba = {{8, 8, 8, 8}};
119 break;
120 case HAL_PIXEL_FORMAT_RGB_565:
121 desired_rgba = {{5, 6, 5, 0}};
122 break;
123 default:
124 ALOGE("Unsupported framebuffer pixel format %d", format);
125 return -1;
126 }
127
128 EGLint max_configs = 0;
129 if (eglGetConfigs(dpy, NULL, 0, &max_configs) == EGL_FALSE) {
130 ALOGE("No EGL configurations available?!");
131 return -1;
132 }
133
134 std::vector<EGLConfig> configs(max_configs);
135
136 EGLint num_configs;
137 if (eglChooseConfig(dpy, attr, &configs[0], max_configs, &num_configs) ==
138 EGL_FALSE) {
139 ALOGE("eglChooseConfig failed");
140 return -1;
141 }
142
143 std::array<EGLint, 4> config_rgba;
144 for (int i = 0; i < num_configs; i++) {
145 eglGetConfigAttrib(dpy, configs[i], EGL_RED_SIZE, &config_rgba[0]);
146 eglGetConfigAttrib(dpy, configs[i], EGL_GREEN_SIZE, &config_rgba[1]);
147 eglGetConfigAttrib(dpy, configs[i], EGL_BLUE_SIZE, &config_rgba[2]);
148 eglGetConfigAttrib(dpy, configs[i], EGL_ALPHA_SIZE, &config_rgba[3]);
149 if (config_rgba == desired_rgba) {
150 *config = configs[i];
151 return 0;
152 }
153 }
154
155 ALOGE("Cannot find a matching EGL config");
156 return -1;
157}
158
159void DestroyEglContext(EGLDisplay egl_display, EGLContext* egl_context) {
160 if (*egl_context != EGL_NO_CONTEXT) {
161 eglDestroyContext(egl_display, *egl_context);
162 *egl_context = EGL_NO_CONTEXT;
163 }
164}
165
166// Perform internal initialization. A GL context must be bound to the current
167// thread.
168// @param internally_created_context True if we created and own the GL context,
169// false if it was supplied by the application.
170// @return 0 if init was successful, or a negative error code on failure.
171int InitGl(bool internally_created_context) {
172 EGLDisplay egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
173 if (egl_display == EGL_NO_DISPLAY) {
174 ALOGE("eglGetDisplay failed");
175 return -EINVAL;
176 }
177
178 EGLContext egl_context = eglGetCurrentContext();
179 if (egl_context == EGL_NO_CONTEXT) {
180 ALOGE("No GL context bound");
181 return -EINVAL;
182 }
183
184 glGetError(); // Clear the error state
185 GLint major_version, minor_version;
186 glGetIntegerv(GL_MAJOR_VERSION, &major_version);
187 glGetIntegerv(GL_MINOR_VERSION, &minor_version);
188 if (glGetError() != GL_NO_ERROR) {
189 // GL_MAJOR_VERSION and GL_MINOR_VERSION were added in GLES 3. If we get an
190 // error querying them it's almost certainly because it's GLES 1 or 2.
191 ALOGE("Error getting GL version. Must be GLES 3.2 or greater.");
192 return -EINVAL;
193 }
194
195 if (major_version < 3 || (major_version == 3 && minor_version < 2)) {
196 ALOGE("Invalid GL version: %d.%d. Must be GLES 3.2 or greater.",
197 major_version, minor_version);
198 return -EINVAL;
199 }
200
201#ifndef NDEBUG
202 if (internally_created_context) {
203 // Enable verbose GL debug output.
204 glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR);
205 glDebugMessageCallbackKHR(on_gl_error, NULL);
206 GLuint unused_ids = 0;
207 glDebugMessageControlKHR(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0,
208 &unused_ids, GL_TRUE);
209 }
210#else
211 (void)internally_created_context;
212#endif
213
214 load_gl_extensions();
215 return 0;
216}
217
218int CreateEglContext(EGLDisplay egl_display, DvrSurfaceParameter* parameters,
219 EGLContext* egl_context) {
220 *egl_context = EGL_NO_CONTEXT;
221
222 EGLint major, minor;
223 if (!eglInitialize(egl_display, &major, &minor)) {
224 ALOGE("Failed to initialize EGL");
225 return -ENXIO;
226 }
227
228 ALOGI("EGL version: %d.%d\n", major, minor);
229
230 int buffer_format = kDefaultDisplaySurfaceFormat;
231
232 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
233 switch (p->key) {
234 case DVR_SURFACE_PARAMETER_FORMAT_IN:
235 buffer_format = DvrToHalSurfaceFormat(p->value);
236 break;
237 }
238 }
239
240 EGLint config_attrs[] = {EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
241 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE};
242 EGLConfig config = {0};
243
244 int ret = SelectEGLConfig(egl_display, config_attrs, buffer_format, &config);
245 if (ret < 0)
246 return ret;
247
248 ALOGI("EGL SelectEGLConfig ok.\n");
249
250 EGLint context_attrs[] = {EGL_CONTEXT_MAJOR_VERSION,
251 3,
252 EGL_CONTEXT_MINOR_VERSION,
253 2,
254#ifndef NDEBUG
255 EGL_CONTEXT_FLAGS_KHR,
256 EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR,
257#endif
258 EGL_NONE};
259
260 *egl_context =
261 eglCreateContext(egl_display, config, EGL_NO_CONTEXT, context_attrs);
262 if (*egl_context == EGL_NO_CONTEXT) {
263 ALOGE("eglCreateContext failed");
264 return -ENXIO;
265 }
266
267 ALOGI("eglCreateContext ok.\n");
268
269 if (!eglMakeCurrent(egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
270 *egl_context)) {
271 ALOGE("eglMakeCurrent failed");
272 DestroyEglContext(egl_display, egl_context);
273 return -EINVAL;
274 }
275
276 return 0;
277}
278
279} // anonymous namespace
280
281// TODO(hendrikw): When we remove the calls to this in native_window.cpp, move
282// this back into the anonymous namespace
283std::shared_ptr<android::dvr::DisplaySurfaceClient> CreateDisplaySurfaceClient(
284 struct DvrSurfaceParameter* parameters,
285 /*out*/ android::dvr::SystemDisplayMetrics* metrics) {
286 auto client = android::dvr::DisplayClient::Create();
287 if (!client) {
288 ALOGE("Failed to create display client!");
289 return nullptr;
290 }
291
292 const int ret = client->GetDisplayMetrics(metrics);
293 if (ret < 0) {
294 ALOGE("Failed to get display metrics: %s", strerror(-ret));
295 return nullptr;
296 }
297
298 // Parameters that may be modified by the parameters array. Some of these are
299 // here for future expansion.
300 int request_width = -1;
301 int request_height = -1;
302 int request_flags = 0;
303 bool disable_distortion = false;
304 bool disable_stabilization = false;
305 bool disable_cac = false;
306 bool request_visible = true;
307 bool vertical_flip = false;
308 int request_z_order = 0;
309 bool request_exclude_from_blur = false;
310 bool request_blur_behind = true;
311 int request_format = kDefaultDisplaySurfaceFormat;
312 int request_usage = kDefaultDisplaySurfaceUsage;
313 int geometry_type = DVR_SURFACE_GEOMETRY_SINGLE;
314
315 // Handle parameter inputs.
316 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
317 switch (p->key) {
318 case DVR_SURFACE_PARAMETER_WIDTH_IN:
319 request_width = p->value;
320 break;
321 case DVR_SURFACE_PARAMETER_HEIGHT_IN:
322 request_height = p->value;
323 break;
324 case DVR_SURFACE_PARAMETER_DISABLE_DISTORTION_IN:
325 disable_distortion = !!p->value;
326 break;
327 case DVR_SURFACE_PARAMETER_DISABLE_STABILIZATION_IN:
328 disable_stabilization = !!p->value;
329 break;
330 case DVR_SURFACE_PARAMETER_DISABLE_CAC_IN:
331 disable_cac = !!p->value;
332 break;
333 case DVR_SURFACE_PARAMETER_VISIBLE_IN:
334 request_visible = !!p->value;
335 break;
336 case DVR_SURFACE_PARAMETER_Z_ORDER_IN:
337 request_z_order = p->value;
338 break;
339 case DVR_SURFACE_PARAMETER_EXCLUDE_FROM_BLUR_IN:
340 request_exclude_from_blur = !!p->value;
341 break;
342 case DVR_SURFACE_PARAMETER_BLUR_BEHIND_IN:
343 request_blur_behind = !!p->value;
344 break;
345 case DVR_SURFACE_PARAMETER_VERTICAL_FLIP_IN:
346 vertical_flip = !!p->value;
347 break;
348 case DVR_SURFACE_PARAMETER_GEOMETRY_IN:
349 geometry_type = p->value;
350 break;
351 case DVR_SURFACE_PARAMETER_FORMAT_IN:
352 request_format = DvrToHalSurfaceFormat(p->value);
353 break;
354 case DVR_SURFACE_PARAMETER_ENABLE_LATE_LATCH_IN:
355 case DVR_SURFACE_PARAMETER_CREATE_GL_CONTEXT_IN:
356 case DVR_SURFACE_PARAMETER_DISPLAY_WIDTH_OUT:
357 case DVR_SURFACE_PARAMETER_DISPLAY_HEIGHT_OUT:
358 case DVR_SURFACE_PARAMETER_SURFACE_WIDTH_OUT:
359 case DVR_SURFACE_PARAMETER_SURFACE_HEIGHT_OUT:
360 case DVR_SURFACE_PARAMETER_INTER_LENS_METERS_OUT:
361 case DVR_SURFACE_PARAMETER_LEFT_FOV_LRBT_OUT:
362 case DVR_SURFACE_PARAMETER_RIGHT_FOV_LRBT_OUT:
363 case DVR_SURFACE_PARAMETER_VSYNC_PERIOD_OUT:
364 case DVR_SURFACE_PARAMETER_SURFACE_TEXTURE_TARGET_TYPE_OUT:
365 case DVR_SURFACE_PARAMETER_SURFACE_TEXTURE_TARGET_ID_OUT:
366 case DVR_SURFACE_PARAMETER_GRAPHICS_API_IN:
367 case DVR_SURFACE_PARAMETER_VK_INSTANCE_IN:
368 case DVR_SURFACE_PARAMETER_VK_PHYSICAL_DEVICE_IN:
369 case DVR_SURFACE_PARAMETER_VK_DEVICE_IN:
370 case DVR_SURFACE_PARAMETER_VK_PRESENT_QUEUE_IN:
371 case DVR_SURFACE_PARAMETER_VK_PRESENT_QUEUE_FAMILY_IN:
372 case DVR_SURFACE_PARAMETER_VK_SWAPCHAIN_IMAGE_COUNT_OUT:
373 case DVR_SURFACE_PARAMETER_VK_SWAPCHAIN_IMAGE_FORMAT_OUT:
374 break;
375 default:
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800376 ALOGE("Invalid display surface parameter: key=%d value=%" PRId64,
377 p->key, p->value);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800378 return nullptr;
379 }
380 }
381
382 request_flags |= disable_distortion
383 ? DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_DISTORTION
384 : 0;
385 request_flags |=
386 disable_stabilization ? DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_EDS : 0;
387 request_flags |=
388 disable_cac ? DVR_DISPLAY_SURFACE_FLAGS_DISABLE_SYSTEM_CAC : 0;
389 request_flags |= vertical_flip ? DVR_DISPLAY_SURFACE_FLAGS_VERTICAL_FLIP : 0;
390 request_flags |= (geometry_type == DVR_SURFACE_GEOMETRY_SEPARATE_2)
391 ? DVR_DISPLAY_SURFACE_FLAGS_GEOMETRY_SEPARATE_2
392 : 0;
393
394 if (request_width == -1) {
395 request_width = disable_distortion ? metrics->display_native_width
396 : metrics->distorted_width;
397 if (!disable_distortion &&
398 geometry_type == DVR_SURFACE_GEOMETRY_SEPARATE_2) {
399 // The metrics always return the single wide buffer resolution.
400 // When split between eyes, we need to halve the width of the surface.
401 request_width /= 2;
402 }
403 }
404 if (request_height == -1) {
405 request_height = disable_distortion ? metrics->display_native_height
406 : metrics->distorted_height;
407 }
408
409 std::shared_ptr<android::dvr::DisplaySurfaceClient> surface =
410 client->CreateDisplaySurface(request_width, request_height,
411 request_format, request_usage,
412 request_flags);
413 surface->SetAttributes(
414 {{DisplaySurfaceAttributeEnum::Visible,
415 DisplaySurfaceAttributeValue{request_visible}},
416 {DisplaySurfaceAttributeEnum::ZOrder,
417 DisplaySurfaceAttributeValue{request_z_order}},
418 {DisplaySurfaceAttributeEnum::ExcludeFromBlur,
419 DisplaySurfaceAttributeValue{request_exclude_from_blur}},
420 {DisplaySurfaceAttributeEnum::BlurBehind,
421 DisplaySurfaceAttributeValue{request_blur_behind}}});
422
423 // Handle parameter output requests down here so we can return surface info.
424 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
425 switch (p->key) {
426 case DVR_SURFACE_PARAMETER_DISPLAY_WIDTH_OUT:
427 *static_cast<int32_t*>(p->value_out) = metrics->display_native_width;
428 break;
429 case DVR_SURFACE_PARAMETER_DISPLAY_HEIGHT_OUT:
430 *static_cast<int32_t*>(p->value_out) = metrics->display_native_height;
431 break;
432 case DVR_SURFACE_PARAMETER_SURFACE_WIDTH_OUT:
433 *static_cast<int32_t*>(p->value_out) = surface->width();
434 break;
435 case DVR_SURFACE_PARAMETER_SURFACE_HEIGHT_OUT:
436 *static_cast<int32_t*>(p->value_out) = surface->height();
437 break;
438 case DVR_SURFACE_PARAMETER_INTER_LENS_METERS_OUT:
439 *static_cast<float*>(p->value_out) = metrics->inter_lens_distance_m;
440 break;
441 case DVR_SURFACE_PARAMETER_LEFT_FOV_LRBT_OUT:
442 for (int i = 0; i < 4; ++i) {
443 float* float_values_out = static_cast<float*>(p->value_out);
444 float_values_out[i] = metrics->left_fov_lrbt[i];
445 }
446 break;
447 case DVR_SURFACE_PARAMETER_RIGHT_FOV_LRBT_OUT:
448 for (int i = 0; i < 4; ++i) {
449 float* float_values_out = static_cast<float*>(p->value_out);
450 float_values_out[i] = metrics->right_fov_lrbt[i];
451 }
452 break;
453 case DVR_SURFACE_PARAMETER_VSYNC_PERIOD_OUT:
454 *static_cast<uint64_t*>(p->value_out) = metrics->vsync_period_ns;
455 break;
456 default:
457 break;
458 }
459 }
460
461 return surface;
462}
463
464extern "C" int dvrGetNativeDisplayDimensions(int* native_width,
465 int* native_height) {
466 int error = 0;
467 auto client = android::dvr::DisplayClient::Create(&error);
468 if (!client) {
469 ALOGE("Failed to create display client!");
470 return error;
471 }
472
473 android::dvr::SystemDisplayMetrics metrics;
474 const int ret = client->GetDisplayMetrics(&metrics);
475
476 if (ret != 0) {
477 ALOGE("Failed to get display metrics!");
478 return ret;
479 }
480
481 *native_width = static_cast<int>(metrics.display_native_width);
482 *native_height = static_cast<int>(metrics.display_native_height);
483 return 0;
484}
485
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800486struct DvrGraphicsContext : public android::ANativeObjectBase<
487 ANativeWindow, DvrGraphicsContext,
488 android::LightRefBase<DvrGraphicsContext>> {
489 public:
490 DvrGraphicsContext();
491 ~DvrGraphicsContext();
492
493 int graphics_api; // DVR_SURFACE_GRAPHICS_API_*
494
495 // GL specific members.
496 struct {
497 EGLDisplay egl_display;
498 EGLContext egl_context;
499 bool owns_egl_context;
500 GLuint texture_id[kSurfaceViewMaxCount];
501 int texture_count;
502 GLenum texture_target_type;
503 } gl;
504
505 // VK specific members
506 struct {
507 // These objects are passed in by the application, and are NOT owned
508 // by the context.
509 VkInstance instance;
510 VkPhysicalDevice physical_device;
511 VkDevice device;
512 VkQueue present_queue;
513 uint32_t present_queue_family;
514 const VkAllocationCallbacks* allocation_callbacks;
515 // These objects are owned by the context.
516 ANativeWindow* window;
517 VkSurfaceKHR surface;
518 VkSwapchainKHR swapchain;
519 std::vector<VkImage> swapchain_images;
520 std::vector<VkImageView> swapchain_image_views;
521 } vk;
522
523 // Display surface, metrics, and buffer management members.
524 std::shared_ptr<android::dvr::DisplaySurfaceClient> display_surface;
525 android::dvr::SystemDisplayMetrics display_metrics;
526 std::unique_ptr<android::dvr::NativeBufferQueue> buffer_queue;
527 android::dvr::NativeBufferProducer* current_buffer;
528 bool buffer_already_posted;
529
530 // Synchronization members.
531 std::unique_ptr<android::dvr::VSyncClient> vsync_client;
532 LocalHandle timerfd;
533
534 android::dvr::FrameHistory frame_history;
535
536 // Mapped surface metadata (ie: for pose delivery with presented frames).
537 volatile android::dvr::DisplaySurfaceMetadata* surface_metadata;
538
539 // LateLatch support.
540 std::unique_ptr<android::dvr::LateLatch> late_latch;
541
542 // Video mesh support.
543 std::vector<std::shared_ptr<android::dvr::VideoMeshSurfaceClient>>
544 video_mesh_surfaces;
545
546 private:
547 // ANativeWindow function implementations
548 std::mutex lock_;
549 int Post(android::dvr::NativeBufferProducer* buffer, int fence_fd);
550 static int SetSwapInterval(ANativeWindow* window, int interval);
551 static int DequeueBuffer(ANativeWindow* window, ANativeWindowBuffer** buffer,
552 int* fence_fd);
553 static int QueueBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer,
554 int fence_fd);
555 static int CancelBuffer(ANativeWindow* window, ANativeWindowBuffer* buffer,
556 int fence_fd);
557 static int Query(const ANativeWindow* window, int what, int* value);
558 static int Perform(ANativeWindow* window, int operation, ...);
559 static int DequeueBuffer_DEPRECATED(ANativeWindow* window,
560 ANativeWindowBuffer** buffer);
561 static int CancelBuffer_DEPRECATED(ANativeWindow* window,
562 ANativeWindowBuffer* buffer);
563 static int QueueBuffer_DEPRECATED(ANativeWindow* window,
564 ANativeWindowBuffer* buffer);
565 static int LockBuffer_DEPRECATED(ANativeWindow* window,
566 ANativeWindowBuffer* buffer);
567
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800568 DvrGraphicsContext(const DvrGraphicsContext&) = delete;
569 void operator=(const DvrGraphicsContext&) = delete;
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800570};
571
572DvrGraphicsContext::DvrGraphicsContext()
573 : graphics_api(DVR_GRAPHICS_API_GLES),
574 gl{},
575 vk{},
576 current_buffer(nullptr),
577 buffer_already_posted(false),
578 surface_metadata(nullptr) {
579 gl.egl_display = EGL_NO_DISPLAY;
580 gl.egl_context = EGL_NO_CONTEXT;
581 gl.owns_egl_context = true;
582 gl.texture_target_type = GL_TEXTURE_2D;
583
584 ANativeWindow::setSwapInterval = SetSwapInterval;
585 ANativeWindow::dequeueBuffer = DequeueBuffer;
586 ANativeWindow::cancelBuffer = CancelBuffer;
587 ANativeWindow::queueBuffer = QueueBuffer;
588 ANativeWindow::query = Query;
589 ANativeWindow::perform = Perform;
590
591 ANativeWindow::dequeueBuffer_DEPRECATED = DequeueBuffer_DEPRECATED;
592 ANativeWindow::cancelBuffer_DEPRECATED = CancelBuffer_DEPRECATED;
593 ANativeWindow::lockBuffer_DEPRECATED = LockBuffer_DEPRECATED;
594 ANativeWindow::queueBuffer_DEPRECATED = QueueBuffer_DEPRECATED;
595}
596
597DvrGraphicsContext::~DvrGraphicsContext() {
598 if (graphics_api == DVR_GRAPHICS_API_GLES) {
599 glDeleteTextures(gl.texture_count, gl.texture_id);
600 if (gl.owns_egl_context)
601 DestroyEglContext(gl.egl_display, &gl.egl_context);
602 } else if (graphics_api == DVR_GRAPHICS_API_VULKAN) {
603 if (vk.swapchain != VK_NULL_HANDLE) {
604 for (auto view : vk.swapchain_image_views) {
605 vkDestroyImageView(vk.device, view, vk.allocation_callbacks);
606 }
607 vkDestroySwapchainKHR(vk.device, vk.swapchain, vk.allocation_callbacks);
608 vkDestroySurfaceKHR(vk.instance, vk.surface, vk.allocation_callbacks);
609 delete vk.window;
610 }
611 }
612}
613
614int dvrGraphicsContextCreate(struct DvrSurfaceParameter* parameters,
615 DvrGraphicsContext** return_graphics_context) {
616 std::unique_ptr<DvrGraphicsContext> context(new DvrGraphicsContext);
617
618 // See whether we're using GL or Vulkan
619 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
620 switch (p->key) {
621 case DVR_SURFACE_PARAMETER_GRAPHICS_API_IN:
622 context->graphics_api = p->value;
623 break;
624 }
625 }
626
627 if (context->graphics_api == DVR_GRAPHICS_API_GLES) {
628 context->gl.egl_display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
629 if (context->gl.egl_display == EGL_NO_DISPLAY) {
630 ALOGE("eglGetDisplay failed");
631 return -ENXIO;
632 }
633
634 // See if we should create a GL context
635 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
636 switch (p->key) {
637 case DVR_SURFACE_PARAMETER_CREATE_GL_CONTEXT_IN:
638 context->gl.owns_egl_context = p->value != 0;
639 break;
640 }
641 }
642
643 if (context->gl.owns_egl_context) {
644 int ret = CreateEglContext(context->gl.egl_display, parameters,
645 &context->gl.egl_context);
646 if (ret < 0)
647 return ret;
648 } else {
649 context->gl.egl_context = eglGetCurrentContext();
650 }
651
652 int ret = InitGl(context->gl.owns_egl_context);
653 if (ret < 0)
654 return ret;
655 } else if (context->graphics_api == DVR_GRAPHICS_API_VULKAN) {
656 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
657 switch (p->key) {
658 case DVR_SURFACE_PARAMETER_VK_INSTANCE_IN:
659 context->vk.instance = reinterpret_cast<VkInstance>(p->value);
660 break;
661 case DVR_SURFACE_PARAMETER_VK_PHYSICAL_DEVICE_IN:
662 context->vk.physical_device =
663 reinterpret_cast<VkPhysicalDevice>(p->value);
664 break;
665 case DVR_SURFACE_PARAMETER_VK_DEVICE_IN:
666 context->vk.device = reinterpret_cast<VkDevice>(p->value);
667 break;
668 case DVR_SURFACE_PARAMETER_VK_PRESENT_QUEUE_IN:
669 context->vk.present_queue = reinterpret_cast<VkQueue>(p->value);
670 break;
671 case DVR_SURFACE_PARAMETER_VK_PRESENT_QUEUE_FAMILY_IN:
672 context->vk.present_queue_family = static_cast<uint32_t>(p->value);
673 break;
674 }
675 }
676 } else {
677 ALOGE("Error: invalid graphics API type");
678 return -EINVAL;
679 }
680
681 context->display_surface =
682 CreateDisplaySurfaceClient(parameters, &context->display_metrics);
683 if (!context->display_surface) {
684 ALOGE("Error: failed to create display surface client");
685 return -ECOMM;
686 }
687
688 context->buffer_queue.reset(new android::dvr::NativeBufferQueue(
689 context->gl.egl_display, context->display_surface, kDefaultBufferCount));
690
691 // The way the call sequence works we need 1 more than the buffer queue
692 // capacity to store data for all pending frames
693 context->frame_history.Reset(context->buffer_queue->GetQueueCapacity() + 1);
694
695 context->vsync_client = android::dvr::VSyncClient::Create();
696 if (!context->vsync_client) {
697 ALOGE("Error: failed to create vsync client");
698 return -ECOMM;
699 }
700
701 context->timerfd.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
702 if (!context->timerfd) {
703 ALOGE("Error: timerfd_create failed because: %s", strerror(errno));
704 return -EPERM;
705 }
706
707 context->surface_metadata = context->display_surface->GetMetadataBufferPtr();
708 if (!context->surface_metadata) {
709 ALOGE("Error: surface metadata allocation failed");
710 return -ENOMEM;
711 }
712
713 ALOGI("buffer: %d x %d\n", context->display_surface->width(),
714 context->display_surface->height());
715
716 if (context->graphics_api == DVR_GRAPHICS_API_GLES) {
717 context->gl.texture_count = (context->display_surface->flags() &
718 DVR_DISPLAY_SURFACE_FLAGS_GEOMETRY_SEPARATE_2)
719 ? 2
720 : 1;
721
722 // Create the GL textures.
723 glGenTextures(context->gl.texture_count, context->gl.texture_id);
724
725 // We must make sure that we have at least one buffer allocated at this time
726 // so that anyone who tries to bind an FBO to context->texture_id
727 // will not get an incomplete buffer.
728 context->current_buffer = context->buffer_queue->Dequeue();
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800729 LOG_ALWAYS_FATAL_IF(context->gl.texture_count !=
730 context->current_buffer->buffer()->slice_count());
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800731 for (int i = 0; i < context->gl.texture_count; ++i) {
732 glBindTexture(context->gl.texture_target_type, context->gl.texture_id[i]);
733 glEGLImageTargetTexture2DOES(context->gl.texture_target_type,
734 context->current_buffer->image_khr(i));
735 }
736 glBindTexture(context->gl.texture_target_type, 0);
737 CHECK_GL();
738
739 bool is_late_latch = false;
740
741 // Pass back the texture target type and id.
742 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
743 switch (p->key) {
744 case DVR_SURFACE_PARAMETER_ENABLE_LATE_LATCH_IN:
745 is_late_latch = !!p->value;
746 break;
747 case DVR_SURFACE_PARAMETER_SURFACE_TEXTURE_TARGET_TYPE_OUT:
748 *static_cast<GLenum*>(p->value_out) = context->gl.texture_target_type;
749 break;
750 case DVR_SURFACE_PARAMETER_SURFACE_TEXTURE_TARGET_ID_OUT:
751 for (int i = 0; i < context->gl.texture_count; ++i) {
752 *(static_cast<GLuint*>(p->value_out) + i) =
753 context->gl.texture_id[i];
754 }
755 break;
756 }
757 }
758
759 // Initialize late latch.
760 if (is_late_latch) {
761 LocalHandle fd;
762 int ret = context->display_surface->GetMetadataBufferFd(&fd);
763 if (ret == 0) {
764 context->late_latch.reset(
765 new android::dvr::LateLatch(true, std::move(fd)));
766 } else {
767 ALOGE("Error: failed to get surface metadata buffer fd for late latch");
768 }
769 }
770 } else if (context->graphics_api == DVR_GRAPHICS_API_VULKAN) {
771 VkResult result = VK_SUCCESS;
772 // Create a VkSurfaceKHR from the ANativeWindow.
773 VkAndroidSurfaceCreateInfoKHR android_surface_ci = {};
774 android_surface_ci.sType =
775 VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
776 android_surface_ci.window = context.get();
777 result = vkCreateAndroidSurfaceKHR(
778 context->vk.instance, &android_surface_ci,
779 context->vk.allocation_callbacks, &context->vk.surface);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800780 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800781 VkBool32 surface_supports_present = VK_FALSE;
782 result = vkGetPhysicalDeviceSurfaceSupportKHR(
783 context->vk.physical_device, context->vk.present_queue_family,
784 context->vk.surface, &surface_supports_present);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800785 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800786 if (!surface_supports_present) {
787 ALOGE("Error: provided queue family (%u) does not support presentation",
788 context->vk.present_queue_family);
789 return -EPERM;
790 }
791 VkSurfaceCapabilitiesKHR surface_capabilities = {};
792 result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
793 context->vk.physical_device, context->vk.surface,
794 &surface_capabilities);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800795 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800796 // Determine the swapchain image format.
797 uint32_t device_surface_format_count = 0;
798 result = vkGetPhysicalDeviceSurfaceFormatsKHR(
799 context->vk.physical_device, context->vk.surface,
800 &device_surface_format_count, nullptr);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800801 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800802 std::vector<VkSurfaceFormatKHR> device_surface_formats(
803 device_surface_format_count);
804 result = vkGetPhysicalDeviceSurfaceFormatsKHR(
805 context->vk.physical_device, context->vk.surface,
806 &device_surface_format_count, device_surface_formats.data());
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800807 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
808 LOG_ALWAYS_FATAL_IF(device_surface_format_count == 0U);
809 LOG_ALWAYS_FATAL_IF(device_surface_formats[0].format ==
810 VK_FORMAT_UNDEFINED);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800811 VkSurfaceFormatKHR present_surface_format = device_surface_formats[0];
812 // Determine the swapchain present mode.
813 // TODO(cort): query device_present_modes to make sure MAILBOX is supported.
814 // But according to libvulkan, it is.
815 uint32_t device_present_mode_count = 0;
816 result = vkGetPhysicalDeviceSurfacePresentModesKHR(
817 context->vk.physical_device, context->vk.surface,
818 &device_present_mode_count, nullptr);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800819 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800820 std::vector<VkPresentModeKHR> device_present_modes(
821 device_present_mode_count);
822 result = vkGetPhysicalDeviceSurfacePresentModesKHR(
823 context->vk.physical_device, context->vk.surface,
824 &device_present_mode_count, device_present_modes.data());
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800825 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800826 VkPresentModeKHR present_mode = VK_PRESENT_MODE_MAILBOX_KHR;
827 // Extract presentation surface extents, image count, transform, usages,
828 // etc.
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800829 LOG_ALWAYS_FATAL_IF(
830 static_cast<int>(surface_capabilities.currentExtent.width) == -1 ||
831 static_cast<int>(surface_capabilities.currentExtent.height) == -1);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800832 VkExtent2D swapchain_extent = surface_capabilities.currentExtent;
833
834 uint32_t desired_image_count = surface_capabilities.minImageCount;
835 if (surface_capabilities.maxImageCount > 0 &&
836 desired_image_count > surface_capabilities.maxImageCount) {
837 desired_image_count = surface_capabilities.maxImageCount;
838 }
839 VkSurfaceTransformFlagBitsKHR surface_transform =
840 surface_capabilities.currentTransform;
841 VkImageUsageFlags image_usage_flags =
842 surface_capabilities.supportedUsageFlags;
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800843 LOG_ALWAYS_FATAL_IF(surface_capabilities.supportedCompositeAlpha ==
844 static_cast<VkFlags>(0));
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800845 VkCompositeAlphaFlagBitsKHR composite_alpha =
846 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
847 if (!(surface_capabilities.supportedCompositeAlpha &
848 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)) {
849 composite_alpha = VkCompositeAlphaFlagBitsKHR(
850 static_cast<int>(surface_capabilities.supportedCompositeAlpha) &
851 -static_cast<int>(surface_capabilities.supportedCompositeAlpha));
852 }
853 // Create VkSwapchainKHR
854 VkSwapchainCreateInfoKHR swapchain_ci = {};
855 swapchain_ci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
856 swapchain_ci.pNext = nullptr;
857 swapchain_ci.surface = context->vk.surface;
858 swapchain_ci.minImageCount = desired_image_count;
859 swapchain_ci.imageFormat = present_surface_format.format;
860 swapchain_ci.imageColorSpace = present_surface_format.colorSpace;
861 swapchain_ci.imageExtent.width = swapchain_extent.width;
862 swapchain_ci.imageExtent.height = swapchain_extent.height;
863 swapchain_ci.imageUsage = image_usage_flags;
864 swapchain_ci.preTransform = surface_transform;
865 swapchain_ci.compositeAlpha = composite_alpha;
866 swapchain_ci.imageArrayLayers = 1;
867 swapchain_ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
868 swapchain_ci.queueFamilyIndexCount = 0;
869 swapchain_ci.pQueueFamilyIndices = nullptr;
870 swapchain_ci.presentMode = present_mode;
871 swapchain_ci.clipped = VK_TRUE;
872 swapchain_ci.oldSwapchain = VK_NULL_HANDLE;
873 result = vkCreateSwapchainKHR(context->vk.device, &swapchain_ci,
874 context->vk.allocation_callbacks,
875 &context->vk.swapchain);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800876 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800877 // Create swapchain image views
878 uint32_t image_count = 0;
879 result = vkGetSwapchainImagesKHR(context->vk.device, context->vk.swapchain,
880 &image_count, nullptr);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800881 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
882 LOG_ALWAYS_FATAL_IF(image_count == 0U);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800883 context->vk.swapchain_images.resize(image_count);
884 result = vkGetSwapchainImagesKHR(context->vk.device, context->vk.swapchain,
885 &image_count,
886 context->vk.swapchain_images.data());
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800887 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800888 context->vk.swapchain_image_views.resize(image_count);
889 VkImageViewCreateInfo image_view_ci = {};
890 image_view_ci.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
891 image_view_ci.pNext = nullptr;
892 image_view_ci.flags = 0;
893 image_view_ci.format = swapchain_ci.imageFormat;
894 image_view_ci.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
895 image_view_ci.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
896 image_view_ci.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
897 image_view_ci.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
898 image_view_ci.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
899 image_view_ci.subresourceRange.baseMipLevel = 0;
900 image_view_ci.subresourceRange.levelCount = 1;
901 image_view_ci.subresourceRange.baseArrayLayer = 0;
902 image_view_ci.subresourceRange.layerCount = 1;
903 image_view_ci.viewType = VK_IMAGE_VIEW_TYPE_2D;
904 image_view_ci.image = VK_NULL_HANDLE; // filled in below
905 for (uint32_t i = 0; i < image_count; ++i) {
906 image_view_ci.image = context->vk.swapchain_images[i];
907 result = vkCreateImageView(context->vk.device, &image_view_ci,
908 context->vk.allocation_callbacks,
909 &context->vk.swapchain_image_views[i]);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800910 LOG_ALWAYS_FATAL_IF(result != VK_SUCCESS);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800911 }
912 // Fill in any requested output parameters.
913 for (auto p = parameters; p && p->key != DVR_SURFACE_PARAMETER_NONE; ++p) {
914 switch (p->key) {
915 case DVR_SURFACE_PARAMETER_VK_SWAPCHAIN_IMAGE_COUNT_OUT:
916 *static_cast<uint32_t*>(p->value_out) = image_count;
917 break;
918 case DVR_SURFACE_PARAMETER_VK_SWAPCHAIN_IMAGE_FORMAT_OUT:
919 *static_cast<VkFormat*>(p->value_out) = swapchain_ci.imageFormat;
920 break;
921 }
922 }
923 }
924
925 *return_graphics_context = context.release();
926 return 0;
927}
928
929void dvrGraphicsContextDestroy(DvrGraphicsContext* graphics_context) {
930 delete graphics_context;
931}
932
933// ANativeWindow function implementations. These should only be used
934// by the Vulkan path.
935int DvrGraphicsContext::Post(android::dvr::NativeBufferProducer* buffer,
936 int fence_fd) {
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800937 LOG_ALWAYS_FATAL_IF(graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800938 ATRACE_NAME(__PRETTY_FUNCTION__);
939 ALOGI_IF(TRACE, "DvrGraphicsContext::Post: buffer_id=%d, fence_fd=%d",
940 buffer->buffer()->id(), fence_fd);
941 ALOGW_IF(!display_surface->visible(),
942 "DvrGraphicsContext::Post: Posting buffer on invisible surface!!!");
943 // The NativeBufferProducer closes the fence fd, so dup it for tracking in the
944 // frame history.
945 frame_history.OnFrameSubmit(LocalHandle::AsDuplicate(fence_fd));
946 int result = buffer->Post(fence_fd, 0);
947 return result;
948}
949
950int DvrGraphicsContext::SetSwapInterval(ANativeWindow* window, int interval) {
951 ALOGI_IF(TRACE, "SetSwapInterval: window=%p interval=%d", window, interval);
952 DvrGraphicsContext* self = getSelf(window);
953 (void)self;
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800954 LOG_ALWAYS_FATAL_IF(self->graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800955 return android::NO_ERROR;
956}
957
958int DvrGraphicsContext::DequeueBuffer(ANativeWindow* window,
959 ANativeWindowBuffer** buffer,
960 int* fence_fd) {
961 ATRACE_NAME(__PRETTY_FUNCTION__);
962
963 DvrGraphicsContext* self = getSelf(window);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800964 LOG_ALWAYS_FATAL_IF(self->graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800965 std::lock_guard<std::mutex> autolock(self->lock_);
966
967 if (!self->current_buffer) {
968 self->current_buffer = self->buffer_queue.get()->Dequeue();
969 }
970 ATRACE_ASYNC_BEGIN("BufferDraw", self->current_buffer->buffer()->id());
971 *fence_fd = self->current_buffer->ClaimReleaseFence().Release();
972 *buffer = self->current_buffer;
973
974 ALOGI_IF(TRACE, "DvrGraphicsContext::DequeueBuffer: fence_fd=%d", *fence_fd);
975 return android::NO_ERROR;
976}
977
978int DvrGraphicsContext::QueueBuffer(ANativeWindow* window,
979 ANativeWindowBuffer* buffer, int fence_fd) {
980 ATRACE_NAME("NativeWindow::QueueBuffer");
981 ALOGI_IF(TRACE, "NativeWindow::QueueBuffer: fence_fd=%d", fence_fd);
982
983 DvrGraphicsContext* self = getSelf(window);
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800984 LOG_ALWAYS_FATAL_IF(self->graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800985 std::lock_guard<std::mutex> autolock(self->lock_);
986
987 android::dvr::NativeBufferProducer* native_buffer =
988 static_cast<android::dvr::NativeBufferProducer*>(buffer);
989 ATRACE_ASYNC_END("BufferDraw", native_buffer->buffer()->id());
990 bool do_post = true;
991 if (self->buffer_already_posted) {
992 // Check that the buffer is the one we expect, but handle it if this happens
993 // in production by allowing this buffer to post on top of the previous one.
Alex Vakulenko4fe60582017-02-02 11:35:59 -0800994 LOG_FATAL_IF(native_buffer != self->current_buffer);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -0800995 if (native_buffer == self->current_buffer) {
996 do_post = false;
997 if (fence_fd >= 0)
998 close(fence_fd);
999 }
1000 }
1001 if (do_post) {
1002 ATRACE_ASYNC_BEGIN("BufferPost", native_buffer->buffer()->id());
1003 self->Post(native_buffer, fence_fd);
1004 }
1005 self->buffer_already_posted = false;
1006 self->current_buffer = nullptr;
1007
1008 return android::NO_ERROR;
1009}
1010
1011int DvrGraphicsContext::CancelBuffer(ANativeWindow* window,
1012 ANativeWindowBuffer* buffer,
1013 int fence_fd) {
1014 ATRACE_NAME("DvrGraphicsContext::CancelBuffer");
1015 ALOGI_IF(TRACE, "DvrGraphicsContext::CancelBuffer: fence_fd: %d", fence_fd);
1016
1017 DvrGraphicsContext* self = getSelf(window);
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001018 LOG_ALWAYS_FATAL_IF(self->graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001019 std::lock_guard<std::mutex> autolock(self->lock_);
1020
1021 android::dvr::NativeBufferProducer* native_buffer =
1022 static_cast<android::dvr::NativeBufferProducer*>(buffer);
1023 ATRACE_ASYNC_END("BufferDraw", native_buffer->buffer()->id());
1024 ATRACE_INT("CancelBuffer", native_buffer->buffer()->id());
1025 bool do_enqueue = true;
1026 if (self->buffer_already_posted) {
1027 // Check that the buffer is the one we expect, but handle it if this happens
1028 // in production by returning this buffer to the buffer queue.
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001029 LOG_FATAL_IF(native_buffer != self->current_buffer);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001030 if (native_buffer == self->current_buffer) {
1031 do_enqueue = false;
1032 }
1033 }
1034 if (do_enqueue) {
1035 self->buffer_queue.get()->Enqueue(native_buffer);
1036 }
1037 if (fence_fd >= 0)
1038 close(fence_fd);
1039 self->buffer_already_posted = false;
1040 self->current_buffer = nullptr;
1041
1042 return android::NO_ERROR;
1043}
1044
1045int DvrGraphicsContext::Query(const ANativeWindow* window, int what,
1046 int* value) {
1047 DvrGraphicsContext* self = getSelf(const_cast<ANativeWindow*>(window));
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001048 LOG_ALWAYS_FATAL_IF(self->graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001049 std::lock_guard<std::mutex> autolock(self->lock_);
1050
1051 switch (what) {
1052 case NATIVE_WINDOW_WIDTH:
1053 *value = self->display_surface->width();
1054 return android::NO_ERROR;
1055 case NATIVE_WINDOW_HEIGHT:
1056 *value = self->display_surface->height();
1057 return android::NO_ERROR;
1058 case NATIVE_WINDOW_FORMAT:
1059 *value = self->display_surface->format();
1060 return android::NO_ERROR;
1061 case NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS:
1062 *value = 1;
1063 return android::NO_ERROR;
1064 case NATIVE_WINDOW_CONCRETE_TYPE:
1065 *value = NATIVE_WINDOW_SURFACE;
1066 return android::NO_ERROR;
1067 case NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER:
1068 *value = 1;
1069 return android::NO_ERROR;
1070 case NATIVE_WINDOW_DEFAULT_WIDTH:
1071 *value = self->display_surface->width();
1072 return android::NO_ERROR;
1073 case NATIVE_WINDOW_DEFAULT_HEIGHT:
1074 *value = self->display_surface->height();
1075 return android::NO_ERROR;
1076 case NATIVE_WINDOW_TRANSFORM_HINT:
1077 *value = 0;
1078 return android::NO_ERROR;
1079 }
1080
1081 *value = 0;
1082 return android::BAD_VALUE;
1083}
1084
1085int DvrGraphicsContext::Perform(ANativeWindow* window, int operation, ...) {
1086 DvrGraphicsContext* self = getSelf(window);
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001087 LOG_ALWAYS_FATAL_IF(self->graphics_api != DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001088 std::lock_guard<std::mutex> autolock(self->lock_);
1089
1090 va_list args;
1091 va_start(args, operation);
1092
1093 // TODO(eieio): The following operations are not used at this time. They are
1094 // included here to help document which operations may be useful and what
1095 // parameters they take.
1096 switch (operation) {
1097 case NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS: {
1098 int w = va_arg(args, int);
1099 int h = va_arg(args, int);
1100 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_BUFFERS_DIMENSIONS: w=%d h=%d", w, h);
1101 return android::NO_ERROR;
1102 }
1103
1104 case NATIVE_WINDOW_SET_BUFFERS_FORMAT: {
1105 int format = va_arg(args, int);
1106 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_BUFFERS_FORMAT: format=%d", format);
1107 return android::NO_ERROR;
1108 }
1109
1110 case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM: {
1111 int transform = va_arg(args, int);
1112 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_BUFFERS_TRANSFORM: transform=%d",
1113 transform);
1114 return android::NO_ERROR;
1115 }
1116
1117 case NATIVE_WINDOW_SET_USAGE: {
1118 int usage = va_arg(args, int);
1119 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_USAGE: usage=%d", usage);
1120 return android::NO_ERROR;
1121 }
1122
1123 case NATIVE_WINDOW_CONNECT:
1124 case NATIVE_WINDOW_DISCONNECT:
1125 case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
1126 case NATIVE_WINDOW_API_CONNECT:
1127 case NATIVE_WINDOW_API_DISCONNECT:
1128 // TODO(eieio): we should implement these
1129 return android::NO_ERROR;
1130
1131 case NATIVE_WINDOW_SET_BUFFER_COUNT: {
1132 int buffer_count = va_arg(args, int);
1133 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_BUFFER_COUNT: bufferCount=%d",
1134 buffer_count);
1135 return android::NO_ERROR;
1136 }
1137 case NATIVE_WINDOW_SET_BUFFERS_DATASPACE: {
1138 android_dataspace_t data_space =
1139 static_cast<android_dataspace_t>(va_arg(args, int));
1140 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_BUFFERS_DATASPACE: dataSpace=%d",
1141 data_space);
1142 return android::NO_ERROR;
1143 }
1144 case NATIVE_WINDOW_SET_SCALING_MODE: {
1145 int mode = va_arg(args, int);
1146 ALOGD_IF(TRACE, "NATIVE_WINDOW_SET_SCALING_MODE: mode=%d", mode);
1147 return android::NO_ERROR;
1148 }
1149
1150 case NATIVE_WINDOW_LOCK:
1151 case NATIVE_WINDOW_UNLOCK_AND_POST:
1152 case NATIVE_WINDOW_SET_CROP:
1153 case NATIVE_WINDOW_SET_BUFFERS_TIMESTAMP:
1154 return android::INVALID_OPERATION;
1155 }
1156
1157 return android::NAME_NOT_FOUND;
1158}
1159
1160int DvrGraphicsContext::DequeueBuffer_DEPRECATED(ANativeWindow* window,
1161 ANativeWindowBuffer** buffer) {
1162 int fence_fd = -1;
1163 int ret = DequeueBuffer(window, buffer, &fence_fd);
1164
1165 // wait for fence
1166 if (ret == android::NO_ERROR && fence_fd != -1)
1167 close(fence_fd);
1168
1169 return ret;
1170}
1171
1172int DvrGraphicsContext::CancelBuffer_DEPRECATED(ANativeWindow* window,
1173 ANativeWindowBuffer* buffer) {
1174 return CancelBuffer(window, buffer, -1);
1175}
1176
1177int DvrGraphicsContext::QueueBuffer_DEPRECATED(ANativeWindow* window,
1178 ANativeWindowBuffer* buffer) {
1179 return QueueBuffer(window, buffer, -1);
1180}
1181
1182int DvrGraphicsContext::LockBuffer_DEPRECATED(ANativeWindow* /*window*/,
1183 ANativeWindowBuffer* /*buffer*/) {
1184 return android::NO_ERROR;
1185}
1186// End ANativeWindow implementation
1187
1188int dvrSetEdsPose(DvrGraphicsContext* graphics_context,
1189 float32x4_t render_pose_orientation,
1190 float32x4_t render_pose_translation) {
1191 ATRACE_NAME("dvrSetEdsPose");
1192 if (!graphics_context->current_buffer) {
1193 ALOGE("dvrBeginRenderFrame must be called before dvrSetEdsPose");
1194 return -EPERM;
1195 }
1196
1197 // When late-latching is enabled, the pose buffer is written by the GPU, so
1198 // we don't touch it here.
1199 float32x4_t is_late_latch = DVR_POSE_LATE_LATCH;
1200 if (render_pose_orientation[0] != is_late_latch[0]) {
1201 volatile android::dvr::DisplaySurfaceMetadata* data =
1202 graphics_context->surface_metadata;
1203 uint32_t buffer_index =
1204 graphics_context->current_buffer->surface_buffer_index();
1205 ALOGE_IF(TRACE, "write pose index %d %f %f", buffer_index,
1206 render_pose_orientation[0], render_pose_orientation[1]);
1207 data->orientation[buffer_index] = render_pose_orientation;
1208 data->translation[buffer_index] = render_pose_translation;
1209 }
1210
1211 return 0;
1212}
1213
1214int dvrBeginRenderFrameEds(DvrGraphicsContext* graphics_context,
1215 float32x4_t render_pose_orientation,
1216 float32x4_t render_pose_translation) {
1217 ATRACE_NAME("dvrBeginRenderFrameEds");
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001218 LOG_ALWAYS_FATAL_IF(graphics_context->graphics_api != DVR_GRAPHICS_API_GLES);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001219 CHECK_GL();
1220 // Grab a buffer from the queue and set its pose.
1221 if (!graphics_context->current_buffer) {
1222 graphics_context->current_buffer =
1223 graphics_context->buffer_queue->Dequeue();
1224 }
1225
1226 int ret = dvrSetEdsPose(graphics_context, render_pose_orientation,
1227 render_pose_translation);
1228 if (ret < 0)
1229 return ret;
1230
1231 ATRACE_ASYNC_BEGIN("BufferDraw",
1232 graphics_context->current_buffer->buffer()->id());
1233
1234 {
1235 ATRACE_NAME("glEGLImageTargetTexture2DOES");
1236 // Bind the texture to the latest buffer in the queue.
1237 for (int i = 0; i < graphics_context->gl.texture_count; ++i) {
1238 glBindTexture(graphics_context->gl.texture_target_type,
1239 graphics_context->gl.texture_id[i]);
1240 glEGLImageTargetTexture2DOES(
1241 graphics_context->gl.texture_target_type,
1242 graphics_context->current_buffer->image_khr(i));
1243 }
1244 glBindTexture(graphics_context->gl.texture_target_type, 0);
1245 }
1246 CHECK_GL();
1247 return 0;
1248}
1249int dvrBeginRenderFrameEdsVk(DvrGraphicsContext* graphics_context,
1250 float32x4_t render_pose_orientation,
1251 float32x4_t render_pose_translation,
1252 VkSemaphore acquire_semaphore,
1253 VkFence acquire_fence,
1254 uint32_t* swapchain_image_index,
1255 VkImageView* swapchain_image_view) {
1256 ATRACE_NAME("dvrBeginRenderFrameEds");
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001257 LOG_ALWAYS_FATAL_IF(graphics_context->graphics_api !=
1258 DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001259
1260 // Acquire a swapchain image. This calls Dequeue() internally.
1261 VkResult result = vkAcquireNextImageKHR(
1262 graphics_context->vk.device, graphics_context->vk.swapchain, UINT64_MAX,
1263 acquire_semaphore, acquire_fence, swapchain_image_index);
1264 if (result != VK_SUCCESS)
1265 return -EINVAL;
1266
1267 // Set the pose pose.
1268 int ret = dvrSetEdsPose(graphics_context, render_pose_orientation,
1269 render_pose_translation);
1270 if (ret < 0)
1271 return ret;
1272 *swapchain_image_view =
1273 graphics_context->vk.swapchain_image_views[*swapchain_image_index];
1274 return 0;
1275}
1276
1277int dvrBeginRenderFrame(DvrGraphicsContext* graphics_context) {
1278 return dvrBeginRenderFrameEds(graphics_context, DVR_POSE_NO_EDS,
1279 DVR_POSE_NO_EDS);
1280}
1281int dvrBeginRenderFrameVk(DvrGraphicsContext* graphics_context,
1282 VkSemaphore acquire_semaphore, VkFence acquire_fence,
1283 uint32_t* swapchain_image_index,
1284 VkImageView* swapchain_image_view) {
1285 return dvrBeginRenderFrameEdsVk(
1286 graphics_context, DVR_POSE_NO_EDS, DVR_POSE_NO_EDS, acquire_semaphore,
1287 acquire_fence, swapchain_image_index, swapchain_image_view);
1288}
1289
1290int dvrBeginRenderFrameLateLatch(DvrGraphicsContext* graphics_context,
1291 uint32_t /*flags*/,
1292 uint32_t target_vsync_count, int num_views,
1293 const float** projection_matrices,
1294 const float** eye_from_head_matrices,
1295 const float** pose_offset_matrices,
1296 uint32_t* out_late_latch_buffer_id) {
1297 if (!graphics_context->late_latch) {
1298 return -EPERM;
1299 }
1300 if (num_views > DVR_GRAPHICS_SURFACE_MAX_VIEWS) {
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001301 ALOGE("dvrBeginRenderFrameLateLatch called with too many views.");
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001302 return -EINVAL;
1303 }
1304 dvrBeginRenderFrameEds(graphics_context, DVR_POSE_LATE_LATCH,
1305 DVR_POSE_LATE_LATCH);
1306 auto& ll = graphics_context->late_latch;
1307 // TODO(jbates) Need to change this shader so that it dumps the single
1308 // captured pose for both eyes into the display surface metadata buffer at
1309 // the right index.
1310 android::dvr::LateLatchInput input;
1311 memset(&input, 0, sizeof(input));
1312 for (int i = 0; i < num_views; ++i) {
1313 memcpy(input.proj_mat + i, *(projection_matrices + i), 16 * sizeof(float));
1314 memcpy(input.eye_from_head_mat + i, *(eye_from_head_matrices + i),
1315 16 * sizeof(float));
1316 memcpy(input.pose_offset + i, *(pose_offset_matrices + i),
1317 16 * sizeof(float));
1318 }
1319 input.pose_index =
1320 target_vsync_count & android::dvr::kPoseAsyncBufferIndexMask;
1321 input.render_pose_index =
1322 graphics_context->current_buffer->surface_buffer_index();
1323 ll->AddLateLatch(input);
1324 *out_late_latch_buffer_id = ll->output_buffer_id();
1325 return 0;
1326}
1327
1328extern "C" int dvrGraphicsWaitNextFrame(
1329 DvrGraphicsContext* graphics_context, int64_t start_delay_ns,
1330 DvrFrameSchedule* out_next_frame_schedule) {
1331 start_delay_ns = std::max(start_delay_ns, static_cast<int64_t>(0));
1332
1333 // We only do one-shot timers:
1334 int64_t wake_time_ns = 0;
1335
1336 uint32_t current_frame_vsync;
1337 int64_t current_frame_scheduled_finish_ns;
1338 int64_t vsync_period_ns;
1339
1340 int fetch_schedule_result = graphics_context->vsync_client->GetSchedInfo(
1341 &vsync_period_ns, &current_frame_scheduled_finish_ns,
1342 &current_frame_vsync);
1343 if (fetch_schedule_result == 0) {
1344 wake_time_ns = current_frame_scheduled_finish_ns + start_delay_ns;
1345 // If the last wakeup time is still in the future, use it instead to avoid
1346 // major schedule jumps when applications call WaitNextFrame with
1347 // aggressive offsets.
1348 int64_t now = android::dvr::GetSystemClockNs();
1349 if (android::dvr::TimestampGT(wake_time_ns - vsync_period_ns, now)) {
1350 wake_time_ns -= vsync_period_ns;
1351 --current_frame_vsync;
1352 }
1353 // If the next wakeup time is in the past, add a vsync period to keep the
1354 // application on schedule.
1355 if (android::dvr::TimestampLT(wake_time_ns, now)) {
1356 wake_time_ns += vsync_period_ns;
1357 ++current_frame_vsync;
1358 }
1359 } else {
1360 ALOGE("Error getting frame schedule because: %s",
1361 strerror(-fetch_schedule_result));
1362 // Sleep for a vsync period to avoid cascading failure.
1363 wake_time_ns = android::dvr::GetSystemClockNs() +
1364 graphics_context->display_metrics.vsync_period_ns;
1365 }
1366
1367 // Adjust nsec to [0..999,999,999].
1368 struct itimerspec wake_time;
1369 wake_time.it_interval.tv_sec = 0;
1370 wake_time.it_interval.tv_nsec = 0;
1371 wake_time.it_value = android::dvr::NsToTimespec(wake_time_ns);
1372 bool sleep_result =
1373 timerfd_settime(graphics_context->timerfd.Get(), TFD_TIMER_ABSTIME,
1374 &wake_time, nullptr) == 0;
1375 if (sleep_result) {
1376 ATRACE_NAME("sleep");
1377 uint64_t expirations = 0;
1378 sleep_result = read(graphics_context->timerfd.Get(), &expirations,
1379 sizeof(uint64_t)) == sizeof(uint64_t);
1380 if (!sleep_result) {
1381 ALOGE("Error: timerfd read failed");
1382 }
1383 } else {
1384 ALOGE("Error: timerfd_settime failed because: %s", strerror(errno));
1385 }
1386
1387 auto& frame_history = graphics_context->frame_history;
1388 frame_history.CheckForFinishedFrames();
1389 if (fetch_schedule_result == 0) {
1390 uint32_t next_frame_vsync =
1391 current_frame_vsync +
1392 frame_history.PredictNextFrameVsyncInterval(vsync_period_ns);
1393 int64_t next_frame_scheduled_finish =
1394 (wake_time_ns - start_delay_ns) + vsync_period_ns;
1395 frame_history.OnFrameStart(next_frame_vsync, next_frame_scheduled_finish);
1396 if (out_next_frame_schedule) {
1397 out_next_frame_schedule->vsync_count = next_frame_vsync;
1398 out_next_frame_schedule->scheduled_frame_finish_ns =
1399 next_frame_scheduled_finish;
1400 }
1401 } else {
1402 frame_history.OnFrameStart(UINT32_MAX, -1);
1403 }
1404
1405 return (fetch_schedule_result == 0 && sleep_result) ? 0 : -1;
1406}
1407
1408extern "C" void dvrGraphicsPostEarly(DvrGraphicsContext* graphics_context) {
1409 ATRACE_NAME("dvrGraphicsPostEarly");
1410 ALOGI_IF(TRACE, "dvrGraphicsPostEarly");
1411
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001412 LOG_ALWAYS_FATAL_IF(graphics_context->graphics_api != DVR_GRAPHICS_API_GLES);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001413
1414 // Note that this function can be called before or after
1415 // dvrBeginRenderFrame.
1416 if (!graphics_context->buffer_already_posted) {
1417 graphics_context->buffer_already_posted = true;
1418
1419 if (!graphics_context->current_buffer) {
1420 graphics_context->current_buffer =
1421 graphics_context->buffer_queue->Dequeue();
1422 }
1423
1424 auto buffer = graphics_context->current_buffer->buffer().get();
1425 ATRACE_ASYNC_BEGIN("BufferPost", buffer->id());
1426 int result = buffer->Post<uint64_t>(LocalHandle(), 0);
1427 if (result < 0)
1428 ALOGE("Buffer post failed: %d (%s)", result, strerror(-result));
1429 }
1430}
1431
1432int dvrPresent(DvrGraphicsContext* graphics_context) {
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001433 LOG_ALWAYS_FATAL_IF(graphics_context->graphics_api != DVR_GRAPHICS_API_GLES);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001434
1435 std::array<char, 128> buf;
1436 snprintf(buf.data(), buf.size(), "dvrPresent|vsync=%d|",
1437 graphics_context->frame_history.GetCurrentFrameVsync());
1438 ATRACE_NAME(buf.data());
1439
1440 if (!graphics_context->current_buffer) {
1441 ALOGE("Error: dvrPresent called without dvrBeginRenderFrame");
1442 return -EPERM;
1443 }
1444
1445 LocalHandle fence_fd =
1446 android::dvr::CreateGLSyncAndFlush(graphics_context->gl.egl_display);
1447
1448 ALOGI_IF(TRACE, "PostBuffer: buffer_id=%d, fence_fd=%d",
1449 graphics_context->current_buffer->buffer()->id(), fence_fd.Get());
1450 ALOGW_IF(!graphics_context->display_surface->visible(),
1451 "PostBuffer: Posting buffer on invisible surface!!!");
1452
1453 auto buffer = graphics_context->current_buffer->buffer().get();
1454 ATRACE_ASYNC_END("BufferDraw", buffer->id());
1455 if (!graphics_context->buffer_already_posted) {
1456 ATRACE_ASYNC_BEGIN("BufferPost", buffer->id());
1457 int result = buffer->Post<uint64_t>(fence_fd, 0);
1458 if (result < 0)
1459 ALOGE("Buffer post failed: %d (%s)", result, strerror(-result));
1460 }
1461
1462 graphics_context->frame_history.OnFrameSubmit(std::move(fence_fd));
1463 graphics_context->buffer_already_posted = false;
1464 graphics_context->current_buffer = nullptr;
1465 return 0;
1466}
1467
1468int dvrPresentVk(DvrGraphicsContext* graphics_context,
1469 VkSemaphore submit_semaphore, uint32_t swapchain_image_index) {
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001470 LOG_ALWAYS_FATAL_IF(graphics_context->graphics_api !=
1471 DVR_GRAPHICS_API_VULKAN);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001472
1473 std::array<char, 128> buf;
1474 snprintf(buf.data(), buf.size(), "dvrPresent|vsync=%d|",
1475 graphics_context->frame_history.GetCurrentFrameVsync());
1476 ATRACE_NAME(buf.data());
1477
1478 if (!graphics_context->current_buffer) {
1479 ALOGE("Error: dvrPresentVk called without dvrBeginRenderFrameVk");
1480 return -EPERM;
1481 }
1482
1483 // Present the specified image. Internally, this gets a fence from the
1484 // Vulkan driver and passes it to DvrGraphicsContext::Post(),
1485 // which in turn passes it to buffer->Post() and adds it to frame_history.
1486 VkPresentInfoKHR present_info = {};
1487 present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
1488 present_info.swapchainCount = 1;
1489 present_info.pSwapchains = &graphics_context->vk.swapchain;
1490 present_info.pImageIndices = &swapchain_image_index;
1491 present_info.waitSemaphoreCount =
1492 (submit_semaphore != VK_NULL_HANDLE) ? 1 : 0;
1493 present_info.pWaitSemaphores = &submit_semaphore;
1494 VkResult result =
1495 vkQueuePresentKHR(graphics_context->vk.present_queue, &present_info);
1496 if (result != VK_SUCCESS) {
1497 return -EINVAL;
1498 }
1499
1500 return 0;
1501}
1502
1503extern "C" int dvrGetFrameScheduleResults(DvrGraphicsContext* context,
1504 DvrFrameScheduleResult* results,
1505 int in_result_count) {
1506 if (!context || !results)
1507 return -EINVAL;
1508
1509 return context->frame_history.GetPreviousFrameResults(results,
1510 in_result_count);
1511}
1512
1513extern "C" void dvrGraphicsSurfaceSetVisible(
1514 DvrGraphicsContext* graphics_context, int visible) {
1515 graphics_context->display_surface->SetVisible(visible);
1516}
1517
1518extern "C" int dvrGraphicsSurfaceGetVisible(
1519 DvrGraphicsContext* graphics_context) {
1520 return graphics_context->display_surface->visible() ? 1 : 0;
1521}
1522
1523extern "C" void dvrGraphicsSurfaceSetZOrder(
1524 DvrGraphicsContext* graphics_context, int z_order) {
1525 graphics_context->display_surface->SetZOrder(z_order);
1526}
1527
1528extern "C" int dvrGraphicsSurfaceGetZOrder(
1529 DvrGraphicsContext* graphics_context) {
1530 return graphics_context->display_surface->z_order();
1531}
1532
1533extern "C" DvrVideoMeshSurface* dvrGraphicsVideoMeshSurfaceCreate(
1534 DvrGraphicsContext* graphics_context) {
1535 auto display_surface = graphics_context->display_surface;
1536 // A DisplaySurface must be created prior to the creation of a
1537 // VideoMeshSurface.
Alex Vakulenko4fe60582017-02-02 11:35:59 -08001538 LOG_ALWAYS_FATAL_IF(display_surface == nullptr);
Alex Vakulenkoe4eec202017-01-27 14:41:04 -08001539
1540 LocalChannelHandle surface_handle = display_surface->CreateVideoMeshSurface();
1541 if (!surface_handle.valid()) {
1542 return nullptr;
1543 }
1544
1545 std::unique_ptr<DvrVideoMeshSurface> surface(new DvrVideoMeshSurface);
1546 surface->client =
1547 android::dvr::VideoMeshSurfaceClient::Import(std::move(surface_handle));
1548
1549 // TODO(jwcai) The next line is not needed...
1550 auto producer_queue = surface->client->GetProducerQueue();
1551 return surface.release();
1552}
1553
1554extern "C" void dvrGraphicsVideoMeshSurfaceDestroy(
1555 DvrVideoMeshSurface* surface) {
1556 delete surface;
1557}
1558
1559extern "C" void dvrGraphicsVideoMeshSurfacePresent(
1560 DvrGraphicsContext* graphics_context, DvrVideoMeshSurface* surface,
1561 const int eye, const float* transform) {
1562 volatile android::dvr::VideoMeshSurfaceMetadata* metadata =
1563 surface->client->GetMetadataBufferPtr();
1564
1565 const uint32_t graphics_buffer_index =
1566 graphics_context->current_buffer->surface_buffer_index();
1567
1568 for (int i = 0; i < 4; ++i) {
1569 metadata->transform[graphics_buffer_index][eye].val[i] = {
1570 transform[i + 0], transform[i + 4], transform[i + 8], transform[i + 12],
1571 };
1572 }
1573}