Debian Codegraph @

src/wayland-eglsurface.c

raw
1 /*
2 * Copyright (c) 2014-2024, NVIDIA CORPORATION. All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 */
22
23 #include "wayland-eglsurface-internal.h"
24 #include "wayland-eglstream-client-protocol.h"
25 #include "wayland-eglstream-controller-client-protocol.h"
26 #include "linux-dmabuf-unstable-v1-client-protocol.h"
27 #include "linux-drm-syncobj-v1-client-protocol.h"
28 #include "wayland-eglstream-server.h"
29 #include "wayland-thread.h"
30 #include "wayland-eglutils.h"
31 #include "wayland-egl-ext.h"
32 #include <wayland-egl-backend.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <pthread.h>
37 #include <assert.h>
38 #include <sys/socket.h>
39 #include <sys/types.h>
40 #include <netinet/in.h>
41 #include <fcntl.h>
42 #include <poll.h>
43 #include <errno.h>
44 #include <drm_fourcc.h>
45 #include <sys/stat.h>
46 #include <xf86drm.h>
47 #include <stdio.h>
48
49 #define WL_EGL_WINDOW_DESTROY_CALLBACK_SINCE 3
50 #define MAX_IMAGES 4 /* The swapchain image count */
51
52 enum BufferReleaseThreadEvents {
53 BUFFER_RELEASE_THREAD_EVENT_TERMINATE,
54 };
55
56 enum BufferReleasePipeEndpoints {
57 BUFFER_RELEASE_PIPE_READ = 0,
58 BUFFER_RELEASE_PIPE_WRITE = 1
59 };
60
61 static WlEglStreamImage *
62 pop_acquired_image(WlEglSurface *surface);
63
64 static void
65 remove_surface_image(WlEglDisplay *display,
66 WlEglSurface *surface,
67 EGLImageKHR eglImage);
68
69 static EGLBoolean
70 validateSurfaceAttrib(EGLAttrib attrib,
71 EGLAttrib value);
72
73 static EGLint
74 assignWlEglSurfaceAttribs(WlEglSurface *surface,
75 const EGLAttrib *attribs);
76
77 EGLBoolean wlEglIsWlEglSurfaceForDisplay(WlEglDisplay *display, WlEglSurface *surface)
78 {
79 WlEglSurface *surf;
80
81 wl_list_for_each(surf, &display->wlEglSurfaceList, link) {
82 if (surf == surface) {
83 return EGL_TRUE;
84 }
85 }
86
87 return EGL_FALSE;
88 }
89
90 EGLBoolean wlEglIsWaylandWindowValid(struct wl_egl_window *window)
91 {
92 struct wl_surface *surface = NULL;
93
94 if (!window || !wlEglMemoryIsReadable(window, sizeof (*window))) {
95 return EGL_FALSE;
96 }
97
98 surface = (struct wl_surface *)window->version;
99 if (!wlEglMemoryIsReadable(surface, sizeof (void *))) {
100 surface = window->surface;
101 if (!wlEglMemoryIsReadable(surface, sizeof (void *))) {
102 return EGL_FALSE;
103 }
104 }
105 return wlEglCheckInterfaceType((struct wl_object *)surface,
106 "wl_surface");
107 }
108
109 static void
110 wayland_throttleCallback(void *data,
111 struct wl_callback *callback,
112 uint32_t time)
113 {
114 WlEglSurface *surface = (WlEglSurface *)data;
115
116 (void) time;
117
118 if (surface->throttleCallback != NULL) {
119
120 wl_callback_destroy(callback);
121 surface->throttleCallback = NULL;
122 }
123 }
124
125 static const struct wl_callback_listener throttle_listener = {
126 wayland_throttleCallback
127 };
128
129 void wlEglCreateFrameSync(WlEglSurface *surface)
130 {
131 struct wl_surface *wrapper = NULL;
132
133 assert(surface->wlEventQueue);
134 if (surface->swapInterval > 0) {
135 wrapper = wl_proxy_create_wrapper(surface->wlSurface);
136 wl_proxy_set_queue((struct wl_proxy *)wrapper, surface->wlEventQueue);
137 surface->throttleCallback = wl_surface_frame(wrapper);
138 wl_proxy_wrapper_destroy(wrapper); /* Done with wrapper */
139 if (wl_callback_add_listener(surface->throttleCallback,
140 &throttle_listener, surface) == -1) {
141 return;
142 }
143 }
144 }
145
146 EGLint wlEglWaitFrameSync(WlEglSurface *surface)
147 {
148
149 WlEglDisplay *display = surface->wlEglDpy;
150 struct wl_event_queue *queue = surface->wlEventQueue;
151 int ret = 0;
152
153 assert(queue || surface->throttleCallback == NULL);
154 while (ret != -1 && surface->throttleCallback != NULL) {
155 ret = wl_display_dispatch_queue(display->nativeDpy, queue);
156 }
157
158 return EGL_SUCCESS;
159 }
160
161 static bool
162 syncobj_import_fd_to_current_point(WlEglDisplay *display, WlEglSurface *surface,
163 int syncFd)
164 {
165 bool ret = false;
166 uint32_t tmpSyncobj;
167
168 /* Import our syncfd at a new release point */
169 if (drmSyncobjCreate(display->drmFd, 0, &tmpSyncobj) != 0) {
170 return false;
171 }
172
173 if (drmSyncobjImportSyncFile(display->drmFd, tmpSyncobj, syncFd) != 0) {
174 goto end;
175 }
176
177 if (drmSyncobjTransfer(display->drmFd, surface->drmSyncobjHandle,
178 surface->syncPoint, tmpSyncobj, 0, 0) != 0) {
179 goto end;
180 }
181
182 ret = true;
183
184 end:
185 drmSyncobjDestroy(display->drmFd, tmpSyncobj);
186
187 return ret;
188 }
189
190 static bool
191 send_explicit_sync_points (WlEglDisplay *display, WlEglSurface *surface,
192 WlEglStreamImage *image)
193 {
194 WlEglPlatformData *data = display->data;
195 EGLDisplay dpy = display->devDpy->eglDisplay;
196 int syncFd, err;
197 uint64_t acquireSyncPoint;
198
199 /* Ignore this unless we are using Explicit Sync */
200 if (!surface->wlSyncobjSurf) {
201 return true;
202 }
203
204 /* --------------- Get acquire sync fd -------------- */
205 syncFd = data->egl.dupNativeFenceFD(dpy, image->acquireSync);
206 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
207 return false;
208 }
209
210 /* Clean up our acquire sync object now that we are done with it */
211 data->egl.destroySync(dpy, image->acquireSync);
212 image->acquireSync = EGL_NO_SYNC_KHR;
213
214 err = syncobj_import_fd_to_current_point(display, surface, syncFd);
215 close(syncFd);
216 if (!err) {
217 return false;
218 }
219 acquireSyncPoint = surface->syncPoint++;
220
221 /* --------------- Get release EGLSyncKHR -------------- */
222
223 /* Increment to a new sync point here in the image. */
224 image->releasePoint++;
225 image->releasePending = true;
226
227 /* --------------- Send sync points -------------- */
228
229 /* Now notify the compositor of our next acquire point */
230 wp_linux_drm_syncobj_surface_v1_set_acquire_point(surface->wlSyncobjSurf,
231 surface->wlAcquireTimeline,
232 acquireSyncPoint >> 32,
233 acquireSyncPoint & 0xffffffff);
234
235 /* Now notify the compositor of our next release point */
236 wp_linux_drm_syncobj_surface_v1_set_release_point(surface->wlSyncobjSurf,
237 image->wlReleaseTimeline,
238 image->releasePoint >> 32,
239 image->releasePoint & 0xffffffff);
240
241 return true;
242 }
243
244 EGLBoolean
245 wlEglSendDamageEvent(WlEglSurface *surface,
246 struct wl_event_queue *queue,
247 EGLint *rects,
248 EGLint n_rects)
249 {
250 struct wl_display *wlDpy = surface->wlEglDpy->nativeDpy;
251 EGLint i;
252
253 if (surface->ctx.wlStreamResource) {
254 /* Attach same buffer to indicate new content for the surface is
255 * made available by the client */
256 wl_surface_attach(surface->wlSurface,
257 surface->ctx.wlStreamResource,
258 surface->dx,
259 surface->dy);
260 } else {
261 WlEglStreamImage *image;
262
263 if (wlEglHandleImageStreamEvents(surface) != EGL_SUCCESS) {
264 return EGL_FALSE;
265 }
266
267 image = pop_acquired_image(surface);
268 if (!image) {
269 return EGL_FALSE;
270 }
271
272 surface->ctx.currentBuffer = image->buffer;
273 image->attached = EGL_TRUE;
274
275 /*
276 * Send our explicit sync acquire and release points. This needs to be done
277 * as part of the surface attach as it is a protocol error to specify these
278 * points without attaching a buffer in the same commit.
279 *
280 * Perform this before wl_surface_attach in case there is an error importing
281 * the syncfd at the current timeline point. If this errors out after the
282 * attach has happened then we are stuck with a protocol error from not
283 * specifying the timeline sync points.
284 */
285 if (!send_explicit_sync_points(surface->wlEglDpy, surface, image)) {
286 return EGL_FALSE;
287 }
288
289 wl_surface_attach(surface->wlSurface,
290 surface->ctx.currentBuffer,
291 surface->dx,
292 surface->dy);
293 }
294
295 if (n_rects > 0 &&
296 (wl_proxy_get_version((struct wl_proxy *)surface->wlSurface) >=
297 WL_SURFACE_DAMAGE_BUFFER_SINCE_VERSION)) {
298 for (i = 0; i < n_rects; i++) {
299 const EGLint *rect = &rects[i * 4];
300 // Coordinate systems are flipped between eglSwapBuffersWithDamage
301 // and wl_surface_damage_buffer, so invert Y values.
302 int inv_y = surface->height - (rect[1] + rect[3]);
303 wl_surface_damage_buffer(surface->wlSurface, rect[0], inv_y, rect[2], rect[3]);
304 }
305 } else {
306 wl_surface_damage(surface->wlSurface, 0, 0, INT32_MAX, INT32_MAX);
307 }
308
309
310 wl_surface_commit(surface->wlSurface);
311 surface->ctx.isAttached = EGL_TRUE;
312
313 return (wl_display_roundtrip_queue(wlDpy,
314 queue) >= 0) ? EGL_TRUE : EGL_FALSE;
315 }
316
317 static void*
318 damage_thread(void *args)
319 {
320 WlEglSurface *surface = (WlEglSurface*)args;
321 WlEglDisplay *display = surface->wlEglDpy;
322 WlEglPlatformData *data = display->data;
323 struct wl_event_queue *queue = wl_display_create_queue(
324 display->nativeDpy);
325 int ok = (queue != NULL);
326 EGLint state;
327
328 while (ok) {
329 // Unsignal sync and check latest frame and stream state
330 // Done if any functions fail or stream has disconnected.
331 ok = data->egl.signalSync(display->devDpy->eglDisplay,
332 surface->ctx.damageThreadSync,
333 EGL_UNSIGNALED_KHR)
334 && data->egl.queryStreamu64(display->devDpy->eglDisplay,
335 surface->ctx.eglStream,
336 EGL_PRODUCER_FRAME_KHR,
337 &surface->ctx.framesFinished)
338 && data->egl.queryStream(display->devDpy->eglDisplay,
339 surface->ctx.eglStream,
340 EGL_STREAM_STATE_KHR,
341 &state)
342 && (state != EGL_STREAM_STATE_DISCONNECTED_KHR);
343
344 // If flush has been requested, trigger shutdown once
345 // last produced frame has been processed.
346 if (surface->ctx.damageThreadFlush) {
347 if (surface->ctx.framesProcessed ==
348 surface->ctx.framesProduced) {
349 surface->ctx.damageThreadShutdown = 1;
350 }
351 }
352
353 // If shutdown has been requested, we're done
354 if (surface->ctx.damageThreadShutdown) {
355 ok = 0;
356 }
357
358 // We only expect a valid wlEglWin to be set when using
359 // a surface created with EGL_KHR_platform_wayland.
360 if(!wlEglIsWaylandDisplay(display->nativeDpy) ||
361 (surface->isSurfaceProducer && !wlEglIsWaylandWindowValid(surface->wlEglWin))) {
362 ok = 0;
363 }
364 // If not done, keep handling frames
365 if (ok) {
366
367 pthread_mutex_lock(&surface->mutexFrameSync);
368
369 // If there's an unprocessed frame ready, send damage event
370 if (surface->ctx.framesFinished !=
371 surface->ctx.framesProcessed) {
372 if (display->devDpy->exts.stream_flush) {
373 data->egl.streamFlush(display->devDpy->eglDisplay,
374 surface->ctx.eglStream);
375 }
376
377 wlEglCreateFrameSync(surface);
378
379 ok = wlEglSendDamageEvent(surface, queue, NULL, 0);
380 surface->ctx.framesProcessed++;
381
382 pthread_cond_signal(&surface->condFrameSync);
383
384 pthread_mutex_unlock(&surface->mutexFrameSync);
385 }
386
387 // Otherwise, wait for sync to trigger
388 else {
389 pthread_mutex_unlock(&surface->mutexFrameSync);
390
391 ok = (EGL_CONDITION_SATISFIED_KHR ==
392 data->egl.clientWaitSync(display->devDpy->eglDisplay,
393 surface->ctx.damageThreadSync,
394 0, EGL_FOREVER_KHR));
395 }
396 }
397 }
398
399 wl_event_queue_destroy(queue);
400 data->egl.releaseThread();
401
402 return NULL;
403 }
404
405 static EGLint setup_wl_eglstream_damage_thread(WlEglSurface *surface)
406 {
407 WlEglDisplay *display = surface->wlEglDpy;
408 WlEglPlatformData *data = display->data;
409 int ret;
410
411 surface->ctx.damageThreadFlush = 0;
412 surface->ctx.damageThreadShutdown = 0;
413 surface->ctx.framesProduced = 0;
414 surface->ctx.framesFinished = 0;
415 surface->ctx.framesProcessed = 0;
416 surface->ctx.damageThreadSync =
417 data->egl.createStreamSync(display->devDpy->eglDisplay,
418 surface->ctx.eglStream,
419 EGL_SYNC_NEW_FRAME_NV,
420 NULL);
421 if (surface->ctx.damageThreadSync == EGL_NO_SYNC_KHR) {
422 return data->egl.getError();
423 }
424
425 ret = pthread_create(&surface->ctx.damageThreadId, NULL,
426 damage_thread, (void*)surface);
427 if (ret != 0) {
428 return EGL_BAD_ALLOC;
429 }
430
431 return EGL_SUCCESS;
432 }
433
434 static void
435 finish_wl_eglstream_damage_thread(WlEglSurface *surface,
436 WlEglSurfaceCtx *ctx,
437 int immediate)
438 {
439 WlEglDisplay *display = surface->wlEglDpy;
440 WlEglPlatformData *data = display->data;
441
442 if (ctx->damageThreadSync != EGL_NO_SYNC_KHR) {
443 if (immediate) {
444 ctx->damageThreadShutdown = 1;
445 } else {
446 ctx->damageThreadFlush = 1;
447 }
448 data->egl.signalSync(display->devDpy->eglDisplay,
449 ctx->damageThreadSync,
450 EGL_SIGNALED_KHR);
451 if (ctx->damageThreadId != (pthread_t)0) {
452 pthread_join(ctx->damageThreadId, NULL);
453 ctx->damageThreadId = (pthread_t)0;
454 }
455 data->egl.destroySync(display->devDpy->eglDisplay,
456 ctx->damageThreadSync);
457 ctx->damageThreadSync = EGL_NO_SYNC_KHR;
458 }
459 }
460
461 static void*
462 buffer_release_thread(void *args)
463 {
464 WlEglSurface *surface = (WlEglSurface*)args;
465 WlEglDisplay *display = surface->wlEglDpy;
466 struct wl_display *wlDpy = display->nativeDpy;
467 struct wl_event_queue *queue = surface->wlBufferEventQueue;
468 struct pollfd pfds[2];
469 const int fd = wl_display_get_fd(wlDpy);
470 int res;
471 uint8_t cmd;
472
473 while (1) {
474 /* First clear out any previously-read events on the queue */
475 wl_display_dispatch_queue_pending(wlDpy, queue);
476
477 /*
478 * Now block until more events are present on the wire, then
479 * read them. Also, watch for messages from the app thread.
480 */
481 if ((wl_display_prepare_read_queue(wlDpy, queue) < 0)) {
482 if (errno == EAGAIN) {
483 continue;
484 } else {
485 return NULL;
486 }
487 }
488
489 memset(&pfds, 0, sizeof(pfds));
490 pfds[0].fd = fd;
491 pfds[0].events = POLLIN;
492 pfds[1].fd =
493 surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_READ];
494 pfds[1].events = POLLIN;
495 res = poll(&pfds[0], sizeof(pfds) / sizeof(pfds[0]), 1000);
496
497 if (res <= 0) {
498 wl_display_cancel_read(wlDpy);
499 continue;
500 }
501
502 if (pfds[1].revents & POLLIN) {
503 if (read(pfds[1].fd, &cmd, sizeof(cmd)) != sizeof(cmd)) {
504 /* Reading an event from the app side failed. Bail. */
505 wl_display_cancel_read(wlDpy);
506 return NULL;
507 }
508
509 switch (cmd) {
510 default:
511 /*
512 * Unknown command from the app side. Treat it like a
513 * termination request.
514 *
515 * fall through.
516 */
517 case BUFFER_RELEASE_THREAD_EVENT_TERMINATE:
518 wl_display_cancel_read(wlDpy);
519 return NULL;
520 }
521 }
522
523 if (pfds[0].revents & POLLIN) {
524 if (wl_display_read_events(wlDpy) < 0) {
525 return NULL;
526 }
527 } else {
528 wl_display_cancel_read(wlDpy);
529 }
530 }
531
532 return NULL;
533 }
534
535 static EGLint setup_wl_buffer_release_thread(WlEglSurface *surface)
536 {
537 int ret;
538
539 if (pipe(surface->bufferReleaseThreadPipe)) {
540 return EGL_BAD_ALLOC;
541 }
542
543 surface->wlBufferEventQueue =
544 wl_display_create_queue(surface->wlEglDpy->nativeDpy);
545
546 ret = pthread_create(&surface->bufferReleaseThreadId, NULL,
547 buffer_release_thread, (void*)surface);
548 if (ret != 0) {
549 close(surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_WRITE]);
550 surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_WRITE] = -1;
551 close(surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_READ]);
552 surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_READ] = -1;
553 wl_event_queue_destroy(surface->wlBufferEventQueue);
554 surface->wlBufferEventQueue = NULL;
555 return EGL_BAD_ALLOC;
556 }
557
558 return EGL_SUCCESS;
559 }
560
561 static void
562 finish_wl_buffer_release_thread(WlEglSurface *surface)
563 {
564 uint8_t cmd = BUFFER_RELEASE_THREAD_EVENT_TERMINATE;
565
566 if (surface->wlBufferEventQueue) {
567 if (write(surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_WRITE],
568 &cmd, sizeof(cmd)) != sizeof(cmd)) {
569 /* The thread is not going to terminate gracefully. */
570 pthread_cancel(surface->bufferReleaseThreadId);
571 }
572 pthread_join(surface->bufferReleaseThreadId, NULL);
573 surface->bufferReleaseThreadId = (pthread_t)0;
574
575 close(surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_WRITE]);
576 surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_WRITE] = -1;
577 close(surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_READ]);
578 surface->bufferReleaseThreadPipe[BUFFER_RELEASE_PIPE_READ] = -1;
579
580 wl_event_queue_destroy(surface->wlBufferEventQueue);
581 surface->wlBufferEventQueue = NULL;
582 }
583 }
584
585 static void
586 destroy_stream_image(WlEglDisplay *display,
587 WlEglSurface *surface,
588 WlEglStreamImage *image)
589 {
590 WlEglPlatformData *data = display->data;
591 EGLDisplay dpy = display->devDpy->eglDisplay;
592
593 /* Must be called with surface->ctx.streamImagesMutex already locked */
594
595 if (surface->ctx.currentBuffer == image->buffer) {
596 surface->ctx.currentBuffer = NULL;
597 }
598
599 if (!surface->wlSyncobjSurf && image->attached) {
600 // This is used for delaying the destruction of images only when
601 // explicit-sync is not in use to prevent the buffer release thread
602 // from accessing images after they are deallocated.
603 image->destructionPending = EGL_TRUE;
604 return;
605 }
606
607 assert(image->eglImage != EGL_NO_IMAGE_KHR);
608 data->egl.destroyImage(dpy, image->eglImage);
609
610 if (image->buffer) {
611 wl_buffer_destroy(image->buffer);
612 }
613
614 if (image->wlReleaseTimeline) {
615 wp_linux_drm_syncobj_timeline_v1_destroy(image->wlReleaseTimeline);
616 drmSyncobjDestroy(display->drmFd, image->drmSyncobjHandle);
617 if (image->acquireSync != EGL_NO_SYNC_KHR) {
618 data->egl.destroySync(dpy, image->acquireSync);
619 }
620 }
621
622 wl_list_remove(&image->acquiredLink);
623 wl_list_remove(&image->link);
624
625 free(image);
626 }
627
628 static void
629 destroy_surface_context(WlEglSurface *surface, WlEglSurfaceCtx *ctx)
630 {
631 WlEglDisplay *display = surface->wlEglDpy;
632 WlEglPlatformData *data = display->data;
633 EGLDisplay dpy = display->devDpy->eglDisplay;
634 EGLSurface surf = ctx->eglSurface;
635 EGLStreamKHR stream = ctx->eglStream;
636 void *resource = ctx->wlStreamResource;
637
638 finish_wl_eglstream_damage_thread(surface, ctx, 1);
639
640 ctx->eglSurface = EGL_NO_SURFACE;
641 ctx->eglStream = EGL_NO_STREAM_KHR;
642 ctx->wlStreamResource = NULL;
643
644 if (surf != EGL_NO_SURFACE) {
645 data->egl.destroySurface(dpy, surf);
646 }
647
648 if (surface->ctx.isOffscreen) {
649 return;
650 }
651
652 if (stream != EGL_NO_STREAM_KHR) {
653 data->egl.destroyStream(dpy, stream);
654 ctx->eglStream = EGL_NO_STREAM_KHR;
655 }
656
657 if (!resource) {
658 // streamImages list is not valid when wlStreamResource is in use.
659 WlEglStreamImage *image, *next;
660
661 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
662
663 // Destroy all images. If there are attached images, this will mark
664 // them for destruction. Following buffer release event will destroy
665 // them.
666 wl_list_for_each_safe(image, next, &ctx->streamImages, link) {
667 destroy_stream_image(display, surface, image);
668 }
669
670 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
671 } else {
672 wl_buffer_destroy(resource);
673 }
674 }
675
676 static void
677 discard_surface_context(WlEglSurface *surface)
678 {
679 /* If the surface context is marked as attached, it means the compositor
680 * might still be using the resources because some content was actually
681 * displayed. In that case, defer its destruction until we make sure the
682 * compositor doesn't need it anymore (i.e. upon stream release);
683 * otherwise, we can just destroy it right away */
684 if (surface->ctx.isAttached && surface->ctx.wlStreamResource) {
685 WlEglSurfaceCtx *ctx = malloc(sizeof(WlEglSurfaceCtx));
686 if (ctx) {
687 memcpy(ctx, &surface->ctx, sizeof(*ctx));
688 wl_list_insert(&surface->oldCtxList, &ctx->link);
689 }
690 } else {
691 destroy_surface_context(surface, &surface->ctx);
692 }
693 }
694
695 static void
696 wl_buffer_release(void *data, struct wl_buffer *buffer)
697 {
698 WlEglSurface *surface = (WlEglSurface*)data;
699 WlEglSurfaceCtx *ctx;
700
701 /* Look for the surface context for the given buffer and destroy it */
702 wl_list_for_each(ctx, &surface->oldCtxList, link) {
703 if (ctx->wlStreamResource == buffer) {
704 destroy_surface_context(surface, ctx);
705 wl_list_remove(&ctx->link);
706 free(ctx);
707 break;
708 }
709 }
710 }
711
712 static struct wl_buffer_listener wl_buffer_listener = {
713 wl_buffer_release
714 };
715
716 static void *
717 create_wl_eglstream(WlEglSurface *surface,
718 int32_t handle,
719 int32_t type,
720 struct wl_array *attribs)
721 {
722 WlEglDisplay *display = surface->wlEglDpy;
723 struct wl_egl_window *window = surface->wlEglWin;
724 struct wl_eglstream_display *wrapper = NULL;
725 struct wl_buffer *buffer = NULL;
726 int32_t width;
727 int32_t height;
728
729 if (!display->wlStreamDpy) {
730 return NULL;
731 }
732
733 if (surface->isSurfaceProducer) {
734 assert(window);
735 width = window->width;
736 height = window->height;
737 } else {
738 width = surface->width;
739 height = surface->height;
740 }
741
742 wrapper = wl_proxy_create_wrapper(display->wlStreamDpy);
743 wl_proxy_set_queue((struct wl_proxy *)wrapper, surface->wlEventQueue);
744
745 buffer = wl_eglstream_display_create_stream(wrapper,
746 width,
747 height,
748 handle,
749 type,
750 attribs);
751
752 wl_proxy_wrapper_destroy(wrapper); /* Done with wrapper */
753
754 if (!buffer) {
755 return NULL;
756 }
757
758 if (wl_buffer_add_listener(buffer, &wl_buffer_listener, surface) == -1) {
759 wl_buffer_destroy(buffer);
760 return NULL;
761 }
762
763 return buffer;
764 }
765
766 static EGLint create_surface_stream_fd(WlEglSurface *surface)
767 {
768 WlEglDisplay *display = surface->wlEglDpy;
769 WlEglPlatformData *data = display->data;
770 int handle = EGL_NO_FILE_DESCRIPTOR_KHR;
771 struct wl_array wlAttribs;
772 EGLint eglAttribs[] = {
773 EGL_STREAM_FIFO_LENGTH_KHR, surface->fifoLength,
774 EGL_NONE, EGL_NONE,
775 EGL_NONE
776 };
777 EGLint err = EGL_SUCCESS;
778
779 /* We don't have any mechanism to check whether the compositor is going to
780 * use this surface for composition or not when using cross_process_fd, so
781 * just enable FIFO_SYNCHRONOUS if the extensions are supported */
782 if (display->devDpy->exts.stream_fifo_synchronous &&
783 display->devDpy->exts.stream_sync &&
784 surface->fifoLength > 0) {
785 eglAttribs[2] = EGL_STREAM_FIFO_SYNCHRONOUS_NV;
786 eglAttribs[3] = EGL_TRUE;
787 }
788
789 /* First, create the EGLStream */
790 surface->ctx.eglStream =
791 data->egl.createStream(display->devDpy->eglDisplay, eglAttribs);
792 if (surface->ctx.eglStream == EGL_NO_STREAM_KHR) {
793 err = data->egl.getError();
794 goto fail;
795 }
796
797 handle = data->egl.getStreamFileDescriptor(display->devDpy->eglDisplay,
798 surface->ctx.eglStream);
799 if (handle == EGL_NO_FILE_DESCRIPTOR_KHR) {
800 err = data->egl.getError();
801 goto fail;
802 }
803
804 /* Finally, create the wl_eglstream */
805 wl_array_init(&wlAttribs); /* Empty attributes list */
806
807 surface->ctx.wlStreamResource =
808 create_wl_eglstream(surface,
809 handle,
810 WL_EGLSTREAM_HANDLE_TYPE_FD,
811 &wlAttribs);
812 if (!surface->ctx.wlStreamResource) {
813 err = EGL_BAD_ALLOC;
814 goto fail;
815 }
816
817 /* Clean-up */
818 close(handle);
819 return EGL_SUCCESS;
820
821 fail:
822 destroy_surface_context(surface, &surface->ctx);
823 if (handle >= 0) {
824 close(handle);
825 }
826 return err;
827 }
828
829 #ifdef EGL_NV_stream_remote
830 static void* acceptOneConnection(void *args)
831 {
832 int *socket = (int *)args;
833 int serverSocket = *socket;
834
835 /* Accept only one connection and store the client socket that will be used
836 * to create the EGLStream */
837 *socket = accept(serverSocket, NULL, NULL);
838 close(serverSocket);
839
840 return NULL;
841 }
842
843 static EGLint startInetHandshake(pthread_t *thread,
844 int *clientSocket,
845 int *port)
846 {
847 struct sockaddr_in addr;
848 unsigned int addrLen;
849 EGLint err = EGL_SUCCESS;
850 int ret;
851
852 /* Create a server socket that will listen to all IPs and pick a random
853 * port. Then, only one connection will be accepted. We can use clientSocket
854 * to temporary store the server socket */
855 *clientSocket = socket(AF_INET, SOCK_STREAM, 0);
856 if (*clientSocket == -1) {
857 err = EGL_BAD_ALLOC;
858 goto fail;
859 }
860
861 memset(&addr, 0, sizeof(addr));
862
863 addr.sin_family = AF_INET;
864 addr.sin_addr.s_addr = INADDR_ANY; /* Accept connections to all IPs */
865 addr.sin_port = htons(0); /* Get a random port */
866 if (bind(*clientSocket, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
867 err = EGL_BAD_ALLOC;
868 goto fail;
869 }
870 if (listen(*clientSocket, 1) < 0) {
871 err = EGL_BAD_ALLOC;
872 goto fail;
873 }
874
875 /* Return host byte ordered port for sending through wayland protocol.
876 * Wayland will convert back to wire format before sending. */
877 addrLen = sizeof(addr);
878 ret = getsockname(*clientSocket, (struct sockaddr *)&addr, &addrLen);
879 if (ret != 0) {
880 err = EGL_BAD_ALLOC;
881 goto fail;
882 }
883 *port = ntohs(addr.sin_port);
884
885 /* Start a new thread that will accept one connection only. It will store
886 * the new client socket in <clientSocket>. */
887 ret = pthread_create(thread, NULL, acceptOneConnection, clientSocket);
888 if (ret != 0) {
889 err = EGL_BAD_ALLOC;
890 goto fail;
891 }
892
893 return EGL_SUCCESS;
894
895 fail:
896 if (*clientSocket >= 0) {
897 close(*clientSocket);
898 *clientSocket = -1;
899 }
900 return err;
901 }
902
903 static EGLint finishInetHandshake(pthread_t thread, int *socket)
904 {
905 int ret = pthread_join(thread, NULL);
906 if (ret != 0 || *socket == -1) {
907 return EGL_BAD_ALLOC;
908 }
909 return EGL_SUCCESS;
910 }
911
912 static EGLint create_surface_stream_remote(WlEglSurface *surface,
913 EGLBoolean useInet)
914 {
915 WlEglDisplay *display = surface->wlEglDpy;
916 WlEglPlatformData *data = display->data;
917 struct wl_array wlAttribs;
918 intptr_t *wlAttribsData;
919 EGLint eglAttribs[] = {
920 EGL_STREAM_TYPE_NV, EGL_STREAM_CROSS_PROCESS_NV,
921 EGL_STREAM_ENDPOINT_NV, EGL_STREAM_PRODUCER_NV,
922 EGL_STREAM_PROTOCOL_NV, EGL_STREAM_PROTOCOL_SOCKET_NV,
923 EGL_SOCKET_TYPE_NV, EGL_DONT_CARE,
924 EGL_SOCKET_HANDLE_NV, -1,
925 EGL_NONE, EGL_NONE,
926 EGL_NONE,
927 };
928 pthread_t thread;
929 int socket[2];
930 int port;
931 EGLint err = EGL_SUCCESS;
932 int ret;
933
934 wl_array_init(&wlAttribs); /* Empty attributes list */
935
936 if (useInet) {
937 /* Start inet handshaking and get the socket and selected port */
938 err = startInetHandshake(&thread, &socket[0], &port);
939 if (err != EGL_SUCCESS) {
940 goto fail;
941 }
942
943 /* Fill the wlAttribs array with the connection data. */
944 if (!(wlAttribsData = (intptr_t *)wl_array_add(&wlAttribs,
945 4*sizeof(intptr_t)))) {
946 err = EGL_BAD_ALLOC;
947 goto fail;
948 }
949
950 /* Get host byte ordered address for sending through wayland protocol.
951 * Wayland will convert back to wire format before sending. Assume a
952 * local INET connection until cross partition wayland support is added.
953 */
954 wlAttribsData[0] = WL_EGLSTREAM_ATTRIB_INET_ADDR;
955 wlAttribsData[1] = (intptr_t)INADDR_LOOPBACK;
956 wlAttribsData[2] = WL_EGLSTREAM_ATTRIB_INET_PORT;
957 wlAttribsData[3] = (intptr_t)port;
958
959 if (wlAttribsData[1] == -1) {
960 err = EGL_BAD_ALLOC;
961 goto fail;
962 }
963
964 /* Create a dummy fd to be feed into wayland. The fd will never be used,
965 * but wayland will abort if an invaild fd is given.
966 */
967 socket[1] = open("/dev/null", O_RDONLY);
968 if (socket[1] == -1) {
969 err = EGL_BAD_ALLOC;
970 goto fail;
971 }
972 } else {
973 /* Create a new socket pair for both EGLStream endpoints */
974 ret = socketpair(AF_UNIX, SOCK_STREAM, 0, socket);
975 if (ret != 0) {
976 err = EGL_BAD_ALLOC;
977 goto fail;
978 }
979 }
980
981 if (!(wlAttribsData = (intptr_t *)wl_array_add(&wlAttribs,
982 2*sizeof(intptr_t)))) {
983 err = EGL_BAD_ALLOC;
984 goto fail;
985 }
986
987 /* If Vulkan, default Y_INVERTED to 'true'. Otherwise, assume OpenGL
988 * orientation (image origin at the lower left corner), which aligns with
989 * what a wayland compositor would consider 'non-y-inverted' */
990 wlAttribsData[0] = WL_EGLSTREAM_ATTRIB_Y_INVERTED;
991 wlAttribsData[1] =
992 (intptr_t)(surface->isSurfaceProducer ? EGL_FALSE : EGL_TRUE);
993
994 surface->ctx.wlStreamResource =
995 create_wl_eglstream(surface,
996 socket[1],
997 (useInet ? WL_EGLSTREAM_HANDLE_TYPE_INET :
998 WL_EGLSTREAM_HANDLE_TYPE_SOCKET),
999 &wlAttribs);
1000 if (!surface->ctx.wlStreamResource) {
1001 err = EGL_BAD_ALLOC;
1002 goto fail;
1003 }
1004
1005 /* Need a roundtrip for the consumer's endpoint to be created before the
1006 * producer's */
1007 if (wl_display_roundtrip_queue(display->nativeDpy,
1008 surface->wlEventQueue) < 0) {
1009 err = EGL_BAD_ALLOC;
1010 goto fail;
1011 }
1012
1013 if (useInet) {
1014 /* Wait for the inet handshake to finish */
1015 err = finishInetHandshake(thread, &socket[0]);
1016 if (err != EGL_SUCCESS) {
1017 goto fail;
1018 }
1019 }
1020
1021 /* Finally, create the EGLStream
1022 *
1023 * EGL_SOCKET_TYPE_NV is in eglAttribs[6]
1024 * EGL_SOCKET_HANDLE_NV is in eglAttribs[8]
1025 */
1026 eglAttribs[7] = (useInet ? EGL_SOCKET_TYPE_INET_NV :
1027 EGL_SOCKET_TYPE_UNIX_NV);
1028 eglAttribs[9] = socket[0];
1029
1030 if (!surface->isSurfaceProducer &&
1031 display->wlStreamCtlVer >= WL_EGLSTREAM_CONTROLLER_ATTACH_EGLSTREAM_CONSUMER_ATTRIB_SINCE) {
1032 eglAttribs[10] = EGL_STREAM_FIFO_LENGTH_KHR;
1033 eglAttribs[11] = surface->fifoLength;
1034 }
1035
1036 surface->ctx.eglStream =
1037 data->egl.createStream(display->devDpy->eglDisplay, eglAttribs);
1038 if (surface->ctx.eglStream == EGL_NO_STREAM_KHR) {
1039 err = data->egl.getError();
1040 goto fail;
1041 }
1042
1043 /* Close server socket on the client side */
1044 if (socket[1] >= 0) {
1045 close(socket[1]);
1046 }
1047
1048 wl_array_release(&wlAttribs);
1049 return EGL_SUCCESS;
1050
1051 fail:
1052 destroy_surface_context(surface, &surface->ctx);
1053 wl_array_release(&wlAttribs);
1054 if (socket[0] >= 0) {
1055 close(socket[0]);
1056 }
1057 if (!useInet && socket[1] >= 0) {
1058 close(socket[1]);
1059 }
1060 return err;
1061 }
1062 #endif
1063
1064 static void
1065 stream_local_buffer_release_callback(void *ptr, struct wl_buffer *buffer)
1066 {
1067 WlEglStreamImage *image = (WlEglStreamImage*)ptr;
1068 /* Safe: image->surface pointer value is const once image is initialized */
1069 WlEglSurface *surface = image->surface;
1070 WlEglDisplay *display = surface->wlEglDpy;
1071 WlEglPlatformData *data = display->data;
1072
1073 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
1074
1075 (void)buffer; /* In case assert() compiles to nothing */
1076 assert(image->buffer == NULL || image->buffer == buffer);
1077
1078 image->attached = EGL_FALSE;
1079
1080 if (image->destructionPending) {
1081 /*
1082 * If there was an attempt to destroy the image while its buffer was
1083 * attached, the buffer destruction was deferred. Clean it up now.
1084 */
1085 destroy_stream_image(display, surface, image);
1086 } else {
1087 /*
1088 * Release our image back to the stream if explicit sync is not in use
1089 *
1090 * If explicit sync was used, then wl_buffer.release means nothing. We
1091 * will instead have already marked this image for release contingent
1092 * on the release sync getting signaled. This callback doesn't even fire
1093 * in that scenario.
1094 */
1095 assert(image->eglImage != EGL_NO_IMAGE_KHR);
1096
1097 data->egl.streamReleaseImage(display->devDpy->eglDisplay,
1098 surface->ctx.eglStream,
1099 image->eglImage,
1100 EGL_NO_SYNC_KHR);
1101 }
1102
1103 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
1104 }
1105
1106 static const struct wl_buffer_listener stream_local_buffer_listener = {
1107 stream_local_buffer_release_callback,
1108 };
1109
1110 /*
1111 * Export a syncfd from the timeline at the specified point and make an
1112 * EGLSyncKHR out of it. We can then pass this eglsync to releaseImageNV and
1113 * it will wait for the release point to signal before releasing the image back
1114 * to the screen.
1115 */
1116 static EGLSyncKHR
1117 get_release_sync(WlEglDisplay *display, WlEglStreamImage *image)
1118 {
1119 EGLDisplay dpy = display->devDpy->eglDisplay;
1120 WlEglPlatformData *data = display->data;
1121 EGLSyncKHR eglSync = EGL_NO_SYNC_KHR;
1122 int syncFd = -1;
1123 uint32_t tmpSyncobj;
1124 EGLint attribs[3];
1125
1126
1127 /* Import our acquire syncfd at a new acquire point */
1128 if (drmSyncobjCreate(display->drmFd, 0, &tmpSyncobj) != 0) {
1129 return EGL_NO_SYNC_KHR;
1130 }
1131
1132 if (drmSyncobjTransfer(display->drmFd, tmpSyncobj, 0,
1133 image->drmSyncobjHandle, image->releasePoint,
1134 0) != 0) {
1135 goto destroy;
1136 }
1137
1138 if (drmSyncobjExportSyncFile(display->drmFd, tmpSyncobj,
1139 &syncFd) != 0) {
1140 goto destroy;
1141 }
1142
1143 attribs[0] = EGL_SYNC_NATIVE_FENCE_FD_ANDROID;
1144 attribs[1] = syncFd;
1145 attribs[2] = EGL_NONE;
1146 eglSync = data->egl.createSync(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID,
1147 attribs);
1148 destroy:
1149 drmSyncobjDestroy(display->drmFd, tmpSyncobj);
1150
1151 return eglSync;
1152 }
1153
1154 /*
1155 * We have committed a frame, and if we are using explicit sync
1156 * we will have registered a release point with the compositor.
1157 * The release point's fence didn't exist then, so we should check
1158 * for any available fences that we should trigger releasing
1159 * images back into the stream with.
1160 *
1161 * This will block if no available buffers have been released.
1162 */
1163 EGLBoolean
1164 wlEglSurfaceCheckReleasePoints(WlEglDisplay *display, WlEglSurface *surface)
1165 {
1166 WlEglPlatformData *data = display->data;
1167 EGLDisplay dpy = display->devDpy->eglDisplay;
1168 EGLSyncKHR releaseSync = EGL_NO_SYNC_KHR;
1169 WlEglStreamImage *image = NULL;
1170 WlEglStreamImage *streamImages[MAX_IMAGES];
1171 uint32_t syncobjs[MAX_IMAGES];
1172 uint64_t syncPoints[MAX_IMAGES];
1173 uint32_t firstSignaled, numSyncPoints = 0;
1174 int64_t timeout;
1175 EGLBoolean ret = EGL_FALSE;
1176
1177 if (!surface->wlSyncobjSurf) {
1178 return EGL_TRUE;
1179 }
1180
1181 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
1182
1183 /* record each release point we are waiting on */
1184 wl_list_for_each(image, &surface->ctx.streamImages, link) {
1185 if (image->releasePending) {
1186 if (numSyncPoints >= MAX_IMAGES) {
1187 assert(!"The number of the pending sync points is more \
1188 than the expected size of the swapchain");
1189 break;
1190 }
1191
1192 streamImages[numSyncPoints] = image;
1193 syncobjs[numSyncPoints] = image->drmSyncobjHandle;
1194 syncPoints[numSyncPoints] = image->releasePoint;
1195
1196 numSyncPoints++;
1197 }
1198 }
1199
1200 if (numSyncPoints == 0) {
1201 goto end;
1202 }
1203
1204 /*
1205 * Wait for at least one release point to have a fence. We need to block here
1206 * since the streams internal code expects to have at least one buffer placed
1207 * back on the release (internally called returns) queue.
1208 *
1209 * We only wait indefinitely when all but one buffers are pending. There are
1210 * four total buffers:
1211 * 1. One owned by the driver (as per above)
1212 * 2. One we just committed and sent to the compositor
1213 * 3. One owned by compositor, queued for scanout
1214 * 4. One owned by compositor, in process of releasing
1215 *
1216 * Not all compositors will hold 3 and 4 indefinitely, although Kwin does
1217 * at certain times.
1218 */
1219 timeout = numSyncPoints >= 3 ? INT64_MAX : 0;
1220
1221 /*
1222 * The Linux docs say that DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE should be
1223 * used to wait for a fence to appear without waiting on the fence itself.
1224 * Note that there are some bugs with older kernels where this may not
1225 * signal correctly.
1226 */
1227 if (drmSyncobjTimelineWait(display->drmFd, syncobjs, syncPoints,
1228 numSyncPoints, timeout,
1229 DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE,
1230 &firstSignaled) != 0) {
1231 /* A timeout is the only type of error we expect here */
1232 #ifdef ETIME
1233 assert(errno == ETIME);
1234 #endif
1235 goto end;
1236 }
1237
1238 image = streamImages[firstSignaled];
1239
1240 /* Try to get a release point for the first available buffer. */
1241 releaseSync = get_release_sync(display, image);
1242 if (releaseSync == EGL_NO_SYNC_KHR) {
1243 goto end;
1244 }
1245
1246 /*
1247 * Pass our newly created release EGLSyncKHR to our eglstream, it
1248 * will wait for it to signal before it releases the image back to
1249 * the stream. Note that wl_buffer.release means nothing with
1250 * linux-drm-syncobj-v1.
1251 */
1252 ret = data->egl.streamReleaseImage(display->devDpy->eglDisplay,
1253 surface->ctx.eglStream,
1254 image->eglImage,
1255 releaseSync);
1256 /* releaseImage makes a copy, so we destroy ours here */
1257 data->egl.destroySync(dpy, releaseSync);
1258
1259 /*
1260 * If we succesfully released the image, Clear our release point so we
1261 * don't repeat this.
1262 */
1263 if (ret == EGL_TRUE) {
1264 image->releasePending = false;
1265 }
1266
1267 end:
1268 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
1269
1270 return ret;
1271 }
1272
1273 static EGLint
1274 acquire_surface_image(WlEglDisplay *display, WlEglSurface *surface)
1275 {
1276 WlEglPlatformData *data = display->data;
1277 EGLDisplay dpy = display->devDpy->eglDisplay;
1278 EGLImageKHR eglImage;
1279 WlEglStreamImage *image = NULL;
1280 struct zwp_linux_dmabuf_v1 *wrapper = NULL;
1281 struct zwp_linux_buffer_params_v1 *params;
1282 EGLuint64KHR modifier;
1283 int format;
1284 int planes;
1285 EGLint stride;
1286 EGLint offset;
1287 int fd;
1288 EGLSyncKHR acquireSync = EGL_NO_SYNC_KHR;
1289 EGLBoolean found = EGL_FALSE;
1290 const EGLint attribs[] = {
1291 EGL_SYNC_NATIVE_FENCE_FD_ANDROID, EGL_NO_NATIVE_FENCE_FD_ANDROID,
1292 EGL_SYNC_STATUS, EGL_SIGNALED,
1293 EGL_NONE,
1294 };
1295
1296 if (surface->wlSyncobjSurf) {
1297 /*
1298 * don't flush before acquireImage, we have to pass it in signaled.
1299 *
1300 * acquireImage will reset this, causing the fd to populate.
1301 */
1302 acquireSync = data->egl.createSync(dpy, EGL_SYNC_NATIVE_FENCE_ANDROID,
1303 attribs);
1304 if (acquireSync == EGL_NO_SYNC_KHR) {
1305 return EGL_BAD_SURFACE;
1306 }
1307 }
1308
1309 if (!data->egl.streamAcquireImage(dpy,
1310 surface->ctx.eglStream,
1311 &eglImage,
1312 acquireSync)) {
1313 goto fail_destroy_sync;
1314 }
1315
1316 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
1317
1318 // Locate the corresponding WlEglStreamImage
1319 wl_list_for_each(image, &surface->ctx.streamImages, link) {
1320 if (image->eglImage == eglImage) {
1321 found = EGL_TRUE;
1322 break;
1323 }
1324 }
1325
1326 if (!found) {
1327 goto fail_release;
1328 }
1329
1330 image->acquireSync = acquireSync;
1331
1332 if (!image->buffer) {
1333 if (!data->egl.exportDMABUFImageQuery(dpy,
1334 eglImage,
1335 &format,
1336 &planes,
1337 &modifier)) {
1338 goto fail_release;
1339 }
1340
1341 assert(planes == 1); /* XXX support planar formats */
1342
1343 if (!data->egl.exportDMABUFImage(dpy,
1344 eglImage,
1345 &fd,
1346 &stride,
1347 &offset)) {
1348 goto fail_release;
1349 }
1350
1351 wrapper = wl_proxy_create_wrapper(display->wlDmaBuf);
1352 wl_proxy_set_queue((struct wl_proxy *)wrapper, surface->wlBufferEventQueue);
1353
1354 params = zwp_linux_dmabuf_v1_create_params(wrapper);
1355
1356 zwp_linux_buffer_params_v1_add(params,
1357 fd,
1358 0, /* XXX support planar formats */
1359 offset,
1360 stride,
1361 modifier >> 32,
1362 modifier & 0xffffffff);
1363
1364 /*
1365 * Before sending the format, check if we are ignoring alpha due to a
1366 * surface attribute.
1367 */
1368 if (surface->presentOpaque) {
1369 /*
1370 * We are ignoring alpha, so we need to find a DRM_FORMAT_* that is equivalent to
1371 * the current format, but ignores the alpha. i.e. RGBA -> RGBX
1372 *
1373 * There is also only one format with alpha that we expose on wayland: ARGB8888. If
1374 * the format does not match this, silently ignore it as the app must be mistakenly
1375 * using EGL_PRESENT_OPAQUE_EXT on an already opaque surface.
1376 */
1377 if (format == DRM_FORMAT_ARGB8888) {
1378 format = DRM_FORMAT_XRGB8888;
1379 }
1380 }
1381
1382 image->buffer = zwp_linux_buffer_params_v1_create_immed(params,
1383 surface->width,
1384 surface->height,
1385 format, 0);
1386
1387 zwp_linux_buffer_params_v1_destroy(params);
1388 wl_proxy_wrapper_destroy(wrapper); /* Done with wrapper */
1389 close(fd);
1390
1391 if (!image->buffer) {
1392 goto fail_release;
1393 }
1394
1395 if (!surface->wlSyncobjSurf &&
1396 wl_buffer_add_listener(image->buffer,
1397 &stream_local_buffer_listener,
1398 image) == -1) {
1399 wl_buffer_destroy(image->buffer);
1400 image->buffer = NULL;
1401 goto fail_release;
1402 }
1403 }
1404
1405 /* Add image to the end of the acquired images list */
1406 wl_list_insert(surface->ctx.acquiredImages.prev, &image->acquiredLink);
1407
1408 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
1409
1410 return EGL_SUCCESS;
1411
1412 fail_release:
1413 /* Release the image back to the stream */
1414 data->egl.streamReleaseImage(dpy,
1415 surface->ctx.eglStream,
1416 eglImage,
1417 EGL_NO_SYNC_KHR);
1418
1419 if (acquireSync != EGL_NO_SYNC_KHR) {
1420 data->egl.destroySync(dpy, acquireSync);
1421 if (found) {
1422 assert(image->acquireSync == acquireSync);
1423 image->acquireSync = EGL_NO_SYNC_KHR;
1424 }
1425 }
1426
1427 /* Release the image lock */
1428 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
1429
1430 return EGL_BAD_SURFACE;
1431
1432 fail_destroy_sync:
1433 if (acquireSync != EGL_NO_SYNC_KHR) {
1434 data->egl.destroySync(dpy, acquireSync);
1435 }
1436 return EGL_BAD_SURFACE;
1437 }
1438
1439 static void
1440 remove_surface_image(WlEglDisplay *display,
1441 WlEglSurface *surface,
1442 EGLImageKHR eglImage)
1443 {
1444 WlEglStreamImage *image;
1445
1446 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
1447
1448 wl_list_for_each(image, &surface->ctx.streamImages, link) {
1449 /* Safe only because the iteration is aborted by a break statement */
1450 if (image->eglImage == eglImage) {
1451 destroy_stream_image(display, surface, image);
1452 break;
1453 }
1454 }
1455
1456 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
1457 }
1458
1459 static WlEglStreamImage *
1460 pop_acquired_image(WlEglSurface *surface)
1461 {
1462 WlEglStreamImage *image;
1463
1464 wl_list_for_each(image, &surface->ctx.acquiredImages, acquiredLink) {
1465 /* Safe only because the iteration is aborted by returning */
1466 wl_list_remove(&image->acquiredLink);
1467 wl_list_init(&image->acquiredLink);
1468 return image;
1469 }
1470
1471 /* List is empty. Return NULL. */
1472 return NULL;
1473 }
1474
1475 static int
1476 create_syncobj_timeline(WlEglDisplay *display, uint32_t *drmSyncobjHandleOut)
1477 {
1478 int ret;
1479
1480 /* Create a DRM timeline and share it with the compositor */
1481 if (drmSyncobjCreate(display->drmFd, 0, drmSyncobjHandleOut)) {
1482 return -1;
1483 }
1484
1485 if (drmSyncobjHandleToFD(display->drmFd, *drmSyncobjHandleOut, &ret)) {
1486 return -1;
1487 }
1488
1489 return ret;
1490 }
1491
1492 static EGLint
1493 init_surface_image(WlEglDisplay *display, WlEglSurface *surface,
1494 WlEglStreamImage *image)
1495 {
1496 WlEglPlatformData *data = display->data;
1497 EGLDisplay dpy = display->devDpy->eglDisplay;
1498 int drmSyncobjFd = -1;
1499
1500 image->eglImage = data->egl.createImage(dpy, EGL_NO_CONTEXT,
1501 EGL_STREAM_CONSUMER_IMAGE_NV,
1502 (EGLClientBuffer)surface->ctx.eglStream,
1503 NULL);
1504 if (image->eglImage == EGL_NO_IMAGE_KHR) {
1505 return EGL_BAD_ALLOC;
1506 }
1507
1508 /*
1509 * Create a per-stream image release timeline.
1510 *
1511 * This is needed since we will be the ones signaling acquire points. If the acquire points
1512 * are on the same timeline as the release points then they will accidentally signal all
1513 * pending release points.
1514 */
1515 if (surface->wlSyncobjSurf) {
1516 drmSyncobjFd = create_syncobj_timeline(display, &image->drmSyncobjHandle);
1517 if (drmSyncobjFd < 0) {
1518 goto fail;
1519 }
1520 image->acquireSync = EGL_NO_SYNC_KHR;
1521
1522 /* Get a DRM timeline wl object */
1523 image->wlReleaseTimeline =
1524 wp_linux_drm_syncobj_manager_v1_import_timeline(display->wlDrmSyncobj, drmSyncobjFd);
1525 if (!image->wlReleaseTimeline) {
1526 goto fail;
1527 }
1528
1529 close(drmSyncobjFd);
1530 }
1531
1532 image->surface = surface;
1533 wl_list_init(&image->acquiredLink);
1534
1535 return EGL_SUCCESS;
1536
1537 fail:
1538 if (image->drmSyncobjHandle) {
1539 drmSyncobjDestroy(display->drmFd, image->drmSyncobjHandle);
1540 }
1541
1542 if (drmSyncobjFd > 0) {
1543 close(drmSyncobjFd);
1544 }
1545
1546 data->egl.destroyImage(dpy, image->eglImage);
1547 return EGL_BAD_ALLOC;
1548 }
1549
1550 static EGLint
1551 add_surface_image(WlEglDisplay *display, WlEglSurface *surface)
1552 {
1553 WlEglStreamImage* const image = calloc(1, sizeof(*image));
1554 EGLint ret;
1555
1556 if (!image) {
1557 return EGL_BAD_ALLOC;
1558 }
1559
1560 ret = init_surface_image(display, surface, image);
1561 if (ret != EGL_SUCCESS) {
1562 free(image);
1563 return ret;
1564 }
1565
1566 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
1567 wl_list_insert(&surface->ctx.streamImages, &image->link);
1568 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
1569
1570 return EGL_SUCCESS;
1571 }
1572
1573 EGLint wlEglHandleImageStreamEvents(WlEglSurface *surface)
1574 {
1575 WlEglDisplay *display = surface->wlEglDpy;
1576 EGLDisplay dpy = display->devDpy->eglDisplay;
1577 WlEglPlatformData *data = display->data;
1578 EGLAttrib aux;
1579 EGLenum event;
1580 EGLint err = EGL_SUCCESS;
1581 EGLTime timeout = surface->wlSyncobjSurf ? EGL_FOREVER : 0;
1582
1583 if (surface->ctx.wlStreamResource) {
1584 /* Not a local stream */
1585 return err;
1586 }
1587
1588 while (1) {
1589 /*
1590 * With explicit sync we should block here and not return until we have
1591 * acquired a new image. The stream will not release the image until
1592 * the release point we handed to the compositor signals.
1593 */
1594 err = data->egl.queryStreamConsumerEvent(dpy,
1595 surface->ctx.eglStream,
1596 timeout,
1597 &event,
1598 &aux);
1599
1600 if (err == EGL_TRUE) {
1601 err = EGL_SUCCESS;
1602 } else if (err == EGL_TIMEOUT_EXPIRED) {
1603 err = EGL_SUCCESS;
1604 break;
1605 } else if (err == EGL_FALSE) {
1606 /* XXX Pick the right error code */
1607 err = EGL_BAD_SURFACE;
1608 break;
1609 } else {
1610 break;
1611 }
1612
1613 switch (event) {
1614 case EGL_STREAM_IMAGE_AVAILABLE_NV:
1615 err = acquire_surface_image(display, surface);
1616 /* Clear our timeout so we exit after all events are handled */
1617 timeout = 0;
1618 break;
1619 case EGL_STREAM_IMAGE_ADD_NV:
1620 err = add_surface_image(display, surface);
1621 break;
1622
1623 case EGL_STREAM_IMAGE_REMOVE_NV:
1624 remove_surface_image(display, surface, (EGLImageKHR)aux);
1625 break;
1626
1627 default:
1628 assert(!"Unhandled EGLImage stream consumer event");
1629 }
1630 }
1631
1632 return err;
1633 }
1634
1635 static WlEglDmaBufFormatSet *
1636 WlEglGetFormatSetForDev(WlEglDmaBufFeedback *feedback, dev_t dev, uint32_t format)
1637 {
1638 /* find the dev_t in our feedback's list of tranches */
1639 for (int i = 0; i < (int)feedback->numTranches; i++) {
1640 if (feedback->tranches[i].drmDev == dev) {
1641 /* check if this tranche contains our format */
1642 WlEglDmaBufFormatSet *formatSet = &feedback->tranches[i].formatSet;
1643 for (int j = 0; j < (int)formatSet->numFormats; ++j) {
1644 if (formatSet->dmaBufFormats[j].format == format) {
1645 return formatSet;
1646 }
1647 }
1648 }
1649 }
1650
1651 return NULL;
1652 }
1653
1654 /*
1655 * TODO: Remove this once an EGL extension exists to query this information.
1656 *
1657 * This is taken from the GBM library, it looks at the config's sizes and
1658 * hardcodes the equivalent DRM format. Eventually we want to be able to query
1659 * this directly from the EGLConfig, but since that extension is in the works
1660 * we don't want to hold up wayland improvements. This function will be used
1661 * until the extension is available.
1662 */
1663 static uint32_t ConfigToDrmFourCC(WlEglDisplay* display, EGLConfig config)
1664 {
1665 EGLDisplay dpy = display->devDpy->eglDisplay;
1666 EGLint r, g, b, a;
1667 EGLBoolean ret = EGL_TRUE;
1668
1669 ret &= display->data->egl.getConfigAttrib(dpy,
1670 config,
1671 EGL_RED_SIZE,
1672 &r);
1673 ret &= display->data->egl.getConfigAttrib(dpy,
1674 config,
1675 EGL_GREEN_SIZE,
1676 &g);
1677 ret &= display->data->egl.getConfigAttrib(dpy,
1678 config,
1679 EGL_BLUE_SIZE,
1680 &b);
1681 ret &= display->data->egl.getConfigAttrib(dpy,
1682 config,
1683 EGL_ALPHA_SIZE,
1684 &a);
1685
1686 if (!ret) {
1687 /*
1688 * The only reason this could fail is some internal error in the
1689 * platform library code or if the application terminated the display
1690 * in another thread while this code was running. In either case,
1691 * behave as if there is no DRM fourcc format associated with this
1692 * config.
1693 */
1694 return 0; /* DRM_FORMAT_INVALID */
1695 }
1696
1697 /* Handles configs with up to 255 bits per component */
1698 assert(a < 256 && g < 256 && b < 256 && a < 256);
1699 #define PACK_CONFIG(r_, g_, b_, a_) \
1700 (((r_) << 24ULL) | ((g_) << 16ULL) | ((b_) << 8ULL) | (a_))
1701
1702 switch (PACK_CONFIG(r, g, b, a)) {
1703 case PACK_CONFIG(8, 8, 8, 0):
1704 return DRM_FORMAT_XRGB8888;
1705 case PACK_CONFIG(8, 8, 8, 8):
1706 return DRM_FORMAT_ARGB8888;
1707 case PACK_CONFIG(5, 6, 5, 0):
1708 return DRM_FORMAT_RGB565;
1709 case PACK_CONFIG(10, 10, 10, 0):
1710 return DRM_FORMAT_XRGB2101010;
1711 case PACK_CONFIG(10, 10, 10, 2):
1712 return DRM_FORMAT_ARGB2101010;
1713 default:
1714 return 0; /* DRM_FORMAT_INVALID */
1715 }
1716 }
1717
1718 static EGLint create_surface_stream_local(WlEglSurface *surface)
1719 {
1720 WlEglDisplay *display = surface->wlEglDpy;
1721 WlEglPlatformData *data = display->data;
1722 EGLDisplay dpy = display->devDpy->eglDisplay;
1723 EGLint eglAttribs[] = {
1724 EGL_STREAM_FIFO_LENGTH_KHR, surface->fifoLength,
1725 EGL_NONE, EGL_NONE,
1726 EGL_NONE
1727 };
1728 EGLint err = EGL_SUCCESS;
1729 EGLint numModifiers = 0;
1730 EGLuint64KHR *modifiers = NULL;
1731 uint32_t format;
1732 WlEglDmaBufFormatSet *formatSet = NULL;
1733 WlEglDmaBufFeedback *feedback = NULL;
1734
1735 /*
1736 * Vulkan surfaces will not have an eglConfig set. We will need to address them
1737 * separately.
1738 */
1739 if (surface->eglConfig) {
1740 /*
1741 * Find the format we are using
1742 * For now we use the hardcoded calculation in ConfigToDrmFourCC (which is from
1743 * the gbm code). In the future we will have an EGL extension to get this from
1744 * a config, and we will switch to that.
1745 */
1746 format = ConfigToDrmFourCC(display, surface->eglConfig);
1747 if (!format) {
1748 err = EGL_BAD_ACCESS;
1749 goto fail;
1750 }
1751
1752 /* Get our format set, if we have feedback it will be the device's format set */
1753 if (display->dmaBufProtocolVersion < 4) {
1754 formatSet = &display->formatSet;
1755 } else {
1756 /*
1757 * If the surface has a per-surface feedback object, then use the modifiers
1758 * from that. Otherwise use the default feedback.
1759 */
1760 if (surface->feedback.wlDmaBufFeedback) {
1761 feedback = &surface->feedback;
1762 } else {
1763 feedback = &display->defaultFeedback;
1764 }
1765
1766 formatSet = WlEglGetFormatSetForDev(feedback, display->devDpy->dev, format);
1767 if (!formatSet) {
1768 /* try again and see if there is a matching tranche for the render node */
1769 formatSet = WlEglGetFormatSetForDev(feedback, display->devDpy->renderNode, format);
1770 }
1771
1772 /*
1773 * If we could not find any modifiers for this device, and if we are
1774 * in a prime setup, use the main device's format set. This will allow
1775 * us to check if the main device supports the linear modifier.
1776 */
1777 if (!formatSet && display->primeRenderOffload) {
1778 formatSet = WlEglGetFormatSetForDev(feedback, feedback->mainDev, format);
1779 }
1780 }
1781
1782 /* grab the modifier array */
1783 if (formatSet) {
1784 for (int i = 0; i < (int)formatSet->numFormats; i++) {
1785 if (formatSet->dmaBufFormats[i].format == format) {
1786 modifiers = formatSet->dmaBufFormats[i].modifiers;
1787 numModifiers = formatSet->dmaBufFormats[i].numModifiers;
1788 break;
1789 }
1790 }
1791 }
1792 }
1793
1794 /* We don't have any mechanism to check whether the compositor is going to
1795 * use this surface for composition or not when using local streams, so
1796 * just enable FIFO_SYNCHRONOUS if the extensions are supported.
1797 * Note the use of this mechanism makes the optional sync parameter
1798 * passed to eglStreamAcquireImageNV() redundant, so that mechanism is not
1799 * used in this library.
1800 */
1801 if (display->devDpy->exts.stream_fifo_synchronous &&
1802 display->devDpy->exts.stream_sync &&
1803 surface->fifoLength > 0) {
1804 eglAttribs[2] = EGL_STREAM_FIFO_SYNCHRONOUS_NV;
1805 eglAttribs[3] = EGL_TRUE;
1806 }
1807
1808 /* First, create the EGLStream */
1809 surface->ctx.eglStream =
1810 data->egl.createStream(dpy, eglAttribs);
1811 if (surface->ctx.eglStream == EGL_NO_STREAM_KHR) {
1812 err = data->egl.getError();
1813 goto fail;
1814 }
1815
1816 /* Now create the local EGLImage consumer */
1817 if (!data->egl.streamImageConsumerConnect(dpy,
1818 surface->ctx.eglStream,
1819 numModifiers,
1820 modifiers,
1821 NULL)) {
1822 err = data->egl.getError();
1823 goto fail;
1824 }
1825
1826 wl_list_init(&surface->ctx.acquiredImages);
1827
1828 /*
1829 * Don't enable the buffer release thread when explicit sync is in use.
1830 * In explicit sync we don't care about the delivery of release events, we
1831 * only pay attention to the release points.
1832 */
1833 if (!surface->wlBufferEventQueue && !surface->wlSyncobjSurf) {
1834 /*
1835 * Local stream contexts need a private wayland queue used by a separate
1836 * thread that can process buffer release events even the application
1837 * thread is blocking in the EGL library for stream frame acquisition
1838 * while swapping the producer surface. The thread and queue are owned
1839 * by the surface because they need to outlive the context when resizing
1840 * the surface while a buffer is still attached, but they are
1841 * initialized lazily here to avoid incuring the cost of an extra unused
1842 * thread and two pipe file descriptors per surface when they are not
1843 * needed.
1844 */
1845 if (EGL_SUCCESS != setup_wl_buffer_release_thread(surface)) {
1846 goto fail;
1847 }
1848 }
1849
1850 return EGL_SUCCESS;
1851
1852 fail:
1853 destroy_surface_context(surface, &surface->ctx);
1854 return err;
1855 }
1856
1857 static EGLint
1858 create_surface_stream(WlEglSurface *surface)
1859 {
1860 WlEglDisplay *display = surface->wlEglDpy;
1861 EGLint err = EGL_BAD_ACCESS;
1862
1863 /* Try all supported EGLStream creation methods until one of them succeeds.
1864 * More efficient connection schemes should be given a higher priority. If
1865 * there is more than one method giving the same efficiency, the more
1866 * versatile/configurable one would be preferred:
1867 *
1868 * 1. Local stream + dma-buf
1869 * 2. Cross-process unix sockets
1870 * 3. Cross-process FD
1871 * 4. Cross-process inet sockets
1872 */
1873 #ifdef EGL_NV_stream_consumer_eglimage
1874 if ((err != EGL_SUCCESS) &&
1875 display->devDpy->exts.stream_consumer_eglimage &&
1876 display->devDpy->exts.image_dma_buf_export &&
1877 display->wlDmaBuf) {
1878 err = create_surface_stream_local(surface);
1879 }
1880 #endif
1881
1882 #ifdef EGL_NV_stream_remote
1883 if ((err != EGL_SUCCESS) &&
1884 display->caps.stream_socket &&
1885 display->devDpy->exts.stream_remote) {
1886 err = create_surface_stream_remote(surface, EGL_FALSE);
1887 }
1888 #endif
1889
1890 if ((err != EGL_SUCCESS) &&
1891 display->caps.stream_fd &&
1892 display->devDpy->exts.stream_cross_process_fd) {
1893 err = create_surface_stream_fd(surface);
1894 }
1895
1896 #ifdef EGL_NV_stream_remote
1897 if ((err != EGL_SUCCESS) &&
1898 display->caps.stream_inet &&
1899 display->devDpy->exts.stream_remote) {
1900 err = create_surface_stream_remote(surface, EGL_TRUE);
1901 }
1902 #endif
1903
1904 return err;
1905 }
1906
1907 static EGLint
1908 create_surface_context(WlEglSurface *surface)
1909 {
1910 WlEglDisplay *display = surface->wlEglDpy;
1911 WlEglPlatformData *data = display->data;
1912 struct wl_egl_window *window = surface->wlEglWin;
1913 int winWidth = 0;
1914 int winHeight = 0;
1915 int winDx = 0;
1916 int winDy = 0;
1917 EGLint synchronous = EGL_FALSE;
1918 EGLint err = EGL_SUCCESS;
1919 struct wl_array wlAttribs;
1920 intptr_t *wlAttribsData;
1921
1922 assert(surface->ctx.eglSurface == EGL_NO_SURFACE);
1923 if (surface->isSurfaceProducer) {
1924 winWidth = window->width;
1925 winHeight = window->height;
1926 winDx = window->dx;
1927 winDy = window->dy;
1928
1929 /* Width and height are the first and second attributes respectively */
1930 surface->attribs[1] = winWidth;
1931 surface->attribs[3] = winHeight;
1932 } else {
1933 winWidth = surface->width;
1934 winHeight = surface->height;
1935 winDx = surface->dx;
1936 winDy = surface->dy;
1937 }
1938
1939 /* First, create the underlying wl_eglstream and EGLStream */
1940 err = create_surface_stream(surface);
1941 if (err != EGL_SUCCESS) {
1942 goto fail;
1943 }
1944
1945 /* If the stream has a server component, attach the wl_eglstream so the
1946 * compositor connects a consumer to the EGLStream */
1947 if (surface->ctx.wlStreamResource) {
1948 if (display->wlStreamCtl != NULL) {
1949 if (display->wlStreamCtlVer >=
1950 WL_EGLSTREAM_CONTROLLER_ATTACH_EGLSTREAM_CONSUMER_ATTRIB_SINCE) {
1951 wl_array_init(&wlAttribs);
1952
1953 if (!wl_array_add(&wlAttribs, 2 * sizeof(intptr_t))) {
1954 wl_array_release(&wlAttribs);
1955 err = EGL_BAD_ALLOC;
1956 goto fail;
1957 }
1958
1959 wlAttribsData = (intptr_t *)wlAttribs.data;
1960 wlAttribsData[0] = WL_EGLSTREAM_CONTROLLER_ATTRIB_PRESENT_MODE;
1961
1962 if (surface->isSurfaceProducer) {
1963 wlAttribsData[1] = WL_EGLSTREAM_CONTROLLER_PRESENT_MODE_DONT_CARE;
1964 } else if (surface->fifoLength > 0) {
1965 if (!wl_array_add(&wlAttribs, 2 * sizeof(intptr_t))) {
1966 wl_array_release(&wlAttribs);
1967 err = EGL_BAD_ALLOC;
1968 goto fail;
1969 }
1970 wlAttribsData = (intptr_t *)wlAttribs.data;
1971 wlAttribsData[1] = WL_EGLSTREAM_CONTROLLER_PRESENT_MODE_FIFO;
1972 wlAttribsData[2] = WL_EGLSTREAM_CONTROLLER_ATTRIB_FIFO_LENGTH;
1973 wlAttribsData[3] = surface->fifoLength;
1974 } else {
1975 wlAttribsData[1] = WL_EGLSTREAM_CONTROLLER_PRESENT_MODE_MAILBOX;
1976 }
1977
1978 wl_eglstream_controller_attach_eglstream_consumer_attribs(display->wlStreamCtl,
1979 surface->wlSurface,
1980 surface->ctx.wlStreamResource,
1981 &wlAttribs);
1982 wl_array_release(&wlAttribs);
1983 } else {
1984 wl_eglstream_controller_attach_eglstream_consumer(display->wlStreamCtl,
1985 surface->wlSurface,
1986 surface->ctx.wlStreamResource);
1987 }
1988 } else {
1989 wl_surface_attach(surface->wlSurface,
1990 surface->ctx.wlStreamResource,
1991 winDx,
1992 winDy);
1993 wl_surface_commit(surface->wlSurface);
1994
1995 /* Since we are using the legacy method of overloading wl_surface_attach
1996 * in order to create the server-side EGLStream here, the compositor
1997 * will actually take this as a new buffer. We mark it as 'attached'
1998 * because whenever a new wl_surface_attach request is issued, the
1999 * compositor will emit back a wl_buffer_release event, and we will
2000 * destroy the context then. */
2001 surface->ctx.isAttached = EGL_TRUE;
2002 }
2003
2004 if (wl_display_roundtrip_queue(display->nativeDpy,
2005 surface->wlEventQueue) < 0) {
2006 err = EGL_BAD_ALLOC;
2007 goto fail;
2008 }
2009 }
2010
2011 if (surface->isSurfaceProducer) {
2012 /* Finally, create the surface producer */
2013 surface->ctx.eglSurface =
2014 data->egl.createStreamProducerSurface(display->devDpy->eglDisplay,
2015 surface->eglConfig,
2016 surface->ctx.eglStream,
2017 surface->attribs);
2018 if (surface->ctx.eglSurface == EGL_NO_SURFACE) {
2019 err = data->egl.getError();
2020 goto fail;
2021 }
2022 wl_display_flush(display->nativeDpy);
2023 }
2024
2025 /* Check whether we should use a damage thread */
2026 surface->ctx.useDamageThread =
2027 !surface->wlSyncobjSurf &&
2028 display->devDpy->exts.stream_fifo_synchronous &&
2029 display->devDpy->exts.stream_sync &&
2030 data->egl.queryStream(display->devDpy->eglDisplay,
2031 surface->ctx.eglStream,
2032 EGL_STREAM_FIFO_SYNCHRONOUS_NV,
2033 &synchronous) &&
2034 (synchronous == EGL_TRUE);
2035 if (surface->ctx.useDamageThread) {
2036 err = setup_wl_eglstream_damage_thread(surface);
2037 if (err != EGL_SUCCESS) {
2038 goto fail;
2039 }
2040 }
2041
2042 /* Cache current window size and displacement for future checks */
2043 if (surface->isSurfaceProducer) {
2044 surface->width = winWidth;
2045 surface->height = winHeight;
2046 surface->dx = winDx;
2047 surface->dy = winDy;
2048 window->attached_width = winWidth;
2049 window->attached_height = winHeight;
2050 }
2051
2052 return EGL_SUCCESS;
2053
2054 fail:
2055 destroy_surface_context(surface, &surface->ctx);
2056 finish_wl_buffer_release_thread(surface);
2057 return err;
2058 }
2059
2060 WL_EXPORT
2061 EGLStreamKHR wlEglGetSurfaceStreamExport(WlEglSurface *surface)
2062 {
2063 if (!surface)
2064 return EGL_NO_STREAM_KHR;
2065
2066 return surface->ctx.eglStream;
2067 }
2068
2069 WL_EXPORT
2070 int wlEglWaitAllPresentationFeedbacksExport(WlEglSurface *surface)
2071 {
2072 int numberOfPresentEvents = 0;
2073
2074 WlEglDisplay *display = wlEglAcquireDisplay((WlEglDisplay *)surface->wlEglDpy);
2075 pthread_mutex_lock(&surface->mutexLock);
2076
2077 // Destroy all presentation feedback objects in flight
2078 if (display->wpPresentation) {
2079 assert(surface->landedPresentFeedbackCount == 0);
2080
2081 while (surface->inFlightPresentFeedbackCount > 0) {
2082 const int ret = wl_display_dispatch_queue(display->nativeDpy, surface->presentFeedbackQueue);
2083 if (ret < 0) {
2084 pthread_mutex_unlock(&surface->mutexLock);
2085 wlEglReleaseDisplay(display);
2086
2087 return ret;
2088 }
2089 }
2090 }
2091
2092 assert(surface->inFlightPresentFeedbackCount == 0);
2093
2094 numberOfPresentEvents = surface->landedPresentFeedbackCount;
2095 surface->landedPresentFeedbackCount = 0;
2096
2097 pthread_mutex_unlock(&surface->mutexLock);
2098 wlEglReleaseDisplay(display);
2099
2100 return numberOfPresentEvents;
2101 }
2102
2103 WL_EXPORT
2104 int wlEglProcessPresentationFeedbacksExport(WlEglSurface *surface)
2105 {
2106 int numberOfPresentEvents = 0;
2107
2108 WlEglDisplay *display = wlEglAcquireDisplay((WlEglDisplay *)surface->wlEglDpy);
2109 pthread_mutex_lock(&surface->mutexLock);
2110
2111 if (display->wpPresentation) {
2112 int ret = 0;
2113
2114 assert(surface->landedPresentFeedbackCount == 0);
2115 ret = wl_display_dispatch_queue_pending(display->nativeDpy,
2116 surface->presentFeedbackQueue);
2117 if (ret < 0) {
2118 pthread_mutex_unlock(&surface->mutexLock);
2119 wlEglReleaseDisplay(display);
2120
2121 return ret;
2122 }
2123 }
2124
2125 numberOfPresentEvents = surface->landedPresentFeedbackCount;
2126 surface->landedPresentFeedbackCount = 0;
2127
2128 assert(surface->inFlightPresentFeedbackCount >= 0);
2129
2130 pthread_mutex_unlock(&surface->mutexLock);
2131 wlEglReleaseDisplay(display);
2132
2133 return numberOfPresentEvents;
2134 }
2135
2136 WL_EXPORT
2137 WlEglSurface *wlEglCreateSurfaceExport(EGLDisplay dpy,
2138 int width,
2139 int height,
2140 struct wl_surface *native_surface,
2141 int fifo_length)
2142 {
2143 WlEglDisplay *display = (WlEglDisplay *)wlEglAcquireDisplay(dpy);
2144 WlEglSurface *surface = NULL;
2145
2146 if (!display) {
2147 return NULL;
2148 }
2149
2150 pthread_mutex_lock(&display->mutex);
2151
2152 surface = calloc(1, sizeof (*surface));
2153 if (!surface) {
2154 goto fail;
2155 }
2156
2157 surface->wlEglDpy = display;
2158 surface->width = width;
2159 surface->height = height;
2160 surface->wlSurface = native_surface;
2161 surface->fifoLength = fifo_length;
2162 surface->swapInterval = fifo_length > 0 ? 1 : 0;
2163
2164 // Create per surface wayland queue
2165 surface->wlEventQueue = wl_display_create_queue(display->nativeDpy);
2166 // Create an event queue for presentation time feedback events if
2167 // the presentation time protocol exists
2168 if (display->wpPresentation) {
2169 surface->presentFeedbackQueue = wl_display_create_queue(display->nativeDpy);
2170 }
2171
2172 surface->refCount = 1;
2173
2174 if (!wlEglInitializeMutex(&surface->mutexLock)) {
2175 goto fail;
2176 }
2177
2178 if (!wlEglInitializeMutex(&surface->mutexFrameSync)) {
2179 pthread_mutex_unlock(&display->mutex);
2180 wlEglReleaseDisplay(display);
2181 return EGL_FALSE;
2182 }
2183
2184 if (pthread_cond_init(&surface->condFrameSync, NULL)) {
2185 pthread_mutex_unlock(&display->mutex);
2186 wlEglReleaseDisplay(display);
2187 return EGL_FALSE;
2188 }
2189
2190 if (create_surface_context(surface) != EGL_SUCCESS) {
2191 wl_event_queue_destroy(surface->wlEventQueue);
2192 if (surface->presentFeedbackQueue) {
2193 wl_event_queue_destroy(surface->presentFeedbackQueue);
2194 }
2195 goto fail;
2196 }
2197
2198 wl_list_insert(&display->wlEglSurfaceList, &surface->link);
2199 wl_list_init(&surface->oldCtxList);
2200
2201 if (surface->ctx.wlStreamResource) {
2202 /* Set client's pendingSwapIntervalUpdate for updating client's
2203 * swapinterval
2204 */
2205 surface->pendingSwapIntervalUpdate = EGL_TRUE;
2206 }
2207
2208 pthread_mutex_unlock(&display->mutex);
2209 wlEglReleaseDisplay(display);
2210 return surface;
2211
2212 fail:
2213 pthread_mutex_unlock(&display->mutex);
2214 wlEglReleaseDisplay(display);
2215 free(surface);
2216 return NULL;
2217 }
2218
2219 WL_EXPORT
2220 WlEglSurface *wlEglCreateSurfaceExport2(EGLDisplay dpy,
2221 int width,
2222 int height,
2223 struct wl_surface *native_surface,
2224 int fifo_length,
2225 int (*present_update_callback)(void*, uint64_t, int),
2226 const EGLAttrib *attribs)
2227 {
2228 WlEglSurface* const surface = wlEglCreateSurfaceExport(dpy,
2229 width,
2230 height,
2231 native_surface,
2232 fifo_length);
2233 if (!surface)
2234 {
2235 return NULL;
2236 }
2237
2238 surface->present_update_callback = present_update_callback;
2239
2240 if (assignWlEglSurfaceAttribs(surface, attribs) != EGL_SUCCESS)
2241 {
2242 wlEglDestroySurfaceHook(dpy, surface);
2243 return NULL;
2244 }
2245
2246 return surface;
2247 }
2248
2249 void
2250 wlEglReallocSurface(WlEglDisplay *display, WlEglPlatformData *pData, WlEglSurface *surface)
2251 {
2252 EGLint err = EGL_SUCCESS;
2253
2254 // If a damage thread is in use, wait for it to finish processing all
2255 // pending frames
2256 finish_wl_eglstream_damage_thread(surface, &surface->ctx, 0);
2257
2258 discard_surface_context(surface);
2259 surface->isResized = EGL_FALSE;
2260 surface->ctx.wlStreamResource = NULL;
2261 surface->ctx.isAttached = EGL_FALSE;
2262 surface->ctx.eglSurface = EGL_NO_SURFACE;
2263 surface->ctx.eglStream = EGL_NO_STREAM_KHR;
2264 surface->ctx.damageThreadSync = EGL_NO_SYNC_KHR;
2265 surface->ctx.damageThreadId = (pthread_t)0;
2266 surface->feedback.unprocessedFeedback = false;
2267
2268 display->defaultFeedback.unprocessedFeedback = false;
2269
2270 err = create_surface_context(surface);
2271 if (err == EGL_SUCCESS) {
2272 /* This looks like a no-op, but we've replaced the surface's internal
2273 * handle with a new surface, so we need to make it current again. */
2274 pData->egl.makeCurrent(display,
2275 pData->egl.getCurrentSurface(EGL_DRAW),
2276 pData->egl.getCurrentSurface(EGL_READ),
2277 pData->egl.getCurrentContext());
2278
2279 if (surface->ctx.wlStreamResource) {
2280 /* Set client's pendingSwapIntervalUpdate for updating client's
2281 * swapinterval
2282 */
2283 surface->pendingSwapIntervalUpdate = EGL_TRUE;
2284 }
2285 }
2286 }
2287
2288 static void
2289 resize_callback(struct wl_egl_window *window, void *data)
2290 {
2291 WlEglDisplay *display = NULL;
2292 WlEglPlatformData *pData;
2293 WlEglSurface *surface = (WlEglSurface *)data;
2294
2295 if (!window || !surface) {
2296 return;
2297 }
2298
2299 display = surface->wlEglDpy;
2300 if (!wlEglIsWaylandDisplay(display->nativeDpy) ||
2301 !wlEglIsWaylandWindowValid(surface->wlEglWin)) {
2302 return;
2303 }
2304
2305 pData = display->data;
2306
2307 pthread_mutex_lock(&surface->mutexLock);
2308
2309 /* Resize stream only if window geometry has changed */
2310 if ((surface->width != window->width) ||
2311 (surface->height != window->height) ||
2312 (surface->dx != window->dx) ||
2313 (surface->dy != window->dy)) {
2314 if (surface == pData->egl.getCurrentSurface(EGL_DRAW) ||
2315 surface == pData->egl.getCurrentSurface(EGL_READ)) {
2316 wlEglReallocSurface(display, pData, surface);
2317 } else {
2318 surface->isResized = EGL_TRUE;
2319 }
2320 }
2321
2322 pthread_mutex_unlock(&surface->mutexLock);
2323 }
2324
2325 static EGLBoolean validateSurfaceAttrib(EGLAttrib attrib, EGLAttrib value)
2326 {
2327 switch (attrib) {
2328 /* Window-only attributes will be ignored, but we still need to make sure a
2329 * valid value is given */
2330 case EGL_RENDER_BUFFER:
2331 return (value == EGL_BACK_BUFFER) ? EGL_TRUE :
2332 EGL_FALSE;
2333 case EGL_POST_SUB_BUFFER_SUPPORTED_NV:
2334 return (value == EGL_TRUE ||
2335 value == EGL_FALSE) ? EGL_TRUE :
2336 EGL_FALSE;
2337
2338 /* EGL_WIDTH and EGL_HEIGHT shouldn't be specified */
2339 case EGL_WIDTH:
2340 case EGL_HEIGHT:
2341 return EGL_FALSE;
2342
2343 case EGL_PRESENT_OPAQUE_EXT:
2344 return (value == EGL_TRUE ||
2345 value == EGL_FALSE) ? EGL_TRUE :
2346 EGL_FALSE;
2347
2348 /* If attribute is supported/unsupported for both EGL_WINDOW_BIT and
2349 * EGL_STREAM_BIT_KHR, then that will be handled inside the actual
2350 * eglCreateStreamProducerSurfaceKHR() */
2351 default:
2352 return EGL_TRUE;
2353 }
2354 }
2355
2356 static EGLint assignWlEglSurfaceAttribs(WlEglSurface *surface,
2357 const EGLAttrib *attribs)
2358 {
2359 EGLint *int_attribs = NULL;
2360 unsigned int nAttribs = 2; // At least width and height
2361 int i;
2362
2363 if (attribs) {
2364 for (i = 0; attribs[i] != EGL_NONE; i += 2) {
2365 if (!validateSurfaceAttrib(attribs[i], attribs[i + 1])) {
2366 return EGL_BAD_ATTRIBUTE;
2367 }
2368
2369 /* Filter out window-only attributes */
2370 if ((attribs[i] != EGL_RENDER_BUFFER) &&
2371 (attribs[i] != EGL_POST_SUB_BUFFER_SUPPORTED_NV)) {
2372 nAttribs++;
2373 }
2374 }
2375 }
2376
2377 int_attribs = (EGLint *)malloc(((nAttribs * 2) + 1) * sizeof(*int_attribs));
2378 if (!int_attribs) {
2379 return EGL_BAD_ALLOC;
2380 }
2381
2382 nAttribs = 0;
2383
2384 int_attribs[nAttribs++] = EGL_WIDTH; // width at offset 0
2385 int_attribs[nAttribs++] = 0;
2386 int_attribs[nAttribs++] = EGL_HEIGHT; // height at offset 2
2387 int_attribs[nAttribs++] = 0;
2388
2389 if (attribs) {
2390 for (i = 0; attribs[i] != EGL_NONE; i += 2) {
2391 if (attribs[i] == EGL_PRESENT_OPAQUE_EXT) {
2392 surface->presentOpaque = attribs[i + 1];
2393 continue;
2394 }
2395 if ((attribs[i] != EGL_RENDER_BUFFER) &&
2396 (attribs[i] != EGL_POST_SUB_BUFFER_SUPPORTED_NV)) {
2397 int_attribs[nAttribs++] = (EGLint)attribs[i];
2398 int_attribs[nAttribs++] = (EGLint)attribs[i + 1];
2399 }
2400 }
2401 }
2402
2403 int_attribs[nAttribs] = EGL_NONE;
2404
2405 surface->attribs = int_attribs;
2406
2407 return EGL_SUCCESS;
2408 }
2409
2410
2411 EGLBoolean wlEglQuerySurfaceHook(EGLDisplay dpy, EGLSurface eglSurface,
2412 EGLint attribute, EGLint *value)
2413 {
2414 WlEglDisplay *display = wlEglAcquireDisplay(dpy);
2415 WlEglPlatformData *data = NULL;
2416 WlEglSurface *surface = (WlEglSurface *)eglSurface;
2417 EGLint ret = EGL_FALSE;
2418 EGLint err = EGL_SUCCESS;
2419
2420 if (!display) {
2421 return EGL_FALSE;
2422 }
2423 data = display->data;
2424
2425 if (!wlEglIsWlEglSurfaceForDisplay(display, surface)) {
2426 err = EGL_BAD_SURFACE;
2427 wlEglSetError(data, err);
2428 goto done;
2429 }
2430
2431 if (attribute == EGL_PRESENT_OPAQUE_EXT) {
2432 *value = surface->presentOpaque;
2433 ret = EGL_TRUE;
2434 goto done;
2435 }
2436
2437 dpy = display->devDpy->eglDisplay;
2438 ret = data->egl.querySurface(dpy, surface->ctx.eglSurface, attribute, value);
2439
2440 done:
2441 wlEglReleaseDisplay(display);
2442 return ret;
2443 }
2444
2445 EGLBoolean wlEglSurfaceRef(WlEglDisplay *display, WlEglSurface *surface)
2446 {
2447
2448 if (!wlEglIsWlEglSurfaceForDisplay(display, surface) ||
2449 surface->wlEglDpy->initCount == 0) {
2450 return EGL_FALSE;
2451 }
2452
2453 surface->refCount++;
2454
2455 return EGL_TRUE;
2456 }
2457
2458 void wlEglSurfaceUnref(WlEglSurface *surface)
2459 {
2460 surface->refCount--;
2461 if (surface->refCount > 0) {
2462 return;
2463 }
2464
2465 wlEglMutexDestroy(&surface->mutexLock);
2466 wlEglMutexDestroy(&surface->ctx.streamImagesMutex);
2467
2468 if (!surface->ctx.isOffscreen) {
2469 wlEglMutexDestroy(&surface->mutexFrameSync);
2470 pthread_cond_destroy(&surface->condFrameSync);
2471 }
2472
2473 free(surface);
2474
2475 return;
2476 }
2477
2478 static EGLBoolean wlEglDestroySurface(EGLDisplay dpy, EGLSurface eglSurface)
2479 {
2480 WlEglDisplay *display = (WlEglDisplay*)dpy;
2481 WlEglSurface *surface = (WlEglSurface*)eglSurface;
2482
2483 if (!wlEglIsWlEglSurfaceForDisplay(display, surface) ||
2484 display != surface->wlEglDpy) {
2485 return EGL_FALSE;
2486 }
2487
2488 wl_list_remove(&surface->link);
2489 surface->isDestroyed = EGL_TRUE;
2490
2491 // Acquire WlEglSurface lock.
2492 pthread_mutex_lock(&surface->mutexLock);
2493
2494 destroy_surface_context(surface, &surface->ctx);
2495
2496 if (!surface->ctx.isOffscreen) {
2497 WlEglSurfaceCtx *ctx;
2498 WlEglSurfaceCtx *next;
2499
2500 // We only expect a valid wlEglWin to be set when using
2501 // a surface created with EGL_KHR_platform_wayland.
2502 if (wlEglIsWaylandDisplay(display->nativeDpy) &&
2503 wlEglIsWaylandWindowValid(surface->wlEglWin)) {
2504
2505 surface->wlEglWin->driver_private = NULL;
2506 surface->wlEglWin->resize_callback = NULL;
2507 if (surface->wlEglWinVer >= WL_EGL_WINDOW_DESTROY_CALLBACK_SINCE) {
2508 surface->wlEglWin->destroy_window_callback = NULL;
2509 }
2510 }
2511
2512 wl_list_for_each_safe(ctx, next, &surface->oldCtxList, link) {
2513 destroy_surface_context(surface, ctx);
2514 wl_list_remove(&ctx->link);
2515 free(ctx);
2516 }
2517
2518 free(surface->attribs);
2519 }
2520
2521 wlEglDestroyFeedback(&surface->feedback);
2522
2523 if (surface->wlSyncobjSurf) {
2524 wp_linux_drm_syncobj_surface_v1_destroy(surface->wlSyncobjSurf);
2525 wp_linux_drm_syncobj_timeline_v1_destroy(surface->wlAcquireTimeline);
2526 }
2527
2528 if (surface->presentFeedbackQueue != NULL) {
2529 wl_event_queue_destroy(surface->presentFeedbackQueue);
2530 surface->presentFeedbackQueue = NULL;
2531 }
2532 if (surface->throttleCallback != NULL) {
2533 wl_callback_destroy(surface->throttleCallback);
2534 surface->throttleCallback = NULL;
2535 }
2536
2537 /* all proxies using the queue must be destroyed first! */
2538 if (surface->wlEventQueue != NULL) {
2539 wl_event_queue_destroy(surface->wlEventQueue);
2540 surface->wlEventQueue = NULL;
2541 }
2542
2543 if (surface->wlBufferEventQueue) {
2544 /*
2545 * If explicit sync is in use, the stream images are destroyed when
2546 * destroy_surface_context() is called above.
2547 */
2548 WlEglStreamImage *image;
2549 WlEglStreamImage *nextImage;
2550
2551 pthread_mutex_lock(&surface->ctx.streamImagesMutex);
2552 /*
2553 * Destroy any attached buffers to ensure no further buffer release
2554 * events are delivered after the buffer release queue and thread are
2555 * torn down.
2556 *
2557 * Do not destroy the WlEglStreamImages here because they may be
2558 * in-flight and as soon as we unlock streamImagesMutex, the buffer
2559 * release thread may access them.
2560 */
2561 wl_list_for_each(image, &surface->ctx.streamImages, link) {
2562 if (image->buffer) {
2563 assert(image->attached);
2564 wl_buffer_destroy(image->buffer);
2565 image->buffer = NULL;
2566 image->attached = EGL_FALSE;
2567 }
2568 }
2569 pthread_mutex_unlock(&surface->ctx.streamImagesMutex);
2570
2571 finish_wl_buffer_release_thread(surface);
2572
2573 /*
2574 * If there are remaining images in the streamImages list, destroy them
2575 * here safely since the buffer release thread is no longer running.
2576 */
2577 wl_list_for_each_safe(image, nextImage, &surface->ctx.streamImages, link) {
2578 destroy_stream_image(display, surface, image);
2579 }
2580 }
2581 assert(wl_list_empty(&surface->ctx.streamImages));
2582
2583 // Release WlEglSurface lock.
2584 pthread_mutex_unlock(&surface->mutexLock);
2585
2586 wlEglSurfaceUnref(eglSurface);
2587
2588 return EGL_TRUE;
2589 }
2590
2591 static void
2592 destroy_callback(void *data)
2593 {
2594 WlEglSurface *surface = (WlEglSurface*)data;
2595 WlEglDisplay *display = surface->wlEglDpy;
2596
2597 pthread_mutex_lock(&display->mutex);
2598
2599 if (!surface || surface->wlEglDpy->initCount == 0) {
2600 pthread_mutex_unlock(&display->mutex);
2601 return;
2602 }
2603
2604 wlEglDestroySurface((EGLDisplay)surface->wlEglDpy,
2605 (EGLSurface)surface);
2606 pthread_mutex_unlock(&display->mutex);
2607 }
2608
2609 static void
2610 getWlEglWindowVersionAndSurface(struct wl_egl_window *window,
2611 long int *version,
2612 struct wl_surface **surface)
2613 {
2614 /*
2615 * Given that wl_egl_window wasn't always a versioned struct, and that
2616 * 'window->version' replaced 'window->surface', we must check whether
2617 * 'window->version' is actually a valid pointer. If it is, we are dealing
2618 * with a wl_egl_window from an old implementation of libwayland-egl.so
2619 */
2620
2621 *version = window->version;
2622 *surface = window->surface;
2623
2624 if (wlEglMemoryIsReadable((void *)window->version,
2625 sizeof (void *))) {
2626 *version = 0;
2627 *surface = (struct wl_surface *)(window->version);
2628 }
2629 }
2630
2631 static bool
2632 wlEglInitializeSurfaceCommon(WlEglDisplay *display,
2633 WlEglSurface *surface,
2634 EGLConfig config)
2635 {
2636 surface->wlEglDpy = display;
2637 surface->eglConfig = config;
2638 surface->syncPoint = 1;
2639 surface->refCount = 1;
2640 surface->isDestroyed = EGL_FALSE;
2641 wl_list_init(&surface->ctx.streamImages);
2642 wl_list_init(&surface->oldCtxList);
2643
2644 return wlEglInitializeMutex(&surface->ctx.streamImagesMutex);
2645 }
2646
2647 EGLSurface wlEglCreatePlatformWindowSurfaceHook(EGLDisplay dpy,
2648 EGLConfig config,
2649 void *nativeWin,
2650 const EGLAttrib *attribs)
2651 {
2652 WlEglDisplay *display = wlEglAcquireDisplay(dpy);
2653 WlEglPlatformData *data = NULL;
2654 WlEglSurface *surface = NULL;
2655 WlEglSurface *existingSurf = NULL;
2656 struct wl_egl_window *window = (struct wl_egl_window *)nativeWin;
2657 struct wl_surface *wsurf = NULL;
2658 long int wver = 0;
2659 EGLBoolean res = EGL_FALSE;
2660 EGLint err = EGL_SUCCESS;
2661 EGLint surfType;
2662 int drmSyncobjFd = -1;
2663
2664 if (!display) {
2665 return EGL_NO_SURFACE;
2666 }
2667 pthread_mutex_lock(&display->mutex);
2668
2669 data = display->data;
2670
2671 if (display->initCount == 0) {
2672 err = EGL_NOT_INITIALIZED;
2673 goto fail;
2674 }
2675
2676 dpy = display->devDpy->eglDisplay;
2677
2678 if (!wlEglIsWaylandWindowValid(window)) {
2679 err = EGL_BAD_NATIVE_WINDOW;
2680 goto fail;
2681 }
2682
2683 // Check for existing associated surface
2684 if (window->driver_private != NULL) {
2685 err = EGL_BAD_ALLOC;
2686 goto fail;
2687 }
2688
2689 getWlEglWindowVersionAndSurface(window, &wver, &wsurf);
2690 if (wsurf == NULL) {
2691 err = EGL_BAD_ALLOC;
2692 goto fail;
2693 }
2694
2695 // Make sure that we don't have any existing EGLSurfaces for this
2696 // wl_surface. The driver_private check above isn't sufficient for this: If
2697 // the app calls wl_egl_window_create more than once on the same
2698 // wl_surface, then it would get multiple wl_egl_window structs.
2699 wl_list_for_each(existingSurf, &display->wlEglSurfaceList, link) {
2700 if (existingSurf->wlSurface == wsurf) {
2701 err = EGL_BAD_ALLOC;
2702 goto fail;
2703 }
2704 }
2705
2706 res = data->egl.getConfigAttrib(dpy, config, EGL_SURFACE_TYPE, &surfType);
2707
2708 if (!res || !(surfType & EGL_STREAM_BIT_KHR)) {
2709 err = EGL_BAD_CONFIG;
2710 goto fail;
2711 }
2712
2713 if (!display->devDpy->exts.stream ||
2714 (!display->devDpy->exts.stream_cross_process_fd &&
2715 !display->devDpy->exts.stream_remote) ||
2716 !display->devDpy->exts.stream_producer_eglsurface) {
2717 err = EGL_BAD_ALLOC;
2718 goto fail;
2719 }
2720
2721 surface = calloc(1, sizeof(*surface));
2722 if (!surface) {
2723 err = EGL_BAD_ALLOC;
2724 goto fail;
2725 }
2726
2727 if (!wlEglInitializeSurfaceCommon(display, surface, config)) {
2728 err = EGL_BAD_ALLOC;
2729 goto fail;
2730 }
2731
2732 if (!wlEglInitializeMutex(&surface->mutexLock)) {
2733 err = EGL_BAD_ALLOC;
2734 goto fail;
2735 }
2736
2737 if (!wlEglInitializeMutex(&surface->mutexFrameSync)) {
2738 err = EGL_BAD_ALLOC;
2739 goto fail;
2740 }
2741
2742 if (pthread_cond_init(&surface->condFrameSync, NULL)) {
2743 err = EGL_BAD_ALLOC;
2744 goto fail;
2745 }
2746
2747 surface->wlEglWin = window;
2748 surface->ctx.eglStream = EGL_NO_STREAM_KHR;
2749 surface->ctx.eglSurface = EGL_NO_SURFACE;
2750 surface->ctx.isOffscreen = EGL_FALSE;
2751 surface->isSurfaceProducer = EGL_TRUE;
2752 // FIFO_LENGTH == 1 to set FIFO mode, FIFO_LENGTH == 0 to set MAILBOX mode
2753 // We set two here however to bump the "swapchain" count to 4 on Wayland.
2754 // This is done to better match what Mesa does, as apparently 4 is the
2755 // expectation on wayland.
2756 // https://gitlab.freedesktop.org/mesa/mesa/-/issues/6249#note_1328923
2757 //
2758 // The problem users are running into is that we always have to advance to
2759 // a new buffer (in PresentCore) because the driver always expects to be
2760 // incremented to the next valid buffer as part of swapbuffers. So
2761 // currently it seems one of the three images will always be owned by the
2762 // driver (either the buffer currently/just rendered to, or the one we just
2763 // advanced to for future rendering)
2764 //
2765 // So the three buffers are used up by:
2766 // 1. One buffer owned by the driver
2767 // 2. One buffer that just got committed and shared with the compositor
2768 // 3. One buffer owned by the compositor, pending a release
2769 //
2770 // For whatever reason Kwin is holding onto 2 and 3 indefinitely when the
2771 // dock gets hidden, and we hold onto 1 and try waiting for one of the
2772 // other two to become free. We need a fourth to allow us to continue feeding
2773 // the driver .
2774 surface->fifoLength = (display->devDpy->exts.stream_fifo_synchronous &&
2775 display->devDpy->exts.stream_sync) ? 2 : 0;
2776
2777 // Create per surface wayland queue
2778 surface->wlEventQueue = wl_display_create_queue(display->nativeDpy);
2779
2780 surface->wlEglWinVer = wver;
2781 surface->wlSurface = wsurf;
2782
2783 err = assignWlEglSurfaceAttribs(surface, attribs);
2784 if (err != EGL_SUCCESS) {
2785 goto fail;
2786 }
2787
2788 /*
2789 * If the compositor supports it, then we can request a dmabuf feedback
2790 * object for this surface. This will let the compositor give us per-surface
2791 * hints about which modifiers to use.
2792 */
2793 if (display->dmaBufProtocolVersion >= 4) {
2794 struct zwp_linux_dmabuf_v1 *wrapper = wl_proxy_create_wrapper(display->wlDmaBuf);
2795 wl_proxy_set_queue((struct wl_proxy *)wrapper, surface->wlEventQueue);
2796
2797 surface->feedback.wlDmaBufFeedback =
2798 zwp_linux_dmabuf_v1_get_surface_feedback(wrapper, surface->wlSurface);
2799
2800 wl_proxy_wrapper_destroy(wrapper);
2801
2802 if (!surface->feedback.wlDmaBufFeedback ||
2803 WlEglRegisterFeedback(&surface->feedback)) {
2804 err = EGL_BAD_ALLOC;
2805 goto fail;
2806 }
2807 /* Do a roundtrip to get the tranches before calling create_surface_context */
2808 if (wl_display_roundtrip_queue(display->nativeDpy, surface->wlEventQueue) < 0) {
2809 err = EGL_BAD_ALLOC;
2810 goto fail;
2811 }
2812
2813 /* We haven't allocated our surface yet, so we can clear this flag. */
2814 surface->feedback.unprocessedFeedback = false;
2815 }
2816
2817 if (display->wlDrmSyncobj) {
2818 /* Create a DRM timeline and share it with the compositor */
2819 drmSyncobjFd = create_syncobj_timeline(display, &surface->drmSyncobjHandle);
2820 if (drmSyncobjFd < 0) {
2821 goto fail;
2822 }
2823
2824 /* Get a per-surface explicit sync object, share our DRM syncobj with the compositor */
2825 surface->wlSyncobjSurf =
2826 wp_linux_drm_syncobj_manager_v1_get_surface(display->wlDrmSyncobj, surface->wlSurface);
2827
2828 surface->wlAcquireTimeline =
2829 wp_linux_drm_syncobj_manager_v1_import_timeline(display->wlDrmSyncobj, drmSyncobjFd);
2830 close(drmSyncobjFd);
2831 drmSyncobjFd = -1;
2832
2833 if (!surface->wlSyncobjSurf || !surface->wlAcquireTimeline) {
2834 err = EGL_BAD_ALLOC;
2835 goto fail;
2836 }
2837 }
2838
2839 err = create_surface_context(surface);
2840 if (err != EGL_SUCCESS) {
2841 goto fail;
2842 }
2843
2844 surface->swapInterval = 1; // Default swap interval is 1
2845
2846 if (surface->ctx.wlStreamResource) {
2847 /* Set client's pendingSwapIntervalUpdate for updating client's
2848 * swapinterval
2849 */
2850 surface->pendingSwapIntervalUpdate = EGL_TRUE;
2851 }
2852 window->driver_private = surface;
2853 window->resize_callback = resize_callback;
2854 if (surface->wlEglWinVer >= WL_EGL_WINDOW_DESTROY_CALLBACK_SINCE) {
2855 window->destroy_window_callback = destroy_callback;
2856 }
2857
2858 wl_list_insert(&display->wlEglSurfaceList, &surface->link);
2859 pthread_mutex_unlock(&display->mutex);
2860 wlEglReleaseDisplay(display);
2861
2862 return surface;
2863
2864 fail:
2865 if (drmSyncobjFd > 0) {
2866 close(drmSyncobjFd);
2867 }
2868
2869 if (surface) {
2870 if (surface->drmSyncobjHandle) {
2871 drmSyncobjDestroy(display->drmFd, surface->drmSyncobjHandle);
2872 }
2873 wlEglDestroySurface(display, surface);
2874 }
2875
2876 pthread_mutex_unlock(&display->mutex);
2877 wlEglReleaseDisplay(display);
2878
2879 wlEglSetError(data, err);
2880
2881 return EGL_NO_SURFACE;
2882 }
2883
2884 EGLSurface wlEglCreatePlatformPixmapSurfaceHook(EGLDisplay dpy,
2885 EGLConfig config,
2886 void *nativePixmap,
2887 const EGLAttrib *attribs)
2888 {
2889 WlEglDisplay *display = (WlEglDisplay*)dpy;
2890 (void) config;
2891 (void) nativePixmap;
2892 (void) attribs;
2893
2894 /* Wayland does not support pixmap types. See EGL_EXT_platform_wayland. */
2895 wlEglSetError(display->data, EGL_BAD_PARAMETER);
2896 return EGL_NO_SURFACE;
2897 }
2898
2899 EGLSurface wlEglCreatePbufferSurfaceHook(EGLDisplay dpy,
2900 EGLConfig config,
2901 const EGLint *attribs)
2902 {
2903 WlEglDisplay *display = wlEglAcquireDisplay(dpy);
2904 WlEglPlatformData *data = NULL;
2905 WlEglSurface *surface = NULL;
2906 EGLSurface surf = EGL_NO_SURFACE;
2907 EGLint err = EGL_SUCCESS;
2908
2909 if (!display) {
2910 return EGL_NO_SURFACE;
2911 }
2912 pthread_mutex_lock(&display->mutex);
2913
2914 data = display->data;
2915
2916 /* Nothing really special needs to be done. Just fall back to the driver's
2917 * Pbuffer surface creation function */
2918 dpy = display->devDpy->eglDisplay;
2919 surf = data->egl.createPbufferSurface(dpy, config, attribs);
2920
2921 if (surf == EGL_NO_SURFACE) {
2922 goto fail;
2923 }
2924
2925 surface = calloc(1, sizeof(*surface));
2926 if (!surface) {
2927 err = EGL_BAD_ALLOC;
2928 goto fail;
2929 }
2930
2931 if (!wlEglInitializeSurfaceCommon(display, surface, config)) {
2932 err = EGL_BAD_ALLOC;
2933 goto fail;
2934 }
2935
2936 surface->ctx.eglSurface = surf;
2937 surface->ctx.isOffscreen = EGL_TRUE;
2938
2939 wl_list_insert(&display->wlEglSurfaceList, &surface->link);
2940 pthread_mutex_unlock(&display->mutex);
2941 wlEglReleaseDisplay(display);
2942
2943 return surface;
2944
2945 fail:
2946 pthread_mutex_unlock(&display->mutex);
2947 wlEglReleaseDisplay(display);
2948
2949 if (err != EGL_SUCCESS) {
2950 wlEglSetError(data, err);
2951 }
2952 return EGL_NO_SURFACE;
2953 }
2954
2955 EGLSurface wlEglCreateStreamProducerSurfaceHook(EGLDisplay dpy,
2956 EGLConfig config,
2957 EGLStreamKHR stream,
2958 const EGLint *attribs)
2959 {
2960 WlEglDisplay *display = wlEglAcquireDisplay(dpy);
2961 WlEglPlatformData *data = NULL;
2962 WlEglSurface *surface = NULL;
2963 EGLSurface surf = EGL_NO_SURFACE;
2964 EGLint err = EGL_SUCCESS;
2965
2966 if (!display) {
2967 return EGL_NO_SURFACE;
2968 }
2969 pthread_mutex_lock(&display->mutex);
2970
2971 data = display->data;
2972
2973 /* Nothing really special needs to be done. Just fall back to the driver's
2974 * stream producer surface creation function */
2975 dpy = display->devDpy->eglDisplay;
2976 surf = data->egl.createStreamProducerSurface(dpy, config, stream, attribs);
2977
2978 if (surf == EGL_NO_SURFACE) {
2979 goto fail;
2980 }
2981
2982 surface = calloc(1, sizeof(*surface));
2983 if (!surface) {
2984 err = EGL_BAD_ALLOC;
2985 goto fail;
2986 }
2987
2988 if (!wlEglInitializeMutex(&surface->mutexLock)) {
2989 err = EGL_BAD_ALLOC;
2990 goto fail;
2991 }
2992
2993 surface->wlEglDpy = display;
2994 surface->eglConfig = config;
2995 surface->ctx.eglSurface = surf;
2996 surface->ctx.isOffscreen = EGL_TRUE;
2997 surface->refCount = 1;
2998 surface->isDestroyed = EGL_FALSE;
2999 wl_list_init(&surface->oldCtxList);
3000
3001 wl_list_insert(&display->wlEglSurfaceList, &surface->link);
3002 pthread_mutex_unlock(&display->mutex);
3003 wlEglReleaseDisplay(display);
3004
3005 return surface;
3006
3007 fail:
3008 pthread_mutex_unlock(&display->mutex);
3009 wlEglReleaseDisplay(display);
3010 if (err != EGL_SUCCESS) {
3011 wlEglSetError(data, err);
3012 }
3013 return EGL_NO_SURFACE;
3014 }
3015
3016 EGLBoolean wlEglDestroySurfaceHook(EGLDisplay dpy, EGLSurface eglSurface)
3017 {
3018 WlEglDisplay *display = wlEglAcquireDisplay(dpy);
3019 EGLint ret = EGL_FALSE;
3020
3021 if (!display) {
3022 return EGL_FALSE;
3023 }
3024 pthread_mutex_lock(&display->mutex);
3025
3026 if (display->initCount == 0) {
3027 wlEglSetError(display->data, EGL_NOT_INITIALIZED);
3028 goto done;
3029 }
3030
3031 ret = wlEglDestroySurface(dpy, eglSurface);
3032 if (!ret) {
3033 wlEglSetError(display->data, EGL_BAD_SURFACE);
3034 }
3035
3036 done:
3037 pthread_mutex_unlock(&display->mutex);
3038 wlEglReleaseDisplay(display);
3039 return ret;
3040 }
3041
3042
3043 EGLBoolean wlEglDestroyAllSurfaces(WlEglDisplay *display)
3044 {
3045 WlEglSurface *surface, *next;
3046 EGLBoolean res = EGL_TRUE;
3047
3048 wl_list_for_each_safe(surface, next, &display->wlEglSurfaceList, link) {
3049 if (surface->wlEglDpy == display) {
3050 res = wlEglDestroySurface(display, surface) && res;
3051 }
3052 }
3053
3054 return res;
3055 }
3056
3057 EGLBoolean wlEglQueryNativeResourceHook(EGLDisplay dpy,
3058 void *nativeResource,
3059 EGLint attribute,
3060 int *value)
3061 {
3062 struct wl_eglstream_display *wlStreamDpy = NULL;
3063 struct wl_eglstream *wlStream = NULL;
3064 EGLBoolean res = EGL_FALSE;
3065 EGLint originY;
3066
3067 wlExternalApiLock();
3068
3069 wlStreamDpy = wl_eglstream_display_get(dpy);
3070 if (!wlStreamDpy) {
3071 goto done;
3072 }
3073
3074 wlStream = wl_eglstream_display_get_stream(
3075 wlStreamDpy,
3076 (struct wl_resource *)nativeResource);
3077 if(!wlStream) {
3078 goto done;
3079 }
3080
3081 switch (attribute) {
3082 case EGL_WIDTH:
3083 *value = (int)wlStream->width;
3084 res = EGL_TRUE;
3085 goto done;
3086 case EGL_HEIGHT:
3087 *value = (int)wlStream->height;
3088 res = EGL_TRUE;
3089 goto done;
3090 case EGL_WAYLAND_Y_INVERTED_WL:
3091 if (wlStreamDpy->exts.stream_origin &&
3092 wlStreamDpy->data->egl.queryStream(wlStreamDpy->eglDisplay,
3093 wlStream->eglStream,
3094 EGL_STREAM_FRAME_ORIGIN_Y_NV,
3095 &originY)) {
3096 /* If we have an image with origin at the top, the wayland
3097 * compositor will consider it as y-inverted */
3098 *value = (int)((originY == EGL_TOP_NV) ? EGL_TRUE : EGL_FALSE);
3099 } else {
3100 /* No mechanism found to query frame orientation. Set to
3101 * stream's default value.*/
3102 *value = (int)wlStream->yInverted;
3103 }
3104 res = EGL_TRUE;
3105 goto done;
3106 }
3107
3108 done:
3109 wlExternalApiUnlock();
3110 return res;
3111 }